Contenido del Curso
Advanced JavaScript Mastery
Advanced JavaScript Mastery
Event Propagation and Delegation
Event Propagation
Event propagation describes how an event moves through the DOM after being triggered, and it has three distinct phases: Capturing, Target, and Bubbling Phases.
Capturing Phase (Capture)
The event starts at the root of the DOM tree (window
) and moves down toward the target element. Event listeners in this phase catch the event as it travels downward.
Target Phase
The event reaches the target element (the element that triggered the event). This is where the event listeners attached to the target element itself are executed.
Bubbling Phase (Bubble)
After reaching the target element, the event starts moving back up the DOM tree to the root (window
), bubbling through parent elements. This is the most commonly used phase, allowing parent elements to react to events triggered by child elements.
index
index
index
The event propagates through the DOM when the button
is clicked. First, the event triggers on the button
(target phase), then bubbles up to the inner div
and finally the outer div
(bubbling phase).
Event Delegation
Event Delegation is a technique that leverages event propagation to handle events from child elements using a single event listener on a parent element. Instead of attaching individual listeners to each child, a parent element listens for events that bubble up from its children. This approach has two main advantages:
- Performance: Reducing the number of event listeners improves performance, especially in situations where elements are created dynamically (e.g., a list that grows as new items are added);
- Maintainability: Event delegation simplifies code, especially when working with large DOM structures or dynamic content.
index
index
index
Instead of adding click listeners to each li
element individually, a single listener is added to the ul
parent element. The event bubbles up from the li
elements to the ul
, where it's handled.
Practical Example: Handling Dynamic List
Event delegation is perfect for managing interactions in lists or tables that may grow over time (e.g., adding tasks to a to-do list, or products to a shopping cart). As items are added or removed, the parent container (like ul
or table
) handles all interactions, saving the need to attach or remove listeners to each child element.
index
index
index
¡Gracias por tus comentarios!