Dynamically bindable click events

Using JQuery to bind events to elements that do not exist on page load

Nov. 9, 2014, 12:39 p.m.

When building a dynamically AJAX driven web app it is occasionally necessary to bind an event, such as a click, to an element that does not exist in the DOM on page load. Imagine that an AJAX call is made for a newly added object and a button is added to the HTML:

<button class="deleteButton" data-value="1">Delete</button>

In this example we will be using this button to delete an object that was added with the previous AJAX call. Normally, we could use something like this to trigger a click event and delete the object:

$('.deleteButton').click(function() {
    var id = $(this).data('value');
    deleteObject(id); // Our delete an object function

This works perfectly if the deleteButton referenced was in the DOM on page load, but if it was brought in via our AJAX call it won't work. This is because when the event gets bound to the .deleteButton class, this button isn't available yet and isn't bound. However, there is a way to alleviate this problem by using a delegate listener. Lets imagine all of our objects are wrapped in a div with the id of "container". In order to allow dynamically added elements to be bound with our click event we need to use the delegate listener like this:

$('#container').on('click', '.deleteButton', function() {
    var id = $(this).data('value');

We now use the containing div of all of our buttons and ask JQuery to listen for elements with the class "deleteButton" to bind the click event to. Now no matter if the element is in the DOM on page load, or not, the click event will be properly bound.

Comments about Dynamically bindable click events

No one has left a comment yet, be the first to voice your opinion on Dynamically bindable click events!