Saturday, 7 October 2017

Adding event listeners to dynamically added elements using jQuery





So right now, I understand that in order to attach an event listener to a dynamically added element, you have to redefine the listener after adding the element.



Is there any way to bypass this, so you don't have to execute a whole extra block of code?


Answer



Using .on() you can define your function once, and it will execute for any dynamically added elements.



for example



$('#staticDiv').on('click', 'yourSelector', function() {
//do something

});

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...