$('.example').hover(
function () {
$(this).css('background','red');
},
function () {
$(this).css('background','yellow');
}
);
$('.test').click(function(){
$(this).css('marginTop','+=20px').removeClass('example');
}
);
<div class="text example"></div>
Although the class example was seemingly removed, the hover actions for it are still being applied to the element that once had that class. How can I prevent this?
Here it is in jsFiddle. As you can see, after executing the click function to remove the class, the background still changes on hover.
Event handlers are bound to a Node, so it doesn’t matter if that Node doesn’t own a specific className anymore. You would need to
.unbind()those events manually, or better, use jQuerys.off()method.So, if you can be sure that there aren’t any other event handlers bound to that node, just call
This will remove any event handler from that Node. If you need to be specific, you can use jQuerys Event namespacing, like so
and use this call to only unbind any event that is within the namespace
.myNamespace