Thursday, April 28, 2011

How can I remove the event handler once the click event has fired?

I have a click event I wired up on a div on my page.

Once the click event has fired, I want to unbind the event on that div.

How can I do this? Can I unbind it in the click event handler itself?

From stackoverflow
  • Taken from the jQuery documentation found here:

     $("#unbind").click(function () {
          $("#theone").unbind('click', aClick)
                      .text("Does nothing...");
        });
    
  • Use the "one" function:

    $("#only_once").one("click", function() {
    alert('this only happens once');
    });
    
    Tony k : +1 on using one(). :)
    Russ Cam : one for one too :)
    eyelidlessness : Wow. That's actually one of the cooler things I've seen from jQuery.
  • There's the unbind function documented here:

    http://docs.jquery.com/Events/unbind

    Fits your example :)

  • In plain JavaScript:

    var myDiv = document.getElementById("myDiv");
    
    myDiv.addEventListener('click', clicked, false);
    
    function clicked()
    {
        // Process event here...
    
        myDiv.removeEventListener('click', clicked, false);
    }
    

    Steve

    eyelidlessness : +1 for library-agnostic code.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.