Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery listener doesn't "listen" to events on DOM elements dynamically created [duplicate]

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?

like image 279
Luca Avatar asked Mar 17 '10 15:03

Luca


People also ask

How do you add an event listener after an element was created dynamically?

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 .

Does jQuery work on dynamic content?

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.

How do you bind a click event to dynamically created elements?

You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.

What method can be used to listen for DOM events?

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.


2 Answers

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.

like image 144
axel_c Avatar answered Oct 21 '22 12:10

axel_c


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.

like image 29
Kevin Redman Avatar answered Oct 21 '22 10:10

Kevin Redman