Alexander David Alexander David - 8 days ago 6
CSS Question

hover() event handlers not respecting dynamically changed classes

This is my code:

<li class="dropdown">
...
</li>


$(window).scroll(function() {
if ($(".navbar").offset().top > 70) {
$(".dropdown").addClass("dropdown-collapse").removeClass("dropdown");
} else {
$(".dropdown-collapse").addClass("dropdown").removeClass("dropdown-collapse");
}
});

$(".dropdown-collapse").hover(
function() { $(this).addClass('open') },
function() { $(this).removeClass('open') }
);


When the page load at first time the class for
<li>
is still dropdown and when the page scrolled bellow 70px the class replace with dropdown-collapse. The problem is my hover function doesn't work when the class dropdown replaced with dropdown-class. Please help me guys, thank you.

Answer

Your issue is due to the fact that you attach the hover event handlers on load of the page. The change in the classes on the element has no effect on any event handlers that were already bound. To do what you need to would have to use a delegated event handler, like this:

$(window).scroll(function() {
    var offsetTop = $(".navbar").offset().top;
    $(".dropdown, .dropdown-collapse")
        .toggleClass("dropdown-collapse", offsetTop > 70)
        .toggleClass("dropdown", offsetTop <= 70)
});

$(document).on('mouseenter', '.dropdown-collapse', function() {    
    $(this).addClass('open');
}).on('mouseleave', '.dropdown-collapse', function() {
    $(this).removeClass('open');
});

Note that you could simplify the class switching logic by leaving the .dropdown class on the element permanently and simply switching the behaviour dependant on if the .dropdown-collapse class is present.