DEV Community

Iftakhar Alam Rizve
Iftakhar Alam Rizve

Posted on • Updated on

Event Bubbling & Capturing in JS

Event bubbling and capturing are important concepts for JavaScript developers to understand, as they are widely used in the DOM API.

In JavaScript, events are triggered on elements and can either propagate from the innermost element to the outermost elements (Event Bubbling), or from the outermost elements to the innermost element (Event Capturing). This allows developers to handle events at different levels of the DOM hierarchy and make more complex event handling decisions.

It's important to understand the differences between event bubbling and capturing and when to use each, as they can impact the behavior and performance of your event handling logic. By mastering these concepts, developers can write more efficient and effective event handling code in JavaScript.

Prerequisites

  • Basic HTML
  • Familiar with DOM Manipulation in JavaScript

Event Flow

Before understanding Bubbling & Capturing, let's find out how an event is propagated inside the DOM.

The standard DOM Events describes 3 phases of event propagation:

  1. Capture Phase: In JavaScript's DOM API , the capture phase refers to the first phase of the event propagation model. During this phase when user click on target element . the event triggered on the outermost element of the document and propagates the innermost element where the event occurred.
  2. Target Phase: In JavaScript's DOM API , the target phase refers to the second phase of the event propagation model.The event reaches the target element or the element which started the event.
  3. Bubble Phase: This is the reverse of capture.During the bubbling phase, the event is propagated towards the ancestors of the target element until it reaches the top-level ancestor, which is typically the Window object.

Image description

What is Event Bubbling?

Event Bubbling is a type of event propagation in JavaScript that occurs when an event is triggered on an element and moves up the DOM hierarchy to its parent elements. It is the opposite of event capturing, which occurs when events are propagated from the outermost elements to the innermost elements.

In Event Bubbling, events are first captured by the innermost element and then move up the hierarchy, giving all parent elements an opportunity to handle the event. This allows you to attach a single event handler to a parent element and handle events for multiple child elements, rather than having to attach individual event handlers to each child element.

Example for better understanding.

<div class="viewport" onclick="viewportFunction()">       
   <div class="content" onclick="contentFunction()">       
       <button class="button" onclick="buttonFunction()">
          CLick Button Event
       </button>
   </div>       
</div>
Enter fullscreen mode Exit fullscreen mode

In this Code block, when you click the button, an event is triggered and it bubbles up the DOM tree from the button element to the outermost parent element (in this case, the "viewport" element). This is called Event Bubbling.

Event Bubbling allows events to propagate from the innermost element, where they are triggered to the outermost elements in the DOM hierarchy. In other words, if an event is triggered on an inner element, it will be propagated to all its parent elements in order, until it reaches the top-most parent element. This allows you to handle events at multiple levels of the DOM hierarchy, rather than having to attach an event handler to each individual element.

For example, if you have a click event handler attached to both the "button" and the "content" elements, and you click the button, both handlers will be triggered in sequence: first the handler for the button, and then the handler for the content. This allows you to handle events at multiple levels of the DOM hierarchy and make more complex event handling decisions.

Image description

The image you mentioned depicts a nested DOM structure with a button element that has an onclick event. An onclick event is a JavaScript event that is triggered when a user clicks on a specific DOM element . The onclick event is attached to the button element, and when the button is clicked, the code within the event handler function is executed. This event handler function can perform any desired action, such as updating the state of your application or sending an API request.

Image description
This example demonstrates how Event Bubbling works in JavaScript. When you click the button element, the "onclick" event is triggered and the "buttonFunction()" function is called. This function outputs "button function" to the console. After that, the event continues to move up the DOM hierarchy to the parent elements. In this case, the parent element is the "content" div element, which also has an "onclick" event attached to it. This event is triggered and outputs "content function" to the console. The process continues to the next parent element, if there is one, and this flow is called Event Bubbling.

In this way, Event Bubbling allows you to handle events at multiple levels of the DOM hierarchy, giving you more control and flexibility in your event handling logic. It's important to note that the order in which events are triggered during Event Bubbling is determined by the order in which they are registered in the DOM, starting with the innermost element and moving up the hierarchy to the outermost elements.

Full Code block for understanding.

<div class="viewport" onclick="viewportFunction()">       
   <div class="content" onclick="contentFunction()">       
       <button class="button" onclick="buttonFunction()">
          CLick Button Event
       </button>
   </div>       
</div>
Enter fullscreen mode Exit fullscreen mode
  function viewportFunction(){
     //Third Execute This Function 
     console.log("viewportFunction");
  }

  function contentFunction(){
     //Second Execute This Function 
     console.log("contentFunction");
  }

  function buttonFunction(){
     //First Execute This Function 
     console.log("buttonFunction");
  }
Enter fullscreen mode Exit fullscreen mode

How to Stop Event Bubbling?

<div class="viewport" onclick="viewportFunction(event)">       
   <div class="content" onclick="contentFunction(event)">       
       <button class="button" onclick="buttonFunction(event)">
          CLick Button Event
       </button>
   </div>       
</div>
Enter fullscreen mode Exit fullscreen mode

The event bubbling mechanism in JavaScript causes events to propagate from the innermost element to the outermost element in the DOM tree. If you want to prevent the event from propagating to higher elements in the DOM, You can use the event.stopPropagation() method. This method stops the bubbling of the event to parent elements, so that it only triggers the handler for the element that received the event.

function viewportFunction(event){
   console.log("viewportFunction");
}

function contentFunction(event){
   console.log("contentFunction");
}

function buttonFunction(event){
   //Execute only this function
   event.stopPropagation()
   console.log("buttonFunction");
}
Enter fullscreen mode Exit fullscreen mode

If you want to stop the event propagation in the contentFunction(), you can simply add event.stopPropagation() inside the function. This will prevent the event from bubbling up to higher elements in the DOM. Note that you need to pass the event object to the contentFunction() as a parameter in order to use event.stopPropagation().

What is Event Capturing?

Event capture is the reverse of event bubbling. In event capture, events are first captured by the outermost element and then propagated inward to the innermost element. This means that the event handler for the outermost element is triggered first, followed by the event handlers for successively inner elements.
Image description

The right-side diagram in the image represents event capture, where the event flows from the outermost element to the innermost element. The left-side diagram represents event bubbling, where the event flows from the innermost element to the outermost element. Event capture is the reverse of event bubbling, meaning that the event is first captured by the outermost element and then propagated inward.

Example event capturing

<div class="viewport">       
    <div class="content">       
        <button class="button" >CLick Button Event</button>    
    </div>       
</div>
Enter fullscreen mode Exit fullscreen mode
let viewportHandler = document.querySelector('.viewport');
let contentHandler = document.querySelector('.content');
let buttonHandler = document.querySelector('.button');

viewportHandler.addEventListener("click",viewportFunction,true);
contentHandler.addEventListener("click",contentFunction,true);
buttonHandler.addEventListener("click", buttonFunction,true);

function viewportFunction(){
   //Execute First
   console.log("viewportFunction");
}

function contentFunction(){
   //Execute Second
   console.log("contentFunction");
}

function buttonFunction(){
   //Execute Third
   console.log("buttonFunction");
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)