JQuery event binding on dynamically created content
It is pretty common to update the html DOM dynamically using ajax in interactive web applications. But the problem arises when the events bound to the existing html elements don’t work for same type of elements created dynamically.
Like there is a case where I have to perform some operations on the click event of a button and I was using jquery’s on method for event binding.
$(document).ready(function(){ $('button .delete-row').on('click', function(){ //execute some code }); });
It worked perfectly for all buttons available at the time of page load, But I was also updating the DOM using some ajax calls and jquery was not able to bind the click event on the buttons created dynamically.
So to fix this issue we need to call the on method on outer elements under which we append the elements dynamically and pass jquery selector as a second argument.
$(document).ready(function() { $(document).on("click","button .delete-row",function(){ // Do something when button is clicked }); });
The difference between both forms of on method is, the first one binds the event to all applicable elements present at the time of its execution and in second form it finds the applicable elements dynamically under the document object and triggers the click event.
We should not use the second form of on as a replacement of the first one because it traverse the child DOM every time we click on the outer element.