I'm just going to go through some of the basic things you need to know before going into the main event.
An event is an action or an occurrence that happens in your system. The simplest example would be the user clicking on a button.
When we are loading HTML pages in browsers, the browser creates a tree-like structure for each page called the DOM. For example, if you have a button inside your body tag, the path to the button element would be html -> body -> button.
When it comes to handling events, modern browsers have three phases.
- Capturing Phase
- Target Phase
- Bubbling Phase
The browser checks to see if the element's outer-most ancestor has an onclick event handler registered on it for the capturing phase, and runs it if so.
The browser checks to see if the target property has an event handler for the click event registered on it, and runs it if so.
Then, if bubbles is true, it propagates the event to the direct parent of the selected element, then the next one, and so on. Otherwise, if bubbles is false, it doesn’t propagate the event to any ancestors of the target.
The browser checks to see if the direct parent of the element selected has an onclick event handler registered on it for the bubbling phase, and runs it if so.
It is hard to grasp the issue by reading the above lines. Let me simplify. Here is the issue we are facing.
Think you have created a UI with two div blocks (Block A and Block B). Block B is placed inside Block A. And you have created event handlers for the click event of both div tags.
Now when you click on Block B, before calling B's event handler, the browser calls A's event handler function. Obviously, this is not what we expected. When we click on B, only the event handler of B should be called.
Luckily, we do have a solution for this. In the event object, we have a function called stopPropogation. You can call this function at the start of the event handler function of B. You will see that only the event handler function of B is getting executed this time.
There could be some use cases where this can be useful. For example, when you have a list of items and you want to do something for all of the items, you will usually have to add event listeners for all the items.
But since you now know the concept of event bubbling, you can just write and assign the event handler for the parent node and see the magic happen.
This concept is called event delegation. You can read more on that in this article.
Thank you for reading the article. Hope you learned something valuable today. And most importantly, stay safe guys 😷