I have something like:
function init(){
$('.btn').click(function(){
//do something;
}
}
And when new content is added via ajax, I’m calling init(), so that click event applies to new buttons. But when I click it once, it captures several clicks (as many times as I called init()). It makes sense, but how to avoid it?
jsFiddle link: http://jsfiddle.net/s2ZAz/8/
Solutions:
* Use $.delegate() – http://api.jquery.com/delegate/
* Use $.live() – http://api.jquery.com/live/
Less preferred, but still, solutions:
* Use $.off() – http://api.jquery.com/off/ or $.unbind() – http://api.jquery.com/unbind/
clicksays, “for every object matching the selector, hook up this click listener”. You probably want something more likedelegatethat says “for every object that will ever match this selector, hook up this listener”.You will still get double callbacks if you call
inittwice, but in this manner, you won’t have to callinittwice, because as new objects are added, they’ll already be assigned to click listeners.Note that
documentabove should be replaced with the nearest persistent ancestor, as per Greg’s comment below.Demo.
Since jQuery 1.7, you can preferably use the
.on()function to achieve the same effect.Demo.