Photo by Susan Q Yin on Unsplash
Event Propagation: Simple explanation to make you understand and never forget the concept again!
Introduction:
Event Propagation is a mechanism that defines how the event travels through the DOM Tree to arrive at the target of the event.
Let's understand this with the help of a simple example below 👇
Event Propagation example:
Let’s say we have three-layer of divs ⇒ outer div, middle div & innermost div
We have a clickable element in the innermost div.
if we click on “Click me!” & print the div where the click event is triggered.
What do you think will print, innermost div, right? Actually, no!
All the divs will be shown in the output. This is “Event Propagation”
Capturing & Bubbling Phase:
When the event travels through the DOM to get to the target, it also captures all the event listeners present on the way, this is referred to as the “Capturing Phase”.
When the event travels back to the top of DOM after getting to the target event, on the way up it also executes all the event handlers for the events triggered in the capturing phase. This is referred to as the “Bubbling Phase”.
Check the below image from tutorialrepublic.com explaining the flow of capturing and bubbling phase
How to prevent the Event Propagation:
Now the thing is if you don’t want such kind of behavior & you want only the target event should be executed, you can use the method “e.stopPropagation()”
This will prevent the above behavior & only the target event will be printed in the console.
Conclusion:
Event Propagation is a very important concept to have in mind. It might create some bugs especially while creating forms and some click events, and without the knowledge of it, you will sit scratching your head trying to figure out what is causing the bug.
Preventing the event propagation and bug created by it is really simple as you saw a simple method of e.stopPropagation(), but that is of no use until you know how event propagation works.
I hope you have now understood Event Propagation and I believe you won't have to look anywhere else to understand the concept.
For any doubts and questions
Follow and DM me on Twitter at anuragmathes08
I am very active on Twitter, I would be happy to help with your queries 💡
Happy Coding! ✌️