Home >Web Front-end >JS Tutorial >Event Bubbling vs. Capturing: How Do Event Propagation Modes Affect DOM Event Handling?
Event bubbling and capturing play crucial roles in event propagation within the HTML DOM API. To comprehend their functionality, let's delve into the intricacies of these two concepts.
Event Bubbling vs. Event Capturing
When an event occurs in an element nested within another element, and both elements have registered event handlers for that particular event, the event propagation mode determines the order in which the elements receive the event.
Trickling vs. Bubbling
Capturing is also known as "trickling," a term that helps remember the propagation order: "trickle down, bubble up."
Browser Support
Performance Considerations
Event bubbling may have slightly lower performance in complex DOMs compared to event capturing.
Usage
We utilize the addEventListener(type, listener, useCapture) method to register event handlers in either bubbling (default) or capturing mode. To use the capturing model, the third argument should be set to true.
Example
Consider the following HTML structure:
<div> <ul> <li></li> </ul> </div><p>If a click event occurs in the li element:</p> <ul> <li>In capturing mode, the event is first handled by the div, followed by the ul, and finally the li.</li> <li>In bubbling mode, the event is first handled by the li, then by the ul, and lastly by the div.</li> </ul> <p><strong>Additional Resources</strong></p> <ul> <li>[Event Order on QuirksMode](https://www.quirksmode.org/js/events_order.html)</li> <li>[addEventListener on MDN](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)</li> <li>[Events Advanced on QuirksMode](https://www.quirksmode.org/js/events/)</li> </ul> <p><strong>Interactive Demonstration</strong></p> <p>The following interactive example illustrates the capturing and bubbling phases of event propagation:</p> <pre class="brush:php;toolbar:false">var logElement = document.getElementById('log'); function log(msg) { logElement.innerHTML += ('<p>' + msg + '</p>'); } function capture() { log('capture: ' + this.firstChild.nodeValue.trim()); } function bubble() { log('bubble: ' + this.firstChild.nodeValue.trim()); } var divs = document.getElementsByTagName('div'); for (var i = 0; i < divs.length; i++) { divs[i].addEventListener('click', capture, true); divs[i].addEventListener('click', bubble, false); }
When clicking on any of the highlighted elements, observe the event capturing phase occurring first, followed by the bubbling phase.
The above is the detailed content of Event Bubbling vs. Capturing: How Do Event Propagation Modes Affect DOM Event Handling?. For more information, please follow other related articles on the PHP Chinese website!