JAVASCRIPT
Attaching Event Listeners with Event Delegation
Efficiently add a single event listener to a parent container to handle events from multiple child elements, a powerful pattern known as event delegation in JavaScript.
// Get the parent element that contains all the clickable items
const listContainer = document.getElementById('myList'); // Assuming <ul id="myList"> contains <li> items
if (listContainer) {
// Attach a single event listener to the parent container
listContainer.addEventListener('click', function(event) {
// Check if the clicked target is an <li> element
if (event.target.tagName === 'LI') {
console.log('List item clicked:', event.target.textContent);
// Example: Highlight the clicked item
event.target.style.backgroundColor = 'yellow';
setTimeout(() => {
event.target.style.backgroundColor = ''; // Revert after a short delay
}, 500);
}
});
} else {
console.error('List container with ID "myList" not found.');
}
/*
Example HTML structure for this snippet:
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
*/
How it works: This snippet demonstrates event delegation, an efficient way to handle events on multiple child elements. Instead of attaching a listener to each `<li>`, a single listener is placed on their parent `<ul>`. When a click occurs, the `event.target` is checked to see if an `<li>` was clicked, preventing the need for many individual listeners and working for dynamically added children.