← Back to all snippets
JAVASCRIPT

Implement Event Delegation

Master event delegation in JavaScript to efficiently handle events for multiple child elements, including those added dynamically, using a single event listener.

function setupEventDelegation(parentElementId, selector, eventType, callback) {
    const parentElement = document.getElementById(parentElementId);
    if (!parentElement) {
        console.error('Parent element for delegation not found:', parentElementId);
        return;
    }

    parentElement.addEventListener(eventType, function(event) {
        // Check if the clicked element matches the selector
        if (event.target.matches(selector)) {
            callback(event.target, event);
        }
    });
}

// Example Usage:
// HTML structure: <ul id="myList"><li>Item 1</li><li>Item 2</li></ul>
// setupEventDelegation('myList', 'li', 'click', function(targetElement, event) {
//     console.log('Clicked item:', targetElement.textContent);
//     targetElement.style.color = 'blue';
// });

// This also works for items added later:
// const newItem = document.createElement('li');
// newItem.textContent = 'New Item';
// document.getElementById('myList').appendChild(newItem);
How it works: Event delegation is a powerful pattern that attaches a single event listener to a parent element, rather than individual listeners to each child. When an event (like a click) bubbles up from a child, the listener checks if the `event.target` matches a specific selector. This approach is highly efficient for lists of many items or dynamically added elements, as it reduces memory usage and simplifies event management.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs