Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent element from animating based on previous class

$('.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?

http://jsfiddle.net/gSfc3/

Here it is in jsFiddle. As you can see, after executing the click function to remove the class, the background still changes on hover.

like image 963
UserIsCorrupt Avatar asked Jun 28 '26 08:06

UserIsCorrupt


1 Answers

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).css('marginTop','+=20px').removeClass('example').off();

This will remove any event handler from that Node. If you need to be specific, you can use jQuerys Event namespacing, like so

$('.example').on( 'mouseenter.myNamespace'
   function () {
       $(this).css('background','red');
   }
).on('mouseleave.myNamespace'
   function() {
       $(this).css('background','yellow');
   }
);

and use this call to only unbind any event that is within the namespace .myNamespace

$(this).css('marginTop','+=20px').removeClass('example').off('.myNamespace');
like image 54
jAndy Avatar answered Jun 29 '26 21:06

jAndy