What is Event Capturing in JavaScript: Explanation and Example
event capturing is a way events travel from the outermost element down to the target element before the event is handled. It is the first phase in the event flow, opposite to event bubbling, which goes from the target up to the outer elements.How It Works
Imagine dropping a ball into a set of nested boxes, one inside the other. Event capturing is like the ball passing through the outer boxes first before reaching the innermost box where it stops. In JavaScript, when an event happens on an element, the event first travels down from the top-level ancestor (like the document) through each nested element until it reaches the target element where the event occurred.
This is called the capturing phase. After this, the event can be handled at the target, and then it moves back up through the ancestors in the bubbling phase. Event capturing lets you catch the event early, before it reaches the target element.
Example
This example shows event capturing in action. We listen for clicks on nested elements and specify capturing to true so the outer element handles the event first.
const outer = document.getElementById('outer'); const inner = document.getElementById('inner'); outer.addEventListener('click', () => { console.log('Outer clicked (capturing)'); }, true); // true enables capturing inner.addEventListener('click', () => { console.log('Inner clicked (bubbling)'); }); // HTML structure: // <div id="outer" style="padding:50px; background:#eee;"> // Outer // <div id="inner" style="padding:20px; background:#ccc;">Inner</div> // </div>
When to Use
Use event capturing when you want to handle an event before it reaches the target element. This is useful if you want to intercept or modify events early, such as for logging, validation, or stopping certain actions before they happen.
For example, if you have a form inside a container and want to catch clicks anywhere inside the container before the form processes them, capturing lets you do that. It can also help in complex interfaces where event order matters.
Key Points
- Event capturing is the first phase of event flow, moving from outer elements to the target.
- It happens before the target phase and the bubbling phase.
- To use capturing, set the third argument of
addEventListenertotrue. - It helps catch events early for control or modification.
Key Takeaways
addEventListener with the third argument true to enable capturing.