Let’s say I have some of links that I want to add a javascript action to:
<a class='test'>
<a class='test'>
<a class='test'>
When my page loads I give them all a click event:
$('.test').click(function(){
alert("I've been clicked!")
});
but let’s say afterward I add another element and I want to give it the same event. I can’t do this:
$('.test').click(function(){
alert("I've been clicked!")
});
because then the first 3 will have 2 events on them. What’s the best way to deal with this?
You can bind the $.on to a parent element that will always exist in dom like this.
Note that:
You can replace
documentwith any parent of the element that will always exist in dom, and the closer the parent the better.Simple event binding with
clickwont work asclickbind the event handlers to elements that already exists in dom at the time of binding. And hence it doesn’t work for elements dynamically added to dom later through Ajax or jQuery. For that purpose you have to useevent delegation. And you can use$.onfor that purpose.Check documentation of $.on
You can use
$.livebut $live is depreciated. use $.on instead. Equivalent syntax of $.on for $.live and $.delegate which does the same thingIn this case event handler will be bound to
document. And events will be delegated to target element by jQuery in this casetestclass.UPDATE
I would suggest you to use
$.onfor all event handling purposes as all other methods routes through$.onand$.offmethod under the hood.Check the definition of these functions from jQuery source v.1.7.2
And that is true for these convenient events handlers too
You can see all methods are using
$.onand$.offthemselves. So using$.onyou can at least save a function call though which isn’t that significant in most of the cases.