The Wayback Machine - https://web.archive.org/web/20250121113654/https://www.geeksforgeeks.org/event-bubbling-in-javascript/
Open In App

Event bubbling in JavaScript

Last Updated : 27 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Event bubbling is a way that events (like clicks or key presses) move through the elements in an HTML document. When an event happens in a specific element (like a button), it first affects that element and then moves up to its parent elements, triggering any event listeners attached to those parents. This process is called “bubbling” because it starts at the bottom (the innermost element) and bubbles up to the top (the outer elements).

How Event Bubbling Works

  • Starting Point: When you interact with an element, such as clicking a button, the event starts with that element.
  • Propagation: The event then moves up through its parent elements in the DOM (Document Object Model) tree, triggering any event listeners that are set up for that event type.
  • Order of Execution: The innermost element’s event listener is executed first, followed by the outer elements in the order they appear in the DOM.

Syntax: 

addEventListener(type, listener, useCapture)
  • type: Use to refer to the type of event.
  • listener: Function we want to call when the event of the specified type occurs.
  • userCapture: Boolean value. The boolean value indicates the event phase. By Default useCapture is false. It means it is in the bubbling phase.

Example: This example we emonstrates event bubbling in JavaScript. When the “Child” button is clicked, both the child and parent event listeners are triggered, displaying alerts. Event bubbling causes the event to propagate up the DOM hierarchy.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <title>Bubbling Event in Javascript</title>
</head>

<body>
    <h2>Bubbling Event in Javascript</h2>

    <div id="parent">
        <button>
            <h2>Parent</h2>
        </button>
        <button id="child">

            <p>Child</p>

        </button>
    </div><br>


    <script>
        document.getElementById(
            "child").addEventListener("click", function () {
                alert("You clicked the Child element!");
            }, false);

        document.getElementById(
            "parent").addEventListener("click", function () {
                alert("You clicked the parent element!");
            }, false);
    </script>

</body>

</html>

Output:

ezgifcom-resize

Example 2: In this example we clicking any of the nested div elements triggers their respective event listeners. Due to event bubbling, the alerts for each div are shown in order from the innermost to the outermost div.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0">
    <title>Event Bubbling Example</title>
    <style>
        #outerDiv {
            padding: 20px;
            background-color: lightblue;
        }

        #middleDiv {
            padding: 20px;
            background-color: lightgreen;
        }

        #innerDiv {
            padding: 20px;
            background-color: lightcoral;
        }
    </style>
</head>

<body>
    <div id="outerDiv">
        Outer Div
        <div id="middleDiv">
            Middle Div
            <div id="innerDiv">
                Inner Div
            </div>
        </div>
    </div>

    <script>
        document.getElementById("outerDiv").addEventListener("click", function () {
            alert("Outer Div clicked");
        });

        document.getElementById("middleDiv").addEventListener("click", function () {
            alert("Middle Div clicked");
        });

        document.getElementById("innerDiv").addEventListener("click", function () {
            alert("Inner Div clicked");
        });
    </script>
</body>

</html>

Output:

bubbling2

Conclusion

Event bubbling allows you to handle events in a hierarchical way, enabling both specific and general event handling. This means you can set up event listeners at different levels of your HTML structure, making your code more efficient.

Event bubbling in JavaScript-FAQs

How can I stop event bubbling in JavaScript?

You can stop event bubbling by calling event.stopPropagation() within an event handler. This prevents the event from propagating to parent elements.

What is the difference between event bubbling and event capturing?

Event bubbling propagates the event from the innermost element to the outermost, while event capturing (or capturing phase) starts from the outermost element and propagates inward. The useCapture parameter in addEventListener controls this.

How do I use addEventListener for event bubbling?

By default, addEventListener listens for events in the bubbling phase. Simply attach an event listener without specifying the useCapture parameter or set it to false.

What is the useCapture parameter in addEventListener?

The useCapture parameter determines whether the event listener is in the capturing phase (true) or bubbling phase (false). By default, it is false, meaning it listens during bubbling.

Can event bubbling be used for delegation?

Yes, event delegation leverages event bubbling by attaching a single event listener to a parent element to manage events for its child elements, making it efficient and reducing the number of event handlers needed.



Next Article

Similar Reads

three90RightbarBannerImg