Attaching Event Handlers the smart way using Event Bubbling in JavaScript.

I know how much jQuery does tasks easier for a lot of people who are into Web Development. But personally for me, it makes my life complicated more than it makes it easy. Besides I always like to code in vanilla JavaScript because it makes me feel more accomplished.

One of the features of jQuery that vanilla JavaScript lacks unfortunately is the ability to attach Event Handlers to a collection of elements all at once. In JavaScript, to achieve the same functionality you have iterate over the collection attaching the same Event Handler to each item. But what a lot of people don’t know is the magic of Event Bubbling which can be used to achieve the same functionality; sort of!

Now Event Bubbling is not the same concept as attaching Event Handlers to a collection at once. Rather it’s an entirely different concept which can be used to achieve the same functionality. I took this example because it was easier to teach. It’s just one of the things you can do using Event Bubbling. Therefore what I’ll be teaching you is the concept of Event Bubbling with the specified example and then you’ll be free to decide what to do with the knowledge you’ve gained. Read on.

In simple terms, Event Bubbling is the act of firing the same event by all the ancestors of the target element which initially fired the event. So suppose we have the following code.

<div class="grand-parent">
<div class="parent">
<div class="child">Click me!</div>

Now if someone clicks the .child element, then not only the .child element will fire the click event but the .parent as well as the .grand-parent will fire the same click event successively. That is, first the .child element will fire click, then the .parent will do the same, and then the .grand-parent.

This concept is crucial as it will help us achieve the goal we’re looking out for. Let’s look at an example which will help you understand what’s going on under the hood. I’ve created an application which has a list of predefined superhero names. Users can add a superhero name to the list or delete a superhero name from the list. I’ve already coded the application and included the pen. Now let’s work through it. Explanation of the code is done through comments.

As you can see, attaching the Event Handler to the ancestors helps a lot to write short and concise code. One of the reasons I made the Add superhero name functionality is to show you the difference between using Event Bubbling and attaching the Event Handler directly to the target. Cause if you attach it directly to the target, then you have to go through a lot of overhead to find all the proper links to its ancestor elements and its siblings.

Ever since learning Event Bubbling I’m using it more often than I thought I would. Don’t be limited with what I just demonstrated. Try experimenting with these ideas and concepts and come up with new things. And if you do stumble upon them, do share!