javascriptjqueryhtmlcssfadeto

Jquery fade only one item of a class in


I just tried making a script that fades in a tooltip when you hover a link, image etc.. Everything works fine except the actual fading in of only one tooltip at a time. If it was not clear what i mean: I want to hover an image and show a tooltip right above the image, every other tooltip on the page should not be visible. I know what my mistake is (The hovering of an image fades all tooltips in, because they all have the same class) but i don't know how to fix it. I hope I explained my problem properly and would be very happy if someone could help me. (Please excuse me if my english isn't the best, it is obviously not my mother tongue)

Here is my Code:

$(function() {
$('.button').hover(function() { 
    $('.tooltip').stop().fadeTo("fast", 0.8); 
}, function() { 
    $('.tooltip').fadeTo("fast", 0.0); 
});
});
.wrapper{
    width:90px;
    margin:auto;
    margin-top:10%;
}

.tooltip{
    margin-left: auto;
    margin-right:auto;
    background-color:#34495e;
    color:white;
    border-radius:5px;
    opacity:0.8;
    padding:5px;
    text-align: center;
    font-size:15px;
    font-family: 'Open Sans', sans-serif;
    display: block;
    opacity:0.0;
}

.button img{
    margin-top:5px;
    height:50px;
    width: 50px;
    display:block;
    margin-left:auto;
    margin-right:auto;
}

.button img:hover{
    cursor:pointer;
}
<div class="wrapper">
    <div class="tooltip">
    189k Likes
    </div>
        <div class="button">
        <img src="https://cdn2.iconfinder.com/data/icons/metro-uinvert-dock/256/Twitter_alt_3.png"/>
        </div>
</div>
    
<div class="wrapper">
    <div class="tooltip">
    200 Followers
    </div>
        <div class="button">
        <img src="http://lakemacholidayparks.com.au/wp-content/uploads/2014/09/facebook-icon.png"/>
        </div>

And here is my Code in Action on jsfiddle.net: https://jsfiddle.net/3y8pcv69/


Solution

  • You are selecting all .tooltips when you can just select the previous element from your button which IS the tooltip. So just do:

    $(function() {
        $('.button').hover(function() { 
            $(this).prev('.tooltip').stop().fadeTo("fast", 0.8); 
        }, function() { 
            $(this).prev('.tooltip').fadeTo("fast", 0.0); 
        });
    });
    

    Fiddle