What is Event Delegtion in Javascript? Famous Javascript Interview question

 Do you know what is event delegation?

 If this question is asked in an interview you can give these two examples and interviewer will be impressed.


Event Delegation is based on Event bubbling.


Let's understand with example. Suppose we are creating Ecommerce website and there are lot of categories inside it like shoes, clothings, and lot more . When we click on shoes it takes us to different page. if we click on clothings and takes it to a different page. So in each category we have to attach events. What if there are lot of categories this is not good for optimisation then.


So instead of attaching to each category we will try to just attach it to parent element. So because of event bubbling the events are propagating up the hierarchy to the parent element.


Lets understand with code:



Here, the element with id categories is the parent element and element with id laptop, phone and chargers is child element. Now for event delegation we will attach the event at parent element and let's see in code how that works.



Here we have selected parent element and e is the object by which we are able to target the child elements e.target.id gives the id of the child elements when you click on particular li. 

Another Example of Event Delegation

Suppose we have a parent div and there are three input boxes in that, we have to make functionality that whenever we type inside input div so it should be in uppercase.

Lets understand with code:


As we can see parent element is with id form and and child element in which data-uppercase is present we have to make that uppercase text only.


We are selecting the parent element first and then attaching event to it and with the help of e.target.dataset we are targeting child element in which uppercase is present. This is how we use Event delegation in this.

I hope you understood the explanation. Do share it with others.








Comments