Event Propagation in JavaScript

Event Propagation is the process through which the event propagates (up or down) through DOM to react to their target. There are two phases of the event propagation capturing phase and bubbling phase. Understanding the event propagation is very crucial for handling user interaction and give more flexibility to understand the complexity of DOM structure.

Let's understand both event propagation one by one

Event Bubbling Phase

This is the default behavior of an event in which when the event occurs it trigger an event object that propagates through DOM moving from the target element to the outermost ancestor


// Adding event listener to the parent div for the click event
    document.getElementById('parent').addEventListener('click', () => {
        console.log('Parent is clicked');
    });

    // Adding event listener to the child div for the click event
    document.getElementById('child').addEventListener('click', () => {
        console.log('Child is clicked');
    });
  // output

Lets break down this code

  • When you click on the child div a click event is triggered.

  • The event starts at the target element which is the child div

  • The event handle for child div is executed

  • After the target phase is done, the event bubble is started

  • During the bubbling phase, the event reaches the parent div

  • The event handle for parent div is executed

// output of the code when you click on the button
 Child is clicked
 Parent is clicked

Event Capturing

In the event phase, the exact opposite occurs. In this phase, the event starts from the root of the DOM and moves toward the target element.

Lets check out the following example

 document.getElementById('child').addEventListener('click', () => {
    console.log('Capturing Phase: Child is clicked');
  }, true);
 document.getElementById('parent').addEventListener('click', () => {
    console.log('Capturing Phase: Parent is clicked');
  }, true);

In addEventListener method, you have to pass the third parameter as true to handle the capturing phase

Lets break down the above code

  • The event starts capturing from the root element

  • The event handle for parents is triggered

  • It will move down toward the target element

  • The event reacts the target element

Stopping Event Propagation

To prevent an event from propagating through its normal form we stop the propagation in either phase using the stopPropagation technique. This method helps to prevent the event from reaching future event listener in the capturing or bubbling phase

document.getElementById("childElement").addEventListener("click", function(event) {
    console.log("Bubbling phase: Child element clicked");
    event.stopPropagation(); // Stops the event from further propagation
});

if you like this article let's connect on LinkedIn linkedin.com/in/shivamgupta6418

Did you find this article valuable?

Support Shivam Gupta by becoming a sponsor. Any amount is appreciated!