Sunday 2 June 2019

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





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('delete');


My problem is that the listener doesn't "listen" to these dynamically created elements.



Can anyone shed some light please?


Answer




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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...