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.
To attach event handlers to the dynamically created button, we need to select the button with a class of btn and add an event listener of click . We're saying that onclick of the button, the p tag with a class of moreInfo should display block .
In short: . bind() will only apply to the items you currently have selected in your jQuery object. . live() will apply to all current matching elements, as well as any you might add in the future. The underlying difference between them is that live() makes use of event bubbling.
on() method: This method attaches events not only to existing elements but also for the ones appended in the future as well. The difference here between on() and live() function is that on() method is still supported and uses a different syntax pattern, unlike the above two methods.
You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With