Enjoy 20% off all plans by following us on social media. Check out other promotions!
Quiz Questions

Explain the event phases in a browser

Topics
JAVASCRIPT
Edit on GitHub

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.


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); // default is 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

Edit on GitHub