Question

I have

HTML:

<div class="test">test</div>
<div class="sdf">sdf</div>
<div class="lol">lol</div> 

CSS:

.hide { display: none; } 

Jquery:

$(document).ready(function(){
    $(".test").on({
        mouseover: function(){
            $(this).next('.lol').addClass('hide');
        },
        mouseout: function(){
            $(this).next('.lol').removeClass('hide');    
        }
    });
});

If I takeout the <div class="sdf">sdf</div> in my html the hover works, but is there a way to make this hover work when there is another div in between test and lol on my html?

Was it helpful?

Solution

The problem is .lol is not the next sibling of .test it is the next sibling of next element.

You can use .siblings() if there is no other lol element within the same parent

$(document).ready(function(){
    $(".test").on({
        mouseover: function(){
            $(this).siblings('.lol').addClass('hide');
        },
        mouseout: function(){
            $(this).siblings('.lol').removeClass('hide');    
        }
    });
});

else use

$(this).next().next('.lol')....

OTHER TIPS

You can simply do it like this, see how it works http://jsfiddle.net/nLybj/4/:

$(document).ready(function(){
    $(".test").hover(function () {
        $(this).nextAll('.lol').toggleClass("hide");
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top