Last Updated: February 25, 2016
·
2.382K
· bryanmikaelian

Binding events on elements that are dynamically added to the DOM

If your app is like most web apps, it is probably full of AJAX. Suppose you have a page that renders some buttons or links but it also dynamically adds more of those elements as events happen, such as an AJAX pagination event. To top it off, all those elements have events tied to them (think hitting "Like" on a friends Facebook post that was not initially visible on the page.").

How do you handle events for any of those links, regardless when they show up in the DOM?

The standard way works...partially:

$(".awesome-button").on("click", function(e) {
    // do awesome and blow your mind
    // Uh oh. Doesn't work for dynamically added elements
});

Here is what gets you all the way:

$(document).on("click", ".awesome-button", function(event) {
    // do awesome and blow your mind
});

Now all elements, regardless of when they get added to the DOM, will respond to this click event. You can replace ".awesome-button" with your favorite selector.

Pretty cool huh?

1 Response
Add your response

Thank you for the tip. Is this the way framework like d3.js work ? The nodes are dynamically created (svg elements), and we have to bind those elements to evens later.

over 1 year ago ·