Event Bubbling, Capturing and Propagation
Hello friends, In this blog, I've tried to explain Event Bubbling, Capturing, and Propagation. Let's see.
Output
Here I've used <div> tag and inside it, I've used <button> tag.
1. Event Bubbling.
Event bubbling goes from child to parent.
let div = document.querySelector("div");
let button = document.querySelector("button");
div.addEventListener("click", function () {
console.log("Div");
});
button.addEventListener("click", function () {
console.log("Button");
});
Console
When I click on the button the "Button" and "Div" is printed in the console.
1st "Button" is printing because <button> is the child element and the "Div" is printing because <div> is the parent element. Event Bubbling goes from child to parent.
2. Event Capturing
This is similar to event bubbling but the difference is it goes from parent to child. For applying this we have to give a third argument to the addEventListener(), that argument will be true.
div.addEventListener("click", function () {
console.log("Div");
}, true);
button.addEventListener("click", function () {
console.log("Button");
}, true);
Console
If we click on the button we can see "Div" is printing 1st because <div> the parent element. And then "Button" is printing because <button> is the child element.
3. stopPropagation
When we are clicking the button the button's event is being triggered but also the parent's event is being triggered. In some cases, we don't want this. So to stop that we use stopPropagation. When we click on the button we get an event. And on that event, we will stop the propagation.
div.addEventListener("click", function () {
console.log("Div");
});
button.addEventListener("click", function (event) {
event.stopPropagation();
console.log("Button1");
});
button.addEventListener("click", function (event) {
console.log("Button2");
});
We can see only "Button1" and "Button2" is printing, and "Div" is not printing b'cze we stop the propagation on the button. So the child doesn't go to the parent.
4. stopImmediatePropagation()
With this, we can stop the propagation immediately.
button.addEventListener("click", function (event) {
event.stopImmediatePropagation();
console.log("Button1");
});
button.addEventListener("click", function (event) {
console.log("Button2");
});
In the output we can see Only "Button1" is printing, b'cze we stop the propagation immediately after 1st event listener, so it won't go ahead.
Thanks for reading,
Hope you liked it.