« Back to home

jQuery: Attach events to elements added dynamically via AJAX

I was building a page where there's an image slideshow that would cycle through the images every n-seconds inside a <div> element. Simple enough.
Everything was working right until I started moving the HTML elements around and parsing them via AJAX response. In short, the images and its container
were being injected into the page dynamically. What I was trying to accomplish was: add the images dynamically including its container <div>, then
apply the setInterval() function routine so it can start the cycling process.

In most case scenarios such as elements performing CRUD (create, update, delete) operations, a link <a /> can subscribe and automatically be assigned
a handler on specific events in a dynamic fashion. For example, when you add a new record and a new row is appended that contains a link that does
something when clicked on. You can attach a handler that will be invoked once it's triggered by an event which in this case, a click event.

That can be accomplished easily via a delegate or live (pre jQuery 1.7):

$('a').live('click hover', function (){
       // do stuff

This is cool for elements where a user initializes the interaction by means
of click or hover. There's edge cases where you just want stuff to happen
right when the dynamic element has been added into the DOM. A really neat
event that I came across with while searching was DOMNodeInserted, where it listens/subscribes when a new DOM node has been added within a
certain context. This gets triggered anytime the DOM within the specific context changes, and is ready to be interacted with. See code below using delegate.
The following code basically attaches a delegate on an element with an id of "main", that has a child element that we're going to attach the event to.

$('#main').delegate('#main-content', 'DOMNodeInserted', function () {
        var dynamicallyAdded = $('img'); // exists
        // do something with the new element

It might be best to do some checking if the element exists for safety measures unless you know for a fact that the element will be injected for sure.
This event works behind the scene and is triggered automatically by DOM changes as opposed to being triggered via a user interaction.
In jQuery 1.7, you can use $.on() instead of delegate or live (might be deprecated in the future release) and it will work the same.

$('#main-content').on('DOMNodeInserted', function () {

It took a while for me to figure this out because it's one of those things that I don't use often, but it's a good starting point or reference for similar
things that I might come across again at a later time. Hope this helps someone looking for a similar solution.


comments powered by Disqus