DEV Community

Cover image for What is Event Bubbling in JavaScript?
Rahul
Rahul

Posted on

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
    </button>
</div>

<script>
    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"); 
    });
</script>
Enter fullscreen mode Exit fullscreen mode

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 😎

Get weekly newsletter of amazing articles i posted this week and some offers or announcement. Subscribe from Here

Top comments (5)

Collapse
 
torbentee profile image
Torben

Hey nice write up!

Short improvement: you have a typo of parent in

var parent = document.getElementById('parnet'); 
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rahxuls profile image
Rahul

Hey thanks man. Typing on phone get's tough.

Collapse
 
dailydevtips1 profile image
Chris Bongers

you can also use pointer-events: none CSS to stop the click from child elements.
Nice article Rahul

Collapse
 
rahxuls profile image
Rahul

Ikr and that's easy.

Collapse
 
imprimph profile image
Jaswanth

Great series of articles🖤