JavaScript Event Bubbling [In-Depth Tutorial]


JavaScript

What is Event Bubbling in JavaScript?

Event bubbling is a term used in JavaScript to describe the behavior of events when they propagate or bubble up the DOM (Document Object Model) tree. In JavaScript, when an event is triggered on an element, it also triggers on all of its parent elements. This behavior can be useful in some situations, but it can also cause unexpected results in others.

Event bubbling occurs when an event is triggered on an element and it is also triggered on all of its parent elements. For example, if you have a button inside a div element, when you click the button, both the button's click event and the div's click event will be triggered. Let’s illustrate event bubbling with some examples such as applying color.

In this article, we will discuss extensively on event bubbling in JavaScript and how to work with it.

 

Example 1: Applying Color

Let's consider the following HTML code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Event Bubbling</title>
    </head>
    <body>
        <div id="container">
            <p id="paragraph">Click me to change my color!</p>
        </div>
    </body>
    <script src="script.js"></script>
</html>

And within the script.js file, we can add event handlers to both the p and div elements to change their background color when clicked:

document
    .getElementById("paragraph")
    .addEventListener("click", function (event) {
        event.target.style.backgroundColor = "yellow";
    });

document
    .getElementById("container")
    .addEventListener("click", function (event) {
        event.target.style.backgroundColor = "lightblue";
    });

Output

event bubbling javascript

When you click the p element, both the p and div elements will change color. This is because the event bubbles up the DOM tree and triggers on both elements.

 

Example 2: Triggering Alert

Let's consider the following HTML code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Event Bubbling</title>
    </head>
    <body>
        <div id="container">
            <p id="paragraph">Click me to show an alert!</p>
        </div>
    </body>
    <script src="script.js"></script>
</html>

We can add event handlers to both the p and div elements to show an alert when clicked via the script.js file.

document
    .getElementById("paragraph")
    .addEventListener("click", function (event) {
        alert("You clicked the paragraph!");
    });

document
    .getElementById("container")
    .addEventListener("click", function (event) {
        alert("You clicked the container!");
    });

Output

When you click the p element, two alerts will be shown. The first one will say "You clicked the paragraph!", and the second one will say "You clicked the container!". This is because the event bubbles up the DOM tree and triggers on both elements.

 

Handling Event Bubbling

Event bubbling can be useful in some situations, such as when you want to attach a single event handler to multiple elements. For example, you can attach a single click event handler to a container element and handle clicks on all its child elements.

document.getElementById("container").addEventListener("click", function(event){
  console.log("You clicked an element inside the container!");
});

Event bubbling is a natural behavior of events in the DOM. It allows us to trigger events from the innermost element to the outermost, making it possible to handle the same event on multiple elements in the DOM tree. However, sometimes, we want to handle an event on a specific element and prevent it from triggering on parent elements.

We can handle event bubbling by creating event handlers for the elements we want to listen to, and then calling the stopPropagation() method or the preventDefault() method.

 

Stop Event Bubbling

However, in other situations, event bubbling can cause unexpected results. To stop event bubbling, you can use the stopPropagation() method or the preventDefault() method.

To stop an event from triggering on parent elements, we need to stop event bubbling. There are two methods we can use to achieve this:

 

Using the stopPropagation() method

The stopPropagation() method stops the event from bubbling up the DOM tree. This method stops the bubbling of the event, but does not prevent the default action of the event.

Let’s illustrate how we can stop event bubbling using the stopProgragation() method on the child element to stop the event from reaching the parent element.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Event Bubbling</title>
    </head>
    <body>
        <div id="container">
            <p id="child">Click me!</p>
        </div>
    </body>
    <script src="script.js"></script>
</html>

In the script.js file

const child = document.querySelector("#child");
const container = document.querySelector("#container");

child.addEventListener("click", function (e) {
    e.stopPropagation();
    console.log("Child element clicked");
});

container.addEventListener("click", function () {
    console.log("Container element clicked");
});

Output

Child element clicked

In this example, when we click on the child element, the stopPropagation() method stops the event from triggering the click event on the container element.

 

Using the preventDefault() method

The preventDefault() method is used to prevent the default behavior of an event. This method stops the bubbling of the event and prevents the default action of the event. To illustrate how we can stop event bubbling in JavaScript, we are going to prevent a link from opening using the preventDefault() method.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Event Bubbling</title>
    </head>
    <body>
        <a href="<https://www.golinuxcloud.com>" id="link">Learn at GoLinuxCloud</a>
    </body>
    <script src="script.js"></script>
</html>

In the script.js file

const link = document.querySelector("#link");

link.addEventListener("click", function (e) {
    e.preventDefault();
    console.log("Link clicked");
});

Output

Link clicked

In this example, when we click on the link, the preventDefault() method stops the event from navigating to the URL specified in the href attribute and instead logs a message to the console.

 

Summary

Event bubbling is a natural behavior of events in the DOM that allows us to trigger events from the innermost element to the outermost. We can handle event bubbling by creating event handlers for the elements we want to listen to. To stop an event from triggering on parent elements, we need to stop event bubbling using the stopPropagation() method or the preventDefault() method. The stopPropagation() method stops the bubbling of the event, but does not prevent the default action of the event. The preventDefault() method stops the bubbling of the event and prevents the default action of the event.

 

References

Event.stopPropagation() - Web APIs | MDN (mozilla.org)
Event.preventDefault() - Web APIs | MDN (mozilla.org)

 

Olorunfemi Akinlua

Olorunfemi Akinlua

He is boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment