![]() |
VOOZH | about |
Event bubbling and event capturing are the two interesting concepts of JavaScript. Before diving deep into these fascinating concepts, let us first know about what an event listener is? An event listener is basically a function that waits for an event to occur. That event can be anything like a mouse click event, submitting a form, pressing keys of a keyboard, etc.
An event listener contains three parameters and it can be defined using the following syntax.
<element>.addEventListener(<eventName>,
<callbackFunction>, {capture : boolean});
Example 1: Let's take an example to understand event bubbling and event capturing.
When we clicked on the div with the child as its id, we should get the output as 'child' on our console. But unexpectedly, we are receiving a different output even we have not clicked on divs with parent and grandparent as their id. The concept of event bubbling comes into the picture. The child div lies inside the parent div as well as in the grandparent div. So, when the child div clicked, we indirectly clicked on both parent div and grandparent div. Thus, propagation is moving from inside to outside in the DOM or we can say events are getting bubble up.
Therefore, the process of propagating from the closest element to the farthest away element in the DOM (Document Object Modal) is called event bubbling.
Example 2: In the above example, let us change the value of the third parameter of addEventListener() and see what changes will be made in the output.
It's clearly visible that the ancestor divs of the child div were printing first and then the child div itself. So, the process of propagating from the farthest element to the closest element in the DOM is called event capturing. Both terms are just opposite of each other.
Example 3: Let's play around more with the code for better understanding.
Output: If we clicked on the div with id child, then this will be the output.
We can see that the event capturing of event listeners happened first and then the event bubbling happened. This means the propagation of event listeners first goes from outside to inside and then from inside to outside in the DOM.
In the above example, we can see a parameter "e" (or sometimes called as "event") in the callback function of addEventListener(). It is an event object which automatically defines when we add an event listener to an element. This object 'e' has a function called stopPropagation() which helps to prevent this annoying behavior.
Example 4: Let's see what will happen when we will click on child div in the below code.
If we clicked on child div, the propagation is stopped on parent div and does not move to grandparent div. Hence, the event bubbling is prevented.
Note: The event capturing can also be prevented using the same way.