In JavaScript, you must have worked with events. In this article, we are going to learn two concepts of events which is Event Bubbling and Event Capturing. Both of these concepts are related to Event Propagation which is also known as Event Flow.
Introduction
To understand these concepts let's understand what's an event first. As per MDN, definition Events are actions or occurrences that happen in the system you are programming — the system produces (or "fires") a signal of some kind when an event occurs, and provides a mechanism by which an action can be automatically taken (that is, some code running) when the event occurs. You can consider it like you giving a signal to your friend to do something so when you give that signal then your friend starts doing the thing.
There are two main event models: Event Bubbling and Event Capturing.
Now let's understand them one by one-
Event Bubbling
Event Bubbling is the concept of invoking the event handlers where the event handlers are nested in another element. Bubbling happens when an event is actually fired on an element, it will first handle the event on itself, then the event on its parent(if any) and continue till it reaches the body and the root element.
Let's look at an example to understand it -
This is our HTML snippet :
<div id="grandparent">
<div id="parent">
<div id="child"></div>
</div>
</div>
and here we have added the event listeners on them :
grandparent.addEventListener("click", (event) => {
console.log("Grandparent clicked.");
})
parent.addEventListener("click", (event) => {
console.log("parent clicked.");
})
child.addEventListener("click", (event) => {
console.log("child clicked.");
})
Now if we click on the child element we will get an output similar to this :
As we can see here the event is getting triggered from child to parent to grandparent so it means in the Bubbling model event is getting triggered from the innermost element covering all its ancestors along the way. This is just like the bubbles which rise from the bottom to the top in a carbonated drink, hence the name bubbling.
Event Capturing
This is the exact opposite of Bubbling. In the Event Capturing model, an event starts at the least specific element and flows downward toward the most specific element. It means the event will get triggered from grandparent to parent to child.
To use the capturing model you have to pass the true
at the place of the third argument in the addEventListner
function.
Here is the JS code snippet :
grandparent.addEventListener("click", (event) => {
console.log("Grandparent clicked.");
}, true)
parent.addEventListener("click", (event) => {
console.log("parent clicked.");
}, true)
child.addEventListener("click", (event) => {
console.log("child clicked.");
}, true)
You can understand both the models by the following image too.
This is all that I have in my mind, for now, I will add more in the future. Thanks for reading.
Top comments (0)