DEV Community

Asifur Rahaman
Asifur Rahaman

Posted on

Explain Event Bubbling and event delegation like water

Top comments (2)

Collapse
 
tusharkashyap63 profile image
Tushar Kashyap

Bubbling happens when an event is actually fired on an element, it will first handle the event on itself, then the event on it's parent(if any) and continue till it reaches the body and the root element.
Imagine you have a P tag inside a DIV tag which is inside the BODY tag, and all three of them have a "click" event listener. Now you click on the P. The event on P will fire first, followed by the event on DIV, followed by the event on BODY.
This is just like the bubbles which rise from the bottom to the top in a carbonated drink, hence the name bubbling.

Collapse
 
tusharkashyap63 profile image
Tushar Kashyap

Event delegation is a technique by which you can add an event listener on a parent element and perform that event on it's child element. This is necessary to understand because you may not have access to the element currently(maybe it is created after an API call return) so you can set the event handler on it's parent which you have created yourself.
Another usecase is that it can save you alot of time if you have numerous same type of elements and you want all of them to have the same event, you can set the event handler on it's parent and use the event.target property to know on which child element the event happened and use it accordingly.