Search code examples
javascriptjqueryaddclassjquery-hover

Modifying .hover() after using .addClass() on the same element


So I'm trying to use the .hover() method that only does something if the element being hovered over, DOES NOT have a particular class. It works fine if I add the class to the element in question in HTML. But say I have a click event that uses .addClass() to add the class using jQuery. The hover() method then ignores the class that's been added. Enough rambling. Here is the code.

$('.foo:not(.bar)').hover(function() { 

    someCrap();  //when hovering a over .foo that doesn't also have the class .bar, do someCrap

}

$('.foo').click(function(){

    $(this).addClass('bar'); //after the element .foo gets another class .bar, the hover event written earlier continues to work, WTF

})

any idea guys and girls?


Solution

  • .hover() only adds events to elements that is already created. You need to use .on() for also creating events for future elements. This means that you need to set an parent also. Preferably the parent should be as close as possible to the children that should have the mouse events, to save performance.

    $('#parent').on({
        mouseenter : function() {
            "use strict";
            // Do something
        },
        mouseleave: function() {
            "use strict";
            // Do something
        }
    }, ".foo:not(.bar)");