Event delegation is a pattern of adding an event listener to a parent node instead, of adding an event listener to the individual node. The added event listener will check for the bubbled event to find matching child element. In this article we will talk about how to implement an event listener using very trending method in JavaScript i.e., event delegation pattern.

Let us consider an example where we have ‘ul’ which contains multiple ‘li’ of animals.

 

Now, here we want to perform an action when we click on the animal (li). As a developer first thing we do is adding an event listener to each ‘li’ and perform whatever action needs to be performed as below.

There is nothing wrong with above method, it will work awesome but but but…. What if list is dynamic, and we need to add or remove some of the animals from the list?

We will do it, and we will also add and remove the list values and their associates event listener. But adding hundreds of event listeners is really a bad idea. This way of adding an event listener will also cause a memory leakage issue and will degrade the performance of your code.

What’s the Solution?

Solution is simple, add an event listener to the parent ‘ul’. But after adding a listener to the ‘ul’ how to find which ‘li’ is clicked?

Again, answer is simple: When event is bubbled up to the ‘ul’ element, you can check the target property of your object and it will help you to get which ‘li’ is clicked from the list. If you want to read more about event bubbling and capturing than do visit my previous article here at: http://code4developers.com/event-capturing-bubbling-javascript/

Please consider below code to achieve what we have talked so far.

In above code we are adding event listener to parent element ‘ui’. When the event will be fired we will check the clicked element is ‘LI’ which we can check using ‘e.target.nodeName’. If it is ‘LI’ we are done.

Summary

Most of the developers uses JavaScript library and frameworks like JQuery, AngularJs for their DOM element and event handling. I recommend all of you to use event delegation methods your library or framework is providing. They provide advanced delegation and element identification.

What to read next…

Yatendrasinh Joddha
I am a software engineer currently living in Gandhinagar, India. My interest is in web and software development. I am also interested in sharing my knowledge with people.

I have expertise in asp.net and related Microsoft technologies, with JavaScript frameworks and libraries like JQuery, KnockOut.js,and AngularJS.
Yatendrasinh Joddha on FacebookYatendrasinh Joddha on GithubYatendrasinh Joddha on LinkedinYatendrasinh Joddha on TwitterYatendrasinh Joddha on Wordpress