JavaScript events are at the core of web interactions. Understanding how they propagate through the DOM is key to effective event handling, especially in interviews. Here’s a quick rundown of the essentials:

Event Bubbling, Capturing, and Delegation in JavaScript: Quick Interview Guide

Event Bubbling:

Definition: Event bubbling occurs when an event starts at the target element and bubbles up to its parent elements.

Key Point: Use event.stopPropagation() to prevent the event from reaching parent elements.

Event Capturing:

Definition: Event capturing is the opposite of bubbling, where the event starts from the root and trickles down to the target element.

Key Point: Use event.stopPropagation() to stop event capturing.

Event Delegation:

Definition: Event delegation allows you to handle events for multiple child elements using a single parent listener.

Key Point: Improves performance by reducing the number of event listeners.

Example:

<div id="parent" style="padding: 20px; border: 2px solid blue;">
    Parent Div
    <button id="child" style="margin-top: 10px;">Click Me</button>
  </div>
 // Capturing Phase
document.querySelector('#parent').addEventListener('click', (event) => {
      console.log('Parent Div - Capturing Phase');
    }, true); // Use true to enable capturing phase

    // Target Phase
    document.querySelector('#child').addEventListener('click', (event) => {
      console.log('Button - Target Phase');
    });
    // Bubbling Phase
    document.querySelector('#parent').addEventListener('click', (event) => {
      console.log('Parent Div - Bubbling Phase');
    });
    // Stop Propagation Example
    document.querySelector('#child').addEventListener('click', (event) => {
      event.stopPropagation(); // Stops event from bubbling up
      console.log('Button - Bubbling Stopped');
    });

Explanation:

Capturing Phase: The #parent element listens for the click event during the capturing phase (using true as the third argument in addEventListener).

Target Phase: The #child button is the target of the event, and its event listener executes when the event reaches it.

Bubbling Phase: The #parent element also listens for the click event during the bubbling phase.

Stopping Propagation: The event.stopPropagation() in the target phase prevents the event from bubbling up to the parent during the bubbling phase.

Expected Console Output When Clicking the Button:

1. Parent Div - Capturing Phase

2. Button - Target Phase

3. Button - Bubbling Stopped

For a deeper dive into these concepts, including event phases and how to use event.eventPhase, check out the comprehensive guide here.

🚀 If you enjoyed this post, why not show your love for coding with our Javascript Developer Themed Tees from Usha Creations? Discover the perfect shirt for your next hackathon!

Keep reading