Delete current event handler in jQuery?

I want to remove the event handler when the event fires. I cannot use one() because there are cases when I do not want to remove the event handler. Here is what I mean:

 $('#a').on('click',function(){ if(...) // remove current event handler }); 

Edit: I forgot to mention that other event handlers are attached to $('#a') . I only want to delete the current one.

+7
javascript jquery
source share
3 answers

Use .off () with names located on event names

 $('#a').on('click.myevent', function () { if (...) // remove current event handler $(this).off('click.myevent') }); 
+20
source share

To untie an event handler within itself:

 $("#a").on("click", function(evt){ if (...) { $(this).off(evt); } }); 

This is not well documented at . off () , but you can read the best explanation of this "third form" from the "Using an Event Object" section in . Unbind () .

+6
source share

Can you try the following:

 $('#a').on('click',function(){ if(...) { $(this).unbind('click'); or $(this).off('click') } }); 

Binding and decoupling for backward compatibility. You must enable / disable to detach or attach event handlers

hope this helps.

-one
source share

All Articles