Advertisement
728x90
Event capturing is a phase of event propagation in which an event is first intercepted by the outermost ancestor element, then travels downward through the DOM hierarchy until it reaches the target (innermost) element.
To handle events during the capturing phase, you need to pass true as the third argument to the addEventListener method.
javascript
1<div>
2 <button class="child">Hello</button>
3 </div>
4
5 <script>
6 const parent = document.querySelector("div");
7 const child = document.querySelector(".child");
8
9 // Capturing phase: parent listener (runs first)
10 parent.addEventListener("click", function () {
11 console.log("Parent (capturing)");
12 }, true); // `true` enables capturing
13
14 // Bubbling phase: child listener (runs after)
15 child.addEventListener("click", function () {
16 console.log("Child (bubbling)");
17 });
18 </script>
19 // Parent (capturing)
20 // Child (bubbling)Advertisement
Responsive Ad
🎯 Practice NowRelated Challenge
JavaScript Coding Exercise 2
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement
728x90
87of476