Explain the event phases in a browser
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.
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.
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.
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.