Jacob
Jacob

Reputation: 15

Removing class from div doesn't stop jquery function

I have a div with the class "item". When I use .removeClass('item') on the div, it doesn't stop it's jquery function from going. Here's my code:

<div class = "item">
   //stuff in here
</div>

And the jquery:

$(".item").mouseenter(function() {
   $(this).find(".clear").show();
});
$(".clear").click(function() {
   $(this).closest("div").removeClass('item');
});

When I remove it's class (and I am removing it successfully, I tested it with some css) it still responds to the jquery code. How can I make it so that it won't respond to that code?

Upvotes: 0

Views: 50

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196187

You need to unbind() the event handler.

Use

$(this).closest("div").removeClass('item').unbind('mouseenter');

Alternatively you can bind the initial event to a container element (or the document) and delegate to it the handling. This way it will indeed not react to clicks once the class has been removed.

Using 1.7 methods

$(document).on('mouseenter','.item',function() {
   $(this).find(".clear").show();
});

Using 1.6 and below methods

$(document).delegate('.item','mouseenter', function() {
   $(this).find(".clear").show();
});

Upvotes: 3

Related Questions