Reputation: 3303
I can't unbind event use off.
I was trying to bind click
event, then bind mouseleave
event and callback unbind click
, but not working.
el
is dom create and append by script that's why I use document.on... el
so I tried below include commented code for test not working too.... do I miss understand something?
jquery-1.11.1.min.js
https://jsfiddle.net/70t6jtns/
var el = $('div')
$(document).on('click', el, function() {
console.log('oncli')
});
//$(document).on('mouseleave', el, function() {
//$(document).off('click', el, function() {
//console.log('offcli')
//});
//$(document).off('click', el);
el.off('click');
//});
Upvotes: 1
Views: 3570
Reputation: 31
I was facing the same issue. Because i added the on listener on document and trying off with element. that was the issue in my case.
Upvotes: 0
Reputation: 1074178
First, on
doesn't accept jQuery objects as the second argument, so $(document).on('click', el, function() {...
doesn't make sense.
The main issue is that you're using event delegation in one case but expecting a directly-attached handler in the other case. You're attaching your click
handler to document
, but then trying to detach it from a specific element (el
). You have to remove it from the same thing you attached it to.
If you want to attach the handler to el
and detach it later, use el
consistently as the target:
el.on("click", function() { ...
then
el.off("click");
If the handler has to be delegated, you'll want to be sure, again, that you're removing the same thing you're adding. So for instance,
$(document).on("click", "selector-for-the-element", function() { ...
then
$(document).off("click", "selector-for-the-element");
Upvotes: 8