Unraveling Event Bubbling in JavaScript
Tags: javascript, webdev, react, tutorial
Published: 2023-11-07 16:37:13


![Img banner](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aywoa1fal2dm7rnuc896.png)

**Introduction**:
In the world of JavaScript, there are fascinating concepts that underlie the smooth interactivity of web pages. One such concept is "Event Bubbling." If you've ever wondered how events propagate through the Document Object Model (DOM) or how to harness its power for efficient event handling, you're in the right place.

**Understanding Event Bubbling**:
At the heart of event bubbling is the idea that when an event, such as a click, occurs on an element, it doesn't just affect that element alone. It ripples through the DOM, invoking event handlers on ancestor elements. Understanding the flow of events during bubbling is key to mastering this concept.

basically, Event bubbling is the process by which an event triggered on a deeply nested element in the DOM (e.g., a button inside a div inside a section) "bubbles up" through its ancestor elements in the DOM hierarchy. It starts from the target element and travels up to the root of the document. This allows you to capture the event at different levels of the DOM, making it useful for delegation and handling events efficiently.

and other hand
Event capturing is the opposite of event bubbling. It's also known as "trickling." With event capturing, the event is captured at the top of the DOM hierarchy and then trickles down to the target element. While event capturing is less commonly used than event bubbling, it can be useful in certain scenarios, especially when you want to intercept events before they reach their target.


**The Order of Execution**:
Event bubbling follows a predictable order, traveling from the target element up to the root of the DOM tree. We'll delve into this order of execution, helping you gain control over how your event handlers interact and respond to user actions.


![source: Akshay Saini youtube: here he talking about event Direction of Propagation here trickling show Event capturing](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m0p6y3dh7nnttx2wky26.png)


**Direction of Propagation**:
In event bubbling, the event propagates from the target element to its ancestor elements, starting at the target and moving up towards the root. In event capturing, the event travels in the opposite direction: from the root down to the target element.

Understanding event bubbling and event capturing, along with their respective propagation directions, is essential for effective event handling in web development. Depending on your use case, you can choose the phase (bubbling or capturing) that best suits your needs to handle events and create interactive web applications.


now we discus here, at third parameter in 

```
document.getElementById('outer').addEventListener('click', () => { console.log("hello click"); }, true);
```
is a boolean value that controls the event's propagation. In this case, the value is true.

- When set to true, it specifies that the event should be captured during the capturing phase. This means that the event starts from the root of the document and propagates down to the target element. Event capturing is less commonly used than event bubbling, and it's not typically required for most use cases.

- When set to false (or omitted), it indicates that the event should follow the regular event bubbling phase. This means that the event starts at the target element and bubbles up through its ancestor elements in the DOM hierarchy.


**Leveraging Event Delegation**:
One of the most practical applications of event bubbling is event delegation. This technique lets you manage events efficiently on a parent element, reducing the need for numerous event listeners on individual elements. We'll explore how event delegation simplifies event handling and enhances performance.

**Custom Event Systems**:
In the realm of advanced web development, you might find the need to create your custom event systems. Understanding event bubbling is crucial for implementing your own event-driven architecture, providing the flexibility to build robust applications.

**Delegated event handling**:
Delegated event handling is a technique where you attach a single event listener to a common ancestor element of multiple child elements. This listener then handles events for all the child elements. It's an efficient way to manage events on dynamically generated or numerous child elements. Here's a simple example using JavaScript and HTML:

```
<body>
  <ul id="myList">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
  </ul>

  <script>
    // Add a single click event listener to the common parent element (ul)
    document.getElementById('myList').addEventListener('click', function (event) {
      // Check if the clicked element is an li
      if (event.target.tagName === 'LI') {
        // Handle the event for li elements
        alert(`You clicked on ${event.target.innerText}`);
      }
    });
  </script>
</body>
```



> "Explore and Learn: Code Example for Practicing Different Scenarios"

```
<!DOCTYPE html>
<html>
<head>
  <title>Event Bubbling Example</title>
</head>
<body>
  <div id="outer" style="border: 1px solid red;">
    <p>Click me!</p>
  </div>
  <div id="inner" style="border: 1px solid blue;">
    <p>Click me too!</p>
  </div>

  <script>
    // Event handler function
    function handleClick(event) {
      const element = event.target;
      console.log(`Clicked on ${element.tagName}`);
    }

    // Add click event listeners
    document.getElementById('outer').addEventListener('click', handleClick);
    document.getElementById('inner').addEventListener('click', handleClick);
  </script>
</body>
</html>


```