Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Event bubbling in JavaScript

  • Difficulty Level : Basic
  • Last Updated : 09 Nov, 2021

Event bubbling is a method of event propagation in the HTML DOM API when an event is in an element inside another element, and both elements have registered a handle to that event. It is a process that starts with the element that triggered the event and then bubbles up to the containing elements in the hierarchy. In event bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements.

Syntax: 

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

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. Boolean value indicates event phase. By Default useCapture is false. It means it is in the bubbling phase.

Example 1: This example shows the working of event bubbling in JavaScript.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <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:



Output

After Clicking on the Parent button:

After Clicking on the Parent button

After Clicking on the Child button:

After Clicking on the Child button

After Clicking on the Child button

From above example we understand that in bubbling the innermost element’s event is handled first and then the outer: the <p> element’s click event is handled first, then the <div> element’s click event.




My Personal Notes arrow_drop_up

Start Your Coding Journey Now!