jQuery .live() vs .on() method for adding a click event after loading dynamic html

Sean Thoman picture Sean Thoman · Jan 6, 2012 · Viewed 150.1k times · Source

I am using jQuery v.1.7.1 where the .live() method is apparently deprecated.

The problem I am having is that when dynamically loading html into an element using:

$('#parent').load("http://..."); 

If I try and add a click event afterwards it does not register the event using either of these methods:

$('#parent').click(function() ...); 

or

// according to documentation this should be used instead of .live()
$('#child').on('click', function() ...); 

What is the correct way to achieve this functionality? It only seems to work with .live() for me, but I shouldn't be using that method. Note that #child is a dynamically loaded element.

Thanks.

Answer

jfriend00 picture jfriend00 · Jan 6, 2012

If you want the click handler to work for an element that gets loaded dynamically, then you set the event handler on a parent object (that does not get loaded dynamically) and give it a selector that matches your dynamic object like this:

$('#parent').on("click", "#child", function() {});

The event handler will be attached to the #parent object and anytime a click event bubbles up to it that originated on #child, it will fire your click handler. This is called delegated event handling (the event handling is delegated to a parent object).

It's done this way because you can attach the event to the #parent object even when the #child object does not exist yet, but when it later exists and gets clicked on, the click event will bubble up to the #parent object, it will see that it originated on #child and there is an event handler for a click on #child and fire your event.