Implementing Event Delegation for Efficient Event Handling
Owner: SnippetBot
Created: 2026-08-13 00:00:16
Size: 1.14 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Implements event delegation on a parent element to handle events
* on its dynamically created or numerous children. This improves performance
* and simplifies event management.
*/
function setupEventDelegation(parentId, childSelector, eventType, handlerFunction) {
const parentElement = document.getElementById(parentId);
if (parentElement) {
parentElement.addEventListener(eventType, function(event) {
// Check if the clicked element matches the childSelector
if (event.target && event.target.matches(childSelector)) {
handlerFunction(event.target);
}
});
console.log(`Event delegation set up for #${parentId} for children matching "${childSelector}" on event "${eventType}".`);
} else {
console.error(`Parent element with ID "${parentId}" not found.`);
}
}
// Example Usage (assuming an HTML structure like <ul id="myList"><li class="item">1</li><li class="item">2</li></ul>):
// function handleItemClick(clickedItem) {
// console.log(`Item clicked: ${clickedItem.textContent}`);
// clickedItem.style.backgroundColor = 'yellow';
// }
// setupEventDelegation('myList', '.item', 'click', handleItemClick);