JQuery: How to add an 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 great.
But if I add an element with the same class to the web page, as shown below:

  $ ('# clicked'). click (function () {
     $ ("# area"). append ("<button class = 'click'> Click me </button>");
 });

Then the event handler that I added earlier to the .click class will not work for this new element.

What is the best way to add event handlers to elements that have been added dynamically?

+6
javascript jquery
source share
4 answers

UPDATE

It has been a while since I posted this answer, and now everything has changed:

$(document).on('click', '.click', function() { }); 

Since jQuery 1.7+ should use the new .on() and .live() deprecated. General rule:

  • Do not use .live() if your jQuery version does not support .delegate() .
  • Do not use .delegate() if your jQuery version does not support .on() .

Also check this criterion to see the difference in performance, and you will see why you should not use .live() .


Below is my original answer:

use delegate or live

 $('.click').live('click', function(){ }); 

or

 $('body').delegate('.click', 'click', function() { }); 
+17
source share

Regarding your code, a way to do this would be.

 $('.click').live('click', function(){ ... do cool stuff here }); 

Using the .live () function allows you to dynamically attach event handlers to DOM objects. Enjoy!

+5
source share

for all elements dynamically added to the DOM at runtime, use live

http://api.jquery.com/live/

+2
source share

After jQuery 1.7, the live method simply points to the .on () method. And I had a lot of problems with how to associate an event handler with an element that is added to the DOM after loading it.

 $('body').live('click', '.click', function(){ //Your code }); 

It worked for me. Just a little advice for those who have problems with it.

+2
source share

All Articles