Event delegation
Event delegation is a technique in JavaScript where an event listener is attached to a parent element instead of individual child elements. This allows the event to "flow" through the DOM, either upward (bubbling phase) or downward (capturing phase), depending on how the listener is configured.
There are two types of event propagation:
- Event Bubbling: The event starts from the target element (the one that triggered the event) and bubbles up through its ancestors in the DOM hierarchy.
- Event Capturing: The event starts from the root of the DOM and flows down to the target element.
This is particularly useful for:
- Performance optimization
- Handling dynamic elements
- Reducing memory usage
// Instead of this (inefficient)
const buttons = document.querySelectorAll('.product-button');
buttons.forEach(button => {
button.addEventListener('click', function(e) {
// handle click
});
});
// Better approach with event delegation
document.querySelector('.products-container').addEventListener('click', function(e) {
if (e.target.matches('.product-button')) {
const productId = e.target.dataset.productId;
// handle the product click
}
});