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 ?
To attach event handlers to the dynamically created button, we need to select the button with a class of btn and add an event listener of click . We're saying that onclick of the button, the p tag with a class of moreInfo should display block .
If you try to bind the elements that are dynamically added to the DOM using the click() method of jQuery, this will not work, because it only binds the click event to elements that exist at the time of the “binding”. To bind the click event to all existing and future elements, use jQuery's on() method.
The addEventListener() method attaches an event handler to the specified element. The addEventListener() method attaches an event handler to an element without overwriting existing event handlers.
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() {
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With