JAVASCRIPT
Implement Efficient Event Delegation
Master event delegation in JavaScript to efficiently handle events on multiple or dynamically added elements by attaching a single listener to a common parent.
const parentContainer = document.getElementById('list-container');
if (parentContainer) {
parentContainer.addEventListener('click', function(event) {
// Check if the clicked element (or its closest ancestor) is a list item
const listItem = event.target.closest('li');
if (listItem && parentContainer.contains(listItem)) {
console.log(`List item clicked: ${listItem.textContent}`);
listItem.classList.toggle('highlight');
}
});
// Example of adding a new item dynamically after the listener is set
setTimeout(() => {
const newItem = document.createElement('li');
newItem.textContent = 'New dynamic item';
parentContainer.appendChild(newItem);
console.log('New item added after event listener setup.');
}, 2000);
} else {
console.error('List container not found!');
}
How it works: Event delegation is a powerful pattern where you attach a single event listener to a common parent element, rather than individual listeners to many child elements. When an event bubbles up, you can check `event.target` or `event.target.closest()` to identify the specific child that was clicked. This approach is highly efficient for lists, tables, or dynamically added elements, as it reduces memory consumption and automatically handles events for future elements without needing to re-attach listeners.