Event Bubbling and Capture

ref –

  • https://gomakethings.com/what-is-that-third-argument-on-the-vanilla-js-addeventlistener-method-and-when-do-you-need-it/
  • https://medium.com/@vsvaibhav2016/event-bubbling-and-event-capturing-in-javascript-6ff38bec30e

Event Bubbling is the event starts from the deepest element or target element to its parents, then all its ancestors which are on the way to bottom to top. At present, all the modern browsers have event bubbling as the default way of event flow.

So the event goes from button, all the way to the top global object.

use event.stopPropagation() to stop at a certain level:

addEventListener useCapture parameter (Event Capturing)

You may sometimes see a third argument on the addEventListener() method.

That third argument, true? That’s called useCapture.

The reason for this parameter is because certain events, like focus, don’t bubble.

If you wrote your event listener like this, the event would never fire.

So, what exactly does useCapture do?

The useCapture argument, when set to true, tells the addEventListener() method to capture events that happen in the parent.

Instead of the event bubbling from the originating element up to each parent, the event listener starts at the parent and works its way down. This allows you to use event delegation on non-bubbling events.

Event Capturing is the event starts from top element to target element. Modern browser doesn’t support event capturing by default but we can achieve that by code in JavaScript.

Full View of Event Flow

Every event flow has three phase:

  1. Event Capturing
  2. Event Target
  3. Event Bubbling