Adding jQuery Events to Dynamically Created Elements

Recently I was working on an goal planning application that required elements that could be dynamically added that also contained elements that could be dynamically added. I.E. each Goal had multiple obstacles and each obstacle could have multiple solutions, etc.

Using jQuery, had a little plus icon that when clicked, created the first new element. I’m sure everyone has seen this in some application before. So our Goal can now have multiple Obstacles. So we added the same little plus icon to the Obstacle to create multiple Solutions. Then when clicked … nothing.

WTF, mate?

Well, what was happening is that we were adding elements with events after page render. Meaning that since the page was rendered prior to the element being created, the event wasn’t being attached to the element.

Javascript Event Delegation

What is needed is a way to attach an event to an element after the page has been rendered. What was needed, was Event Delegation.

David Walsh has an awesome article that explains how this works in full, but what is essentially happening is that the event gets attached to the parent. Then, using event bubbling, JS analyzes which element was clicked and and then triggers said event as if it were attached to said element.

Pretty fancy pants.

So what did we do?

The code looked like this:

$('.parent').on('click', '.clickedEl', function(e){
//something
});

Pretty straight forward. We attached a click event to the parent, added the element that the user was actually clicking on as a parameter to .on(), and then boom… magic happens. Inside this function we defined the elements that we needed to create on the fly and then,  a switch statement used to detect the parent element and then it created and inserted the child elements where appropriate.

What we had was a simple and reusable way to not only create elements on the fly, but make them interactive to the users as well by attaching events even after page load using Javascript’s bubbling for something other than creating headaches for developers.

Leave a Reply

Your email address will not be published.