New navigation issue for jQuery ancestors

Sorry for the main question, but I'm trying to add a hover state to a navigation list and can't figure out how to have a hover state over a child without affecting the parent <li>

. The parent is <li>

technically frozen too. I know which is .add/removeClass()

more ideal, but for my testing it was easier with .attr()

.

So far I got:

I have a jsfiddle installed at http://jsfiddle.net/gSPkj/ but below is the code -

HTML -

<div id="sidebarNav">
<ul>
    <li class="parent"><a href="page1.html">Page 1</a></li>
    <li class="parent"><a href="page2.html">Page 2</a></li>
    <li class="parent"><a href="page3.html">Page 3</a></li>
    <li class="parent"><a href="page4.html">Page 4</a>
        <ul>
            <li class="child"><a href="subpage_of_4-2.html">Subpage of 4 - 1</a></li>
            <li class="child"><a href="subpage_of_4-2.html">Subpage of 4 - 2</a></li>
        </ul>
    </li>
</ul>

      

jQuery -

    $("#sidebarNav li.parent").hover(function(){
$(this).attr("style","background:#123de1;color:#eb9028;");
},function(){
$(this).attr("style","background:#fff;color:#000;");
});
$("#sidebarNav li.child").hover(function(){
$(this).attr("style","background:#123de1;color:#eb9028;");
$(this).parents(".parent").attr("style","background:#fff;color:#000;");
},function(){
$(this).attr("style","background:#fff;color:#000;");
});

      

+3


source to share


2 answers


It would be easier to orient the anchors and then find the closest li to attach the styles. I would do it like this:

$("#sidebarNav li > a").on('mouseenter mouseleave', function(e) {
    $(this).closest('li').css({
        background: (e.type == 'mouseenter' ? '#123de' : '#fff'),
        color:  (e.type == 'mouseenter' ? '#eb9028' : '#000')
    });
});

      



FIDDLE

+1


source


You can only do this with CSS

a:hover {
    background: #123de1;
    color: #eb9028;
}

      

Changed by JSFiddle

If you really need Javascript you can use event.stopPropagation ()



Prevents the event from bubbles in the DOM tree by preventing parent handlers from being notified of the event.

$("#sidebarNav li.child").hover(function(e){
    e.stopPropagation();
    $(this).attr('style','background:#123de1;color:#eb9028;');
},function(e){
    e.stopPropagation();
    $(this).attr('style','background:#000;color:#fff;');
});

      

Although this still has problems when navigating from child to parent or back.

Changed by JSFiddle

0


source







All Articles