jQuery - change border colors of nested divs of same class on mouseover

Fred Mars picture Fred Mars · Mar 10, 2011 · Viewed 9.6k times · Source

My html contains a series of nested divs, each having the same class ("shell") but a unique id.

<div class="shell s01" id="blah">
    <!-- s01 content -->
    <div class="shell s02" id="bar">
        <!-- s02 content -->
        <div class="shell s03" id="wah">
            <!-- s03 content -->
        </div>

        <div class="shell s03" id="foo">
            <!-- s03 content -->
        </div>
    </div>
</div>

I want the border color of a div to change when the mouse enters it, but it should return to its original color when the mouse enters a child div. The jQuery code below changes the border color to blue, but does not return parent div borders to the original color (#8E8DA2) as the mouse enters a child div. Instead, when mousing over an inner div, it and all its ancestors are highlighted. For example, if hovering over "wah" then "blah" and "bar" are highlighted too. I want "blah" and "bar" to revert to the original border color.

I understand that when the mouse is over a child it is over the child's parent as well. But I'm not sure why the 'parent' statement below does not solve the problem.

$('.shell').mouseover(function() {
    $(this).parent('.shell').css('border-color', '#8E8DA2');
    $(this).css('border-color', '#0000FF');
});

$('.shell').mouseout(function() {
    $(this).css('border-color', '#8E8DA2');
});

Any ideas? Thanks!

Answer

Fred Mars picture Fred Mars · Mar 10, 2011

Thanks guys--sorry I don't have enough of a rep yet to vote up answers.

I found a working solution in this other stackoverflow question. The key was to invoke the stopPropagation() method on the mouseover event.

$('.shell').mouseover(function(e) {
    e.stopPropagation();
    $(this).css('border-color', '#0000FF');
})

$('.shell').mouseout(function() {
    $(this).css('border-color', '#8E8DA2');
});