Wednesday, 14 March 2018

jquery - Event handler not working on dynamic content





I have a tag A in which when clicked on, it appends another tag B to perform an action B on click. So when I click on tag B, action B is performed. However, the .on method does not seems to be working on the dynamically created tag B.



My html and jquery for tag A is as below:



Add Shipping address


$('.add_address').click(function(){
//Add another
$(document).append('
Update');
})


When tag B is clicked, some action B is performed. My jquery is as below:



$('.update').on('click',function(){

//action B
});


I have some non dynamic content which has class ".update" as well. In the .on() method above works fine for the non dynamic content, but not for the dynamic content.



How can I make it work for dynamic content?


Answer



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).




See http://api.jquery.com/on/#direct-and-delegated-events



Change your code to



$(document.body).on('click', '.update' ,function(){


The jQuery set receives the event then delegates it to elements matching the selector given as argument. This means that contrary to when using live, the jQuery set elements must exist when you execute the code.



As this answers receives a lot of attention, here are two supplementary advises :




1) When it's possible, try to bind the event listener to the most precise element, to avoid useless event handling.



That is, if you're adding an element of class b to an existing element of id a, then don't use



$(document.body).on('click', '#a .b', function(){


but use




$('#a').on('click', '.b', function(){


2) Be careful, when you add an element with an id, to ensure you're not adding it twice. Not only is it "illegal" in HTML to have two elements with the same id but it breaks a lot of things. For example a selector "#c" would retrieve only one element with this id.


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...