Alexander David Alexander David - 1 year ago 68
CSS Question

hover() event handlers not respecting dynamically changed classes

This is my code:

<li class="dropdown">

$(window).scroll(function() {
if ($(".navbar").offset().top > 70) {
} else {

function() { $(this).addClass('open') },
function() { $(this).removeClass('open') }

When the page load at first time the class for
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 Source

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() {    
}).on('mouseleave', '.dropdown-collapse', function() {

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download