Event Delegation in JavaScript- A better understanding

What is Event Delegation in JavaScript? and how we can implement Event Delegation in JavaScript?

  Shubham Verma      October 14, 2019


Event Delegation in JavaScript- A better understanding

What is Event Delegation in JavaScript? and how we can implement Event Delegation in JavaScript?

I

n the javascript, the event delegation is a strategy that we can use the optimize the performance of our web app corresponding to user events. event delegation is a better technique to handle events in our web app. This is possible because JavaScript has an event bubbled up (propagated) in the hierarchy in the DOM tree. The event delegation concept comes from event bubbling. This means that if event bubbling is possible, event delegation is also possible. If you are using events in your app, then you should know about event delegation and use only one event listener instead of writing more event listeners. But, before learning about event delegation, you must know about event bubbling. I have written an article about event bubbling so please read this first and then come back here.

Event Delegation

Generally, on our webpage, we have a lot of events that handle everything, like click, keyup, input, mouse events, a lot of random events. When our application grows, we need to add more events if we are following the same approach, and then the number of events keeps increasing and our web app keeps getting loaded with lots of events handlers. At some point in time, it causes performance issues and our web app will be slower. You can also call "DOM event delegation". In this the events are dispatched to its target which we can called "event Target", Event bubbling provides the foundation for event delegation in the browser. Event delegation is kind of handling events that bubbles using an event handlers associated with them on a contaner elements.

Let's observe the below example:

In the above examle, if we clicked on any li (IDK,Blogs,Shubham,Verma) element, you can see an alert of Click!, even though you can see in the above code there is no click event handler associated with li on you were clicked.

Did you get it?...... NO............

Don't worry, here we are to clear your all the doubt(s):



Let's see an example in details:

Suppose we have a webpage with five categories and all five categories are attached with event handlers. When we clicked on a category then an alert box will be opened with information. We can perform anything on this click, like redirecting to a separate webpage, console, call a function, etc. Let’s see the code implementation for the above scenario. Write the below code in a file index.html and open it in the browser.

index.html:

Let’s open this file in the browser: ( double click on index.html and open in the browser )

Event Delegation in JavaScript

Opened file in the browser

Great, it works fine... But what is the problem in our above code?

There is no problem in our code, but the problem is that we have five <li> elements and we have attached five event handlers to it.

What if, in the future, our categories increase to N? Will we write N event handlers?

Also in this code:

* Can we remove some code?

* Can we remove some event handlers and achieve what we want?

* Can this task be done by writing less code instead?

* Can we optimize the code?

The answer is: “Yes, we can.” We can write less code and achieve what we want by using event delegation.

Event delegation is, instead of attaching event handlers to each and every child element or the HTML elements individually, we will attach an event directly to its parent element. So, due to event bubbling in JavaScript, this is possible, event delegation can be done.

What will be the change after attaching the event to its parent element? The event happening is that the child element will propagate (bubble up) to its parent and the attached event handler of the parent will listen and the handler function will be invoked.

Let’s implement this into our code. We will make some changes to our index.html, so now our index.html will have the following code:

Now, we can see in the above code that I have removed all the event handlers from the previous code and written just one event handler to the parent element, which is fruits.
And this event handler does the same things that all five previous handlers were doing separately.
Let’s open this file (index.html) in the browser and see the result.

Event Delegation in JavaScript

Optimized ( event delegation ) code execution

This is how we can optimize our code using event delegation and improve code quality.

Pros and Cons of Event Delegation

Pros:

Performance: The event delegation will improve the performance of the app.
Memory: Having more events in our code will take a lot of memory, and using event delegation we will save memory. There are less event handlers to setup and reside in memory.
DOM manipulation: If we implement the event handlers on each and every child element and we have infinite scroll, then every time the child element gets added dynamically, the DOM will update every time. Using event delegation, DOM manipulation will be less.
Code quality: We can improve our code quality and maintenance would be easy.
* Event delegation allows you to avoid adding event listeners to specific nodes; instead, the event listener is added to one parent.
* Better performance and less crashing.
* There’s no need to re-attach handlers after a DOM update.

Cons:


* The child stops propagation. Sometimes, HTML elements stop doing event propagation using stopPropagation(). In this case, the event propagation will be stopped and will not be bubbled up in the hierarchy.
* Not all events bubble up. There are some events that are not bubbled up like blur, focus, window resizing, or scrolling. In this case, using event delegation would be tough.
* There’s a risk, your code could become a performance bottleneck, so keep it as simple, lean as possible you can.

Conclusion

The conclusion is that we need not attach event handlers to all the child elements. Instead, we can attach only one event handler to its parent and handle the function for achieving the goals.


Support our IDKBlogs team


Welcome to IDKBlogs.

If our contents help you and you learned from this platform, please consider supporting what we do.

Thank you.




Strongly Recommended Books For You:

Reading books opens the door to allow in more lights, If we want to know a man of rare intellect, try to know what books he/she reads.

For India:

For Other Countries (United States, United Kingdom, Spain, Italy, Germany, France, Canada, etc)


Thank you

I appreciate you taking the time to read this article. The more that you read, the more things you will know. The more that you learn, the more places you'll go. If you’re interested in Node.js or JavaScript this link will help you a lot.

If you found this article is helpful, then please share this article's link to your friends to whom this is required, you can share this to your technical social media groups also. You can follow us on our social media page for more updates and latest article updates.
To read more about the technologies, Please subscribe us, You'll get the monthly newsletter having all the published article of the last month.



Funny Programming | Idkblogs.com | Shubham Verma

👈

Enjoyed this moment?