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 ?

Answers:

Answer

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() {

});
Answer

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!

Answer

for all the elements added dynamically to DOM at run time , please use live

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

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.