Reputation: 188
so I'll be short: jquery .off()
doesn't disable a listen I've set with .on
.
html:
<span id="myspan">lol</span>
<button id="b1">jquery On</button>
<button id="b2">jquery Off</button>
js:
$("#b1").on("click", add);
$("#b2").on("click", del);
function add() {
$("#myspan").on("click", function(e) {
var a = 1;
testfunc(a, e);
});
}
function del() {
$("#myspan").off("click", testfunc);
}
function testfunc(num, event) {
alert(num);
}
So first we add to myspan the testfunc()
by clicking the jquery On button. After we do that, if we click on the span, we get an alert. Next, we click the jquery off button. That is supposed to remove the listener but it doesn't. Even after that, when we click on myspan testfunc
is still attached.
Why? And how can I remove it ?
Upvotes: 11
Views: 23774
Reputation: 120
In my case, none of the above solutions worked because the event listener was set on an element with onclick attribute. for unbinding the event I couldn't use off or unbind or something like that. I had to use removeAttr. and it worked for me.
Upvotes: 0
Reputation: 1090
In this simple case, replace your off
call with this:
function del() {
$("#myspan").off("click");
}
You don't need to pass the handler function to the off
call, and if you do, it will only remove that particular handler. However, you did not attach testfunc
, but an anonymous function that just calls testfunc()
. Therefore, your off
call does nothing.
Also, you never assigned the variable testfunc
.
Upvotes: 2
Reputation: 105029
It doesn't because you bound to a different function (anonymous one). And then you're trying to unbind from testfunc
... In order for your event (un)binding to work both parameters between on
and off
must match.
If this is the only click
event listener on the element, then it's be easiest way to unbind from your anonymous function by calling:
$("#myspan").off("click");
If you're binding several event handlers to click event on the same element then you can also distinguish them by providing namespaces and then use proper namespacing in off
call.
$("#myspan").on("click.test", function(e) { ... });
...
$("#myspan").off("click.test");
Or use just namespace if you'd like to unbind several different event handlers that were bound using the same namespace:
$("#myspan").off(".test");
Upvotes: 28
Reputation: 318182
You're not binding the event handler to testfunc
, you're binding it to an anonymous function, and whitin that function you're just calling testfunc
, so you can't automatically unbind that.
It's either
$("#myspan").on("click", testfunc); // bind function
and then
$("#myspan").off("click", testfunc); // unbind function
or to unbind the anonymous function, just
$("#myspan").off("click"); // remove all handlers
or you can also namespace the handler
$("#myspan").on("click.test", function(e) {
var a = 1;
testfunc(a, e);
});
and to remove only that handler
$("#myspan").off("click.test");
Upvotes: 11