Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Event Bubbling in JavaScript
Next article icon

Event Bubbling in JavaScript

Last Updated : 28 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Event bubbling in JavaScript is a mechanism where an event triggered on a child element propagates upward through its ancestors in the DOM. It allows parent elements to respond to events triggered by their child elements.

  • Propagation Direction: In event bubbling, the event starts at the target element and propagates upward through its parent elements to the root of the DOM.
  • Default Behavior: Event bubbling is enabled by default in JavaScript.
  • Event Listeners: If multiple event listeners are attached in the bubbling phase, they are executed in sequence, starting from the innermost target element.

How Event Bubbling Works?

Event-bubbling-and-capturing
Event Bubbling in JavaScript
  • Event Triggering: The click event is triggered on the child element (button), initiating the event propagation.
  • Event Capturing: In the capturing phase, the event propagates from the root of the DOM down to the target (child). However, no listeners are explicitly set to handle events in this phase in the given code.
  • Event Bubbling: After reaching the target element (child), the event enters the bubbling phase, propagating back up through the DOM tree to the parent (parent).
  • Listener Behavior: Event listeners are attached to both parent and child elements using addEventListener. By default, these listeners respond during the bubbling phase unless the capture option is set to true.
  • Execution Order: When the button is clicked, the child listener executes first (console.log("Child")), followed by the parent listener (console.log("Parent")) as the event bubbles up.

Let's see this with an exmple

HTML
<!--Driver Code Starts--> <html> <head>     <style>         *{             margin: 25px;             box-sizing: border-box;         }         .grandparent{             height: 350px;             width: 350px;             border: 2px solid red;         }         .parent{             height: 250px;             width: 250px;             border: 2px solid blue;         }         .child{             height: 150px;             width: 150px;             border: 2px solid green;         }     </style> </head> <body>     <div class="grandparent" id="one">         Grandparent         <div class="parent" id="two">             Parent             <div class="child" id="three">                 Child             </div>         </div>     </div> <!--Driver Code Ends-->      <script>         let grandparent=document.getElementById('one')         let parent=document.getElementById('two')         let child=document.getElementById('three')         grandparent.addEventListener('click',function(e){                        console.log("Grandparent Clicked")         })         parent.addEventListener('click',function(e){              console.log("Parent Clicked")         })         child.addEventListener('click',function(e){                     console.log("Child Clicked")         })     </script>  <!--Driver Code Starts--> </body> </html> <!--Driver Code Ends--> 
  • Event Bubbling: Clicking the child triggers the event to propagate upward, activating listeners on the parent and grandparent.
  • Console Output: The order is "Child Clicked", "Parent Clicked", "Grandparent Clicked", showing the bubbling flow.
  • Event Object: Each listener receives the event object e, which includes details like e.target and methods like e.stopPropagation().
  • CSS Structure: Visual borders and sizes make the DOM hierarchy and event propagation clear.

How to Stop Event Bubbling?

To stop event bubbling, you can use the event e.stopPropagation() method in the event handler. This prevents the event from propagating to parent elements, so only the target element's event listener is triggered.

HTML
<!--Driver Code Starts--> <html> <head>     <style>         *{             margin: 25px;             box-sizing: border-box;         }         .grandparent{             height: 350px;             width: 350px;             border: 2px solid red;         }         .parent{             height: 250px;             width: 250px;             border: 2px solid blue;         }         .child{             height: 150px;             width: 150px;             border: 2px solid green;         }     </style> </head> <body>     <div class="grandparent" id="one">         Grandparent         <div class="parent" id="two">             Parent             <div class="child" id="three">                 Child             </div>         </div>     </div> <!--Driver Code Ends-->      <script>         let grandparent=document.getElementById('one')         let parent=document.getElementById('two')         let child=document.getElementById('three')         grandparent.addEventListener('click',function(e){             e.stopPropagation()             console.log("Grandparent Clicked")         })         parent.addEventListener('click',function(e){             e.stopPropagation()             console.log("Parent Clicked")         })         child.addEventListener('click',function(e){             e.stopPropagation()             console.log("Child Clicked")         })     </script>  <!--Driver Code Starts--> </body> </html> <!--Driver Code Ends--> 
  • Event Bubbling Stopped: e.stopPropagation() prevents the event from bubbling to parent elements.
  • Independent Logs: Only the clicked element logs its message (e.g., "Child Clicked"), as bubbling is stopped.
  • Nested Visualization: CSS borders clearly show the DOM hierarchy and event flow.
  • Unique IDs: Each element has a unique ID for easy event listener management.
  • Practical Use: Useful for isolating behaviors, like preventing dropdowns or modals from closing when interacting with inner elements.

Use Cases of Event Bubbling

  • Delegated Event Handling: Instead of adding event listeners to multiple child elements, attach one to their parent and handle the events as they bubble up.
JavaScript
document.getElementById('parent').addEventListener('click', (event) => {     console.log('Clicked:', event.target.id); }); 
  • Simplified Code: Reduces redundancy and improves performance when handling events for dynamic or large DOM structures.

Advantages of Event Bubbling

  • Reduces the need for multiple event listeners.
  • Enables delegated event handling for dynamic elements.
  • Simplifies event management for complex structures.

Event Bubbling vs Event Capturing

Event Bubbling

Event Capturing

The event starts at the target element and propagates upward to the root of the DOM.

The event starts at the root of the DOM and propagates downward to the target element.

Event listeners are attached to handle events during the bubbling phase by default.

To handle events in the capturing phase, you must explicitly set the capture option to true in addEventListener.

Often used when you want parent elements to respond to events triggered on child elements (e.g., event delegation).

Useful when you want parent elements to handle the event before it reaches the target element.

Inner (child) elements execute their event listeners first, followed by outer (parent) elements as the event propagates upward.

Outer (parent) elements execute their event listeners first, followed by inner (child) elements as the event propagates downward.

Supported by all modern browsers and has been the default behavior for a long time.

Supported, but less commonly used as it requires the explicit capture option to be enabled.


Next Article
Event Bubbling in JavaScript

K

kg_code
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions
  • JavaScript-Events

Similar Reads

    What is Event Bubbling and Capturing in JavaScript ?
    Events are a fundamental construct of the modern web. They are a special set of objects that allow for signaling that something has occurred within a website. By defining Event listeners, developers can run specific code as the events happen. This allows for implementing complex control logic on a w
    5 min read
    Event Queue in JavaScript
    JavaScript, being single-threaded, processes tasks sequentially, meaning it executes one task at a time. This can pose a challenge when dealing with operations that take time to complete, such as fetching data from a server or performing complex calculations. To handle such scenarios efficiently, Ja
    5 min read
    JavaScript Events
    JavaScript Events are actions or occurrences that happen in the browser. They can be triggered by various user interactions or by the browser itself. HTML<html> <script> function myFun() { document.getElementById( "gfg").innerHTML = "GeeksforGeeks"; } </script> <body> <but
    3 min read
    JavaScript Custom Events
    Events are used in almost every web application, such as the onclick event is used to execute some code when the user clicks on something. There are already numerous built-in events available to be used, but what if we want our custom event? Let us suppose we are creating a chat application, and we
    3 min read
    Timing Events in Javascript
    Timing events are the events that help to execute a piece of code at a specific time interval. These events are directly available in the HTML DOM (Document Object Model) Window object, i.e., they are present in the browser. So, these are called global methods and can be invoked through the 'window'
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences