cover-img

Event Bubbling

20 January, 2023

2

2

1

In JavaScript, event bubbling is a mechanism by which an event that occurs on an element is also propagated to its parent elements, allowing you to handle events on multiple elements simultaneously.

When an event is triggered on an element, it first runs the event listeners on that element. It bubbles up to its parent element and runs any event listeners on that element, and so on, all the way up to the document. This allows you to handle events on multiple elements with a single event listener on a parent element.

For example, consider the following HTML:

<div id="parent">
<div id="child">
<button id="button">Click me</button>
</div>
</div>

If you want to handle the click event on the button element, you can attach an event listener to the button element itself:

var button = document.getElementById("button");
button.addEventListener("click", function() {
alert("Button was clicked!");
});

But you can also attach the event listener on the parent element, and the event will still fire when the button is clicked:

var parent = document.getElementById("parent");
parent.addEventListener("click", function() {
alert("Button was clicked!");
});

In this example, when the button is clicked, the click event is first handled by the event listener attached to the button, which will display an alert message, and then it bubbles up to the parent element, and the same alert message will be displayed.

Bubbling events can be helpful because it allows you to handle events on multiple elements at once, but they also can be confusing or unexpected. You can use stopPropagation() method on the event object to stop the event from propagating to its parent elements.

For example,

Here is a parent div with its event Listener, which turns its background colour red and a child button inside it with an event Listener, which applies a dashed border.

Before using stopPropagation() , when a click event occurs on the child(i.e. button), the event Listener of the child is triggered as well as that of the parent.

After adding stopPropagation() , when we do the same, both event Listeners are triggered individually respective to their currentTarget.

It's important to note that there are also capturing events, which go from the outermost element to the innermost. You can use addEventListener method with 3rd parameter (useCapture) to choose between bubbling and capturing events.

2

2

1

ShowwcaseHQ

San Francisco, CA, USA

Showwcase is where developers hang out and find new opportunities together as a community
Vedamruta Udavant
I met my love and that is programming !! Currently learning JS :)

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.