Event Propagation In Javascript
So what is this 'Event Propagation' that you may have heard of while dealing with the best programming language ( for me at least ๐ ) JavaScript? Well, it is simple. Let's say you have 2 elements, say div, one nested inside the other. Now let's give each of these divs their own id.
<div id="first">
<div id="second">I'm Second!</div>
</div>
Looks OK right? Let's add some styles to our divs.
#first{
padding:20px;
background-color:red;
width:30%;
border-radius:10px;
}
#second{
padding:10px;
background-color:blue;
width:30%;
border-radius:10px;
color:white;
text-align:center;
}
Now lets add a click event to each of them.
const first = document.getElementById('first');
first.addEventListener('click',firstWasClicked);
const second = document.getElementById('second');
second.addEventListener('click',secondWasClicked);
Now let's define these functions.
function firstWasClicked(){
console.log("First");
}
function secondWasClicked(){
console.log("Second");
}
So, what is all this? It's just two event handlers are attached to two elements. And here comes Event Propagation into play. The Event Propagation mode simply helps us define which event is triggered first. Now since the second div is "inside" the first div, clicking on the second div automatically means clicking the first. Now there are two types of event propagation in the HTML DOM API:
- Event Bubbling
- Event Capturing
EVENT BUBBLING
Think of bubbles. Bubbles tend to rise up right? Similarly, if the mode of event propagation is Event Bubbling, the the order of events starts from the inner most element and then "bubbles" out. One thing to note is that by default the mode of event propagation is set to Event Bubbling for most events. But still let's see how it is done "manually". While adding the eventListener simply add a third parameter as false. This is the manual way of enforcing event bubbling.
first.addEventListener('click',firstWasClicked,false);
second.addEventListener('click',secondWasClicked,false);
So if you click on the blue area, you will see the logs on the console in this order:
Second
First
EVENT CAPTURING
Event Capturing or Event Trickling is just the opposite of Event Bubbling. Just like 'trickling' (think of water trickling down), the order of events starts from the outer-most event and then 'trickles' out. To use this mode, simply pass the third parameter as true and see what happens.
first.addEventListener('click',firstWasClicked,true);
second.addEventListener('click',secondWasClicked,true);
Now click on the blue area. The order of the logs would be:
First
Second
So that is it! It is as simple as that. Here is the codepen link so that you can add more elements and see how event propagation works! Thanks for reading!
Subscribe to my newsletter
Read articles from Diganta Kr Banik directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by