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:
If a click event occurs in the li element:
Additional Resources
Interactive Demonstration
The following interactive example illustrates the capturing and bubbling phases of event propagation:
var logElement = document.getElementById('log'); function log(msg) { logElement.innerHTML = ('' msg '
'); } 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; iWhen clicking on any of the highlighted elements, observe the event capturing phase occurring first, followed by the bubbling phase.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3