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

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

});

Leave a Comment