Ash
Ash

Reputation: 444

How to unbind and rebind an event based on selector change

This is more a learning piece for me around how event listeners bound to jQuery selectors are handled.

So say I have the following code:

<html>
<div class = "one">one</div>
<div class = "two">two</div>
</html>

<script>
$(".one").click(function() {
$(this).removeClass("one").addClass("two");
console.log("one");
})
$(".two").click(function() {
console.log("two");
})

</script>

On the first click of one, the selector is no longer valid (as the class is now two instead of one). However the event is still bound to this element. This element will also not fire the ".two" handler as this has already been bound.

What would be the easiest way to unbind a handler with the initial click and then rebind afterwards?

Upvotes: 0

Views: 1728

Answers (2)

Gregoire
Gregoire

Reputation: 767

$(".one").unbind("click");
$(".one").bind("click", fn);

You can use unbind() to remove an event added with bind() (or binded like above)

https://jsfiddle.net/7yn7apte/ No re-binding

https://jsfiddle.net/7yn7apte/1/ Re-binding

Well, this answer your question. But, you'd better use on() and off() as bind() calls on() and unbind() calls off().

You can find a more exhaustive explanation here https://stackoverflow.com/a/9113835/6341631

Upvotes: 1

eisbehr
eisbehr

Reputation: 12452

Bind the events on the document, no need to unbind and rebind the events.

$(document).on("click", ".one", function() {
    $(this).removeClass("one").addClass("two");
    console.log("one");
});

$(document).on("click", ".two", function() {
    console.log("two");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="one">one</div>
<div class="two">two</div>

Upvotes: 2

Related Questions