I've a bad-programmed library which is doing this
$(document).on('click','#keep_first_only_button', function(){
I wrote, after this, a piece of code to 'override' this bad behaviour
$("keep_first_only_button").unbind("click");
$("keep_first_only_button").on("click", selectKeepFirstOfAll);
BUT this is not working, then document.click function handler is triggered again
I cannot unbind all click events from document, because disasters will happen in the page.
Which is the right way to proceed in this situation?
EDIT: Sorry for time loosing question, I didn't see the missing '#' in my selector. I'm really sorry !
If a simple event name such as "click" is provided, all events of that type (both direct and delegated) are removed from the elements in the jQuery set.
Use the off() method instead. The unbind() method removes event handlers from selected elements. This method can remove all or selected event handlers, or stop specified functions from running when the event occurs. This method can also unbind event handlers using an event object.
jQuery bind() function is used to attach an event handler to elements, while the unbind() is used to detached an existing event handler from elements.
The removeEventListener() method removes an event handler from an element.
The original event handler was bound as a delegated event, so you can't remove it from $('#keep_first_only_button')
itself. You need to remove it on the document
level.
From the documentation:
To remove specific delegated event handlers, provide a
selector
argument. The selector string must exactly match the one passed to.on()
when the event handler was attached. To remove all delegated events from an element without removing non-delegated events, use the special value"**"
.
In other words, to unbind a delegated event, you should just use the same set of arguments you used to bind them but pass them to off
instead. Since the bound function is anonymous you can't reference it, so you'll have to settle with unbinding all delegated event handlers bound to #keep_first_only_button
on the document
level:
$(document).off('click', '#keep_first_only_button');
EDIT: Looks like the problem was just the missing hash. Odd, I thought you couldn't unbind delegated event handlers using a regular .off()
call...
For anyone wondering ...Mattias Buelens is correct.
If you have the element bound like
$(document).on("click","#element",function(){ });
And want to shut it off later, you have to do it as:
$("#element").click(function(e) {
$(document).off('click', '#element');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With