Trusted answers to developer questions

What is event capturing in JavaScript?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.


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

RELATED TAGS

javascript
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?