JAVASCRIPT
Efficient Event Handling with Event Delegation
Implement efficient event handling for multiple or dynamically added DOM elements by attaching a single event listener to a common parent element using event delegation, improving performance and simplifying code.
function setupEventDelegation(parentId, eventType, selector, callback) {
const parent = document.getElementById(parentId);
if (!parent) {
console.error(`Parent element with ID '${parentId}' not found.`);
return;
}
parent.addEventListener(eventType, function(event) {
// Check if the clicked element (or one of its ancestors) matches the selector
const targetElement = event.target.closest(selector);
if (targetElement && parent.contains(targetElement)) {
callback(event, targetElement);
}
});
}
// Example usage:
// <ul id="myList">
// <li class="item">Item 1</li>
// <li class="item">Item 2</li>
// <li class="item">Item 3</li>
// </ul>
// <button id="addMore">Add More Items</button>
setupEventDelegation('myList', 'click', '.item', (event, itemElement) => {
console.log(`Item clicked: ${itemElement.textContent}`);
itemElement.style.backgroundColor = 'yellow';
});
document.getElementById('addMore').addEventListener('click', () => {
const ul = document.getElementById('myList');
const newItem = document.createElement('li');
newItem.className = 'item';
newItem.textContent = `Item ${ul.children.length + 1} (New)`;
ul.appendChild(newItem);
});
How it works: Event delegation is a powerful pattern for handling events on multiple child elements, especially those added dynamically. Instead of attaching individual listeners to each child, a single listener is attached to a common parent. When an event bubbles up to the parent, the listener checks if the `event.target` (or one of its ancestors via `closest()`) matches a specific selector. This reduces memory footprint and automatically handles events for elements that are added to the DOM after the initial page load, without needing to re-attach listeners.