JAVASCRIPT
Implement Event Delegation on Dynamic Elements
Master event delegation in JavaScript to efficiently handle events on multiple or dynamically added child elements by attaching a single listener to their common parent.
function setupEventDelegation(containerId, selector, eventType, handler) {
const container = document.getElementById(containerId);
if (!container) {
console.error('Container not found:', containerId);
return;
}
container.addEventListener(eventType, function(event) {
// Check if the clicked element matches the selector
if (event.target && event.target.matches(selector)) {
handler.call(event.target, event); // Call handler with 'this' set to the matching element
}
});
}
// Example usage:
// <ul id="myList"><li>Item 1</li><li>Item 2</li></ul>
// setupEventDelegation('myList', 'li', 'click', function(event) {
// console.log('Clicked item:', this.textContent);
// this.style.backgroundColor = 'yellow';
// });
// Dynamically add more <li> elements, and the listener will still work.
How it works: This snippet demonstrates event delegation. Instead of attaching individual event listeners to many child elements (especially dynamic ones), a single listener is attached to their common parent. When an event occurs, it bubbles up to the parent. The listener then checks if the `event.target` (the element where the event originated) matches a specific `selector`. If it does, the provided `handler` function is executed, improving performance and simplifying code for dynamic content.