Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How to add event handler to dynamically added HTML elements?

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 ?

like image 657
Arihant Nahata Avatar asked Apr 24 '11 17:04

Arihant Nahata


People also ask

How do you add an event listener after an element was created 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 .

How do you bind change event in jQuery for dynamically added HTML element?

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.

Which method is used to add event handler to any HTML element?

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.


1 Answers

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:

  • Don't use .live() unless your jQuery version doesn't support .delegate().
  • Don't use .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() {

});
like image 101
PeeHaa Avatar answered Nov 14 '22 13:11

PeeHaa