I want to remove an event handler when an event is triggered. I can't use one()
because there are cases when I don't want to remove the event handler. Here's what I mean:
$('#a').on('click',function(){
if(...)
// remove current event handler
});
Edit: I forgot to mention that there are other event handlers attached to $('#a')
. I only want to remove the current one.
jQuery unbind() Method The unbind() method removes event handlers from selected elements.
The removeEventListener() method removes an event handler from an element.
The off() method is most often used to remove event handlers attached with the on() method. As of jQuery version 1.7, the off() method is the new replacement for the unbind(), die() and undelegate() methods.
To unbind an event handler within itself:
$("#a").on("click", function(evt){
if (...)
{
$(this).off(evt);
}
});
It isn't very well documented in .off(), but you can read a better explanation of this "third form" from section "Using the Event Object" in .unbind().
Use .off(), with name spaced event names
$('#a').on('click.myevent', function () {
if (...)
// remove current event handler
$(this).off('click.myevent')
});
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