What is Event Bubbling in JavaScript?

This post will reveal the mystery of button, how it works when you click it. Let's learn about Event Bubbling in JavaScript.

What does it Mean?

Whenever an event is started, it goes form the deeply nested element to all way up to its ancestors' element to up to its ancestors which lie on top of it.

What are events?

An event is something which makes our JavaScript interact with the HTML page. Just like the "onClick" event of a button.

The element which triggers the event is called "target" ad can be accessed using "event.target()". The current element on which the handler currently runs can be accessed using "this" inside the handler function. Eg:

<div id ="parent">
    <button id="child">
        I am child
    var parent = document.getElementById('parnet'); 
    parent.addEventListener('click', function() {
        alert("Parent is clicked"); 
    var child = document.getElementById('child'); 
    child.addEventListener('click', function(){
        alert("Child is clicked"); 

In this example, we have added an event listener to our parent and child. So when we click on "child" we should see an alert with "Child is clicked" only right? But we see two alert boxes first with a message "Child is clicked" and then with "Parent is clicked".

What happens behind the scenes is that when we trigger the click event on the child, the event propagates up to the parent triggering all the handler on its way. This is called "bubbling".

If we want to stop the propagation at some point, then we have a method called "event.stopPropagation()". This will stop the handler from being called on the particular div. But all other handlers will execute, if we want to stop all the handlers we use "event.stopImmediatePropagation()".

⚡Thanks For Reading | Happy Coding 😎

No Comments Yet