When a DOM object is added after the DOM has loaded, the usual process of binding an event to a specific jQuery object may not be sufficient.

E.g.: Normal binding to a button

$(function() {
  $('#some-id').on('click', function() {
    console.log('button clicked...');
  });
});

But if the button is added dynamically after DOM has loaded, e.g. created by JavaScript, or created by asynchronous postback in ASP.Net, the binding will be lost. Instead of re-binding every time the button is re-created, we can simply bind to the document (always exists) and pass a specific filter, as follows:

$(function() {
  $(document).on("click","#some-id", function() {
    console.log('button clicked...');
  });
});
Published On: August 6, 2018Categories: jQueryTags: