Reputation: 1810
I have the following code:
$(document).ready(function({ $(".click").click(function(){ alert(' The Button Was Clicked !'); }); }));
This works fine.
But If I add an element with the same class to the web page, as shown here:
$('#clicked').click(function(){ $("#area").append("<button class='click'>Click me</button>"); });
Then the event handler I added before to the .click class won't work for this new element.
What's that best way to add event handlers to elements that were added dynamically ?
Upvotes: 6
Views: 15279
Reputation: 72729
UPDATE
It's been a while since I posted this answer and things have changed by now:
$(document).on('click', '.click', function() {
});
Since jQuery 1.7+ the new .on()
should be used and .live()
is deprecated. The general rule of thumb is:
.live()
unless your jQuery version doesn't support .delegate()
..delegate()
unless your jQuery version doesn't support .on()
.Also check out this benchmark to see the difference in performance and you will see why you should not use .live()
.
Below is my original answer:
use either delegate or live
$('.click').live('click', function(){
});
or
$('body').delegate('.click', 'click', function() {
});
Upvotes: 17
Reputation: 21
After jQuery 1.7 the live method just points to .on() method. And I had alot trouble finding out how to bind event handler to element which is appended to the DOM after its loaded.
$('body').live('click', '.click', function(){
//Your code
});
This worked for me. Just a little tip for those having trouble with it also.
Upvotes: 2
Reputation: 5164
In reference to your code, the way to do it would be.
$('.click').live('click', function(){
... do cool stuff here
});
Using the .live() function allows you to dynamically attach event handlers to DOM objects. Have fun!
Upvotes: 5
Reputation: 15835
for all the elements added dynamically to DOM at run time , please use live
Upvotes: 2