DEV Community

Cover image for Event Capturing
Parwinder 👨🏻‍💻
Parwinder 👨🏻‍💻

Posted on

3 1

Event Capturing

Event capturing is the opposite of Event bubbling. In the case of event bubbling, events bubble up from the element parent and then its ancestors.

In the case of event capturing, it starts from the top, going down the DOM structure until it reaches the target element. The target element is common to bubbling and capturing. Capturing ends at target, and bubbling starts at target.

Event capturing is rarely used. To enable event capturing, we can pass the third parameter to addEventListener.

Example:

const myButton = document.querySelector(".btn-primary");

myButton.addEventListener("click", function() {
    console.log("The button was clicked");
}, { capture : true });

The third parameter set to true enables the capturing phase. Now when an event happens, it starts at the top, trickles down to the target element, and eventually bubbles up.

The third parameter does not need to be an object. It can be a boolean true.

myButton.addEventListener("click", function() {
    console.log("The button was clicked");
}, true);

To summarize, DOM Events have three phases:

  1. Capturing
  2. Target
  3. Bubbling

We can determine the phase we are in by using event.eventPhase or the event handler.

🚨If addEventListener used true as the third parameter for event capturing, we mention the same phase in removeEventListener to remove the handler correctly.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay