msigman msigman - 7 months ago 22
Javascript Question

Add an OnClick handler with jQuery only once - even if called again

If I assign a handler to the OnClick event of an element twice, the handler will be executed twice. But I want to change this so even if I assign it twice, the handler will only execute one time.

Nonsensical example to demonstrate issue:

$('.button').click(
function(){
alert('here');
});
$('.button').click(
function(){
alert('here');
});


So I've added the handler twice. Now when I click an element with that class, I'd get two alert boxes.

The question is, how do I restrict it so I would only get one alert box?

Answer

If .one() is in fact what you're after (removing the event handler after it has been triggered once) then I believe that's the correct answer. If not, you can unbind the event before binding it:

var myEventHandler = function () {alert('hello')};
$('a').unbind('click', myEventHandler);
$('a').bind('click', myEventHandler);

Should work.

Edit: since this reply keeps getting up votes, I'll add another (better in most cases) solution that will work at least in the OP's case. When dealing with dynamically added content simply use jQuery's on() on a parent element instead of applying the event handler directly on the element.

http://api.jquery.com/on/

Comments