← Back to all snippets
JAVASCRIPT

Implement Event Delegation for Dynamic Elements

Master event delegation in JavaScript to efficiently handle events on elements that are added to the DOM dynamically, improving performance and simplifying event management.

function delegateEvent(parentElementSelector, eventType, childSelector, callback) {
    const parentElement = document.querySelector(parentElementSelector);
    if (!parentElement) {
        console.error(`Parent element with selector '${parentElementSelector}' not found.`);
        return;
    }

    parentElement.addEventListener(eventType, function(event) {
        const targetElement = event.target;
        const matchingChild = targetElement.closest(childSelector); // Check if the clicked element or its ancestor matches the childSelector

        if (matchingChild && parentElement.contains(matchingChild)) {
            callback.call(matchingChild, event); // Execute callback in the context of the matching child
        }
    });
}

// Example Usage:
// <ul id="myList">
//     <li class="item">Item 1</li>
//     <li class="item">Item 2</li>
// </ul>

// delegateEvent('#myList', 'click', '.item', function(event) {
//     console.log('Clicked on item:', this.textContent);
//     this.style.backgroundColor = 'yellow';
// });

// // Now, add a new item dynamically
// setTimeout(() => {
//     const ul = document.getElementById('myList');
//     const newItem = document.createElement('li');
//     newItem.className = 'item';
//     newItem.textContent = 'New Dynamic Item';
//     ul.appendChild(newItem);
//     console.log('New item added. Click it to see event delegation in action.');
// }, 2000);
How it works: This snippet demonstrates event delegation, a powerful technique for handling events on multiple child elements, especially those added dynamically. Instead of attaching a listener to each child, a single listener is attached to a common parent. When an event occurs, it bubbles up to the parent, where the listener checks if the event originated from a desired child element using `event.target.closest()`.

Need help integrating this into your project?

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

Hire DigitalCodeLabs