views:

171

answers:

4

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?

+3  A: 

Taken from the jQuery documentation found here:

 $("#unbind").click(function () {
      $("#theone").unbind('click', aClick)
                  .text("Does nothing...");
    });
Tony k
+14  A: 

Use the "one" function:

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

There's the unbind function documented here:

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

Fits your example :)

PepperBob
+1  A: 

In plain JavaScript:

var myDiv = document.getElementById("myDiv");

myDiv.addEventListener('click', clicked, false);

function clicked()
{
    // Process event here...

    myDiv.removeEventListener('click', clicked, false);
}

Steve

Steve Harrison
+1 for library-agnostic code.
eyelidlessness