I have a listener like this:
$('.delete').click(function() {
...some stuff
});
Also, on the same page, another script dynamically add elements to the DOM in this way:
$('#list').append('<tr><td><a class="delete" href="#">delete</a></td></tr>');
My problem is that the listener doesn't "listen" to these dynamically created elements.
Can anyone shed some light please?
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 .
You have to add the selector parameter, otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content). The jQuery set receives the event then delegates it to elements matching the selector given as argument.
You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.
The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.
It will listen only on elements that existed when you bound the event handler. If you want it to listen to dynamically created elements you want to use the live() function, which works with current and future elements.
EDIT: as of jQuery 1.7, the recommended way is to use the .on() function, which replaces .bind()
, .live()
and .delegate()
by providing all functionality required for attaching event handlers.
Binding events to an element that doesn't yet exist is impossible. The way you can achieve this, as Yogurt the wise expressed, is using 'on' and specifying the selector you wish to use as the second parameter of the function.
this.$someStaticParent.on('click', 'li', functionName);
What this does, is tells the parent element to hold an event for click. Whenever its clicked, it'll check to see WHERE the event came from, if it matches parameter two, it fires an event. This is called event delegation. You are allowing the parent to accept events then firing the events upon a succesful comparison. This is a common design pattern.
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