moomoo
moomoo

Reputation:

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?

Upvotes: 0

Views: 457

Answers (4)

Steve Harrison
Steve Harrison

Reputation: 125480

In plain JavaScript:

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

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

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

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

Steve

Upvotes: 2

PepperBob
PepperBob

Reputation: 707

There's the unbind function documented here:

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

Fits your example :)

Upvotes: 0

cgp
cgp

Reputation: 41381

Use the "one" function:

$("#only_once").one("click", function() {
alert('this only happens once');
});

Upvotes: 14

Anthony
Anthony

Reputation: 7146

Taken from the jQuery documentation found here:

 $("#unbind").click(function () {
      $("#theone").unbind('click', aClick)
                  .text("Does nothing...");
    });

Upvotes: 3

Related Questions