jQuery .live() vs .on() method for adding a click event after loading dynamic html
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.
Try this:
$('#parent').on('click', '#child', function() {
// Code
});
From the $.on()
documentation:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to
.on()
.
Your #child
element doesn't exist when you call $.on()
on it, so the event isn't bound (unlike $.live()
). #parent
, however, does exist, so binding the event to that is fine.
The second argument in my code above acts as a 'filter' to only trigger if the event bubbled up to #parent
from #child
.
$(document).on('click', '.selector', function() { /* do stuff */ });
EDIT: I'm providing a bit more information on how this works, because... words. With this example, you are placing a listener on the entire document.
When you click
on any element(s) matching .selector
, the event bubbles up to the main document -- so long as there's no other listeners that call event.stopPropagation()
method -- which would top the bubbling of an event to parent elements.
Instead of binding to a specific element or set of elements, you are listening for any events coming from elements that match the specified selector. This means you can create one listener, one time, that will automatically match currently existing elements as well as any dynamically added elements.
This is smart for a few reasons, including performance and memory utilization (in large scale applications)
EDIT:
Obviously, the closest parent element you can listen on is better, and you can use any element in place of document
as long as the children you want to monitor events for are within that parent element... but that really does not have anything to do with the question.