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: