What is event capturing in JavaScript?


Event capturing is one of two ways to do event propagation in the HTML DOM. In event capturing, an event propagates from the outermost element to the target element. It is the opposite of event bubbling, where events propagate outwards from the target to the outer elements.

Events trickle down in event capturing
Events trickle down in event capturing

Capturing happens before bubbling. The three phases of event propagation are: capturing, target, and bubbling.

Event capturing is rarely used and, usually, events are handled on bubbling. When you use the on<event>-property or the two-argument method addEventListener(event, handler) to add event handlers, the events are only handled during the bubbling phase (the default case). However, you can still handle events during the capturing phase using the method given in the example below.

Example

For event capturing, we set the handler capture option to true: elem.addEventListener(event, handler, true). By default, it is set to bubbling: false.

In the example below, we add click event handlers on every HTML element using JavaScript for loop.

Clicking on the p element calls the click event handlers of all parent elements, starting from the outer and propagating inside to the target element p:
htmlbodyarticledivp.

  • HTML
Console
Copyright ©2024 Educative, Inc. All rights reserved