Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove current event handler in JQuery?

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.

like image 421
Leo Jiang Avatar asked Mar 06 '14 04:03

Leo Jiang


People also ask

Which event is removed in jQuery?

jQuery unbind() Method The unbind() method removes event handlers from selected elements.

Which function is used to remove an existing event handler?

The removeEventListener() method removes an event handler from an element.

What is off () in JavaScript?

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.


2 Answers

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().

like image 99
Glenn Lane Avatar answered Oct 23 '22 12:10

Glenn Lane


Use .off(), with name spaced event names

$('#a').on('click.myevent', function () {
    if (...)
    // remove current event handler
    $(this).off('click.myevent')
});
like image 24
Arun P Johny Avatar answered Oct 23 '22 10:10

Arun P Johny