Prevent animate an element based on a 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 examplewould seem to have been deleted, the actions hoverfor it still apply to the element that once had this class. How can I prevent this?

http://jsfiddle.net/gSfc3/

Here it is in jsFiddle. As you can see, after executing the function clickto remove the class, the background still changes when it hangs.

+3
source share
4 answers

Event handlers are tied to Node, so it doesn't matter if this Node has its own class name. You will need .unbind()those events manually or better use the jQuerys method .off().

, , , Node, ,

$(this).css('marginTop','+=20px').removeClass('example').off();

Node. , jQuerys Event namespacing,

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

, .myNamespace

$(this).css('marginTop','+=20px').removeClass('example').off('.myNamespace');
+1

$('.example').unbind('mouseenter').unbind('mouseleave')

$('.example').hover .

-or-

on

$(document.body).on('mouseenter', '.example', function() { ... });
$(document.body).on('mouseleave', '.example', function() { ... });

, example , , css, .hover .

0
$('.example').live({
    mouseenter:function () {
        $(this).css('background','red');
    },
    mouseleave:function () {
        $(this).css('background','yellow');
    }
});

demo: http://jsfiddle.net/gSfc3/1/

0

:

$('.test').hover(
    function () {
        $('.example').css('background','red');
    },
    function () {
        $('.example').css('background','yellow');
    }
);
0

All Articles