Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In jQuery, is there any way to only bind a click once?

I have an ajax app that will run functions on every interaction. I'd like to be able to run my setup function each time so all my setup code for that function remains encapsulated. However, binding elements more than once means that the handler will run more than once, which is obviously undesirable. Is there an elegant way in jQuery to call bind on an element more than once without the handler being called more than once?

like image 327
Chris Henry Avatar asked Jun 01 '10 04:06

Chris Henry


3 Answers

User jQuery one function like Tom said, but unbind the handler each time before binding again. It helps to have the event handler assigned to a variable than using an anonymous function.

 var handler = function(e) { // stuff };

 $('#element').unbind('click', handler).one('click', handler);

 //elsewhere
 $('#element').unbind('click', handler).one('click', handler);

You can also do .unbind('click') to remove all click handlers attached to an element.

like image 118
Chetan S Avatar answered Nov 12 '22 03:11

Chetan S


You could attach the event to document with the one() function:

$(document).one('click', function(e) {
    // initialization here
});

Once run, this event handler is removed again so that it will not run again. However, if you need the initialization to run before the click event of some other element, we will have to think of something else. Using mousedown instead of click might work then, as the mousedown event is fired before the click event.

like image 26
Tom Bartel Avatar answered Nov 12 '22 02:11

Tom Bartel


You can also use .off() if unbind doesn't do the trick. Make sure the selector and event given to .off exactly match the ones initially provided to .on():

$("div.selector").off("click", "a.another_selector");    
$("div.selector").on("click", "a.another_selector", function(e){

This is what worked for me in resolving the same ajax reloading problem.

like image 2
Julie Avatar answered Nov 12 '22 03:11

Julie