3 phases of event propagation

how event capturing, targeting and event bubbling works

Photo by Vanja Matijevic on Unsplash

Whenever any click 💘 event occurs in webpage three things happens in fixed sequence.

1. Capturing 📷

Every DOM element receives the event, one after another. In Top to bottom fashion.

1. Window
2. Document
3. Body
4. the all other underlying elements.

2. Target 🎯

The element which triggers the click event receives the control.

3. Bubbling 🫧

The event then bubble ups from clicked element to it’s parent and it keeps bubbling until it reaches to window.

Let’s understand three phases by a simple setup. Here we have
1. Container Div
2. Some HTML Elements inside DIV and a a clickable button.
3. All these is added in body.

Phase 1: As soon as button is clicked, Event Capturing phase starts

Phase 2 => As soon as event reaches to the clicked button, Phase 2 starts ie Target Setting, in this phase event.target is initialised with button

Phase 3 : After targeting, event bubbling starts from clicked element to the top of the document

Interesting thing: 🧙

Now here is the interesting thing, at a given time one listener can either bubble event, or capture event.

If you want both capturing and bubbling then you have to add two separate event listener, one for capturing and one for bubbling separately.

Default Behaviour: By default capturing phase is turned off by the browser. 🫧

In the above setup, click listener is added to every element even body and document

Here we can clearly see that when I click on inner element, only bubbling is happening, because by default capturing phase is turned off.

With Capturing On 📷

Let’s override the behavior by turning capturing on. We can turn on capturing phase by passing {capture:true} as third argument in addEventListener method.

document.addEventListener("click", function (e) {    console.log("Event Received in Document");}, {capture:true} );
In the above setup, click listener is added to every element even body and document with capture:true

Summary:

1. Order of phases Capturing -> Target -> Bubbling
2. By default capturing is off.
3. One listener can either capture or bubble.
4. If we add event.stopPropagation in document’s click listener when capture is one, event won’t propagate down.

Thanks for Reading.

--

--

राहुल मिश्रा
राहुल मिश्रा

No responses yet