Quiz

Explain the event phases in a browser

Topics
BrowserJavaScript

TL;DR

In a browser, events go through three phases: capturing, target, and bubbling. During the capturing phase, the event travels from the root to the target element. In the target phase, the event reaches the target element. Finally, in the bubbling phase, the event travels back up from the target element to the root. You can control event handling using addEventListener with the capture option.


Propagation path

An event travels down the ancestor path during capture, reaches the target, and—when the event bubbles—travels back up that path.

Browser event propagation phases

Capture listeners run on the downward path and ordinary listeners run on the upward path; listeners registered on the target run at the target phase.

Event phases in a browser

Capturing phase

The capturing phase, also known as the trickling phase, is the first phase of event propagation. During this phase, the event starts from the root of the DOM tree and travels down to the target element. Event listeners registered for this phase will be triggered in the order from the outermost ancestor to the target element.

element.addEventListener('click', handler, true); // true indicates capturing phase

Target phase

The target phase is the second phase of event propagation. In this phase, the event has reached the target element itself. Event listeners registered directly on the target element will be triggered during this phase.

element.addEventListener('click', handler); // listener on the target fires during the target phase

Bubbling phase

The bubbling phase is the final phase of event propagation. During this phase, the event travels back up from the target element to the root of the DOM tree. Event listeners registered for this phase will be triggered in the order from the target element to the outermost ancestor.

element.addEventListener('click', handler, false); // false indicates bubbling phase

Controlling event propagation

You can control event propagation using methods like stopPropagation and stopImmediatePropagation. These methods can be called within an event handler to stop the event from propagating further.

element.addEventListener('click', function (event) {
event.stopPropagation(); // Stops the event from propagating further
});

Further reading

Exercises

Check your understanding
Beta
Check your understanding Exercise 1 of 2
Check your understanding Exercise 1 of 2

For an event that supports bubbling, which sequence describes its trip along the DOM event path?