JAVASCRIPT

Implementing Event Delegation

Optimize performance and simplify event handling for multiple child elements by attaching a single event listener to their common parent using event delegation.

// HTML Example:
// <ul id="myList">
//   <li data-item-id="1">Item One</li>
//   <li data-item-id="2">Item Two</li>
//   <li data-item-id="3">Item Three</li>
//   <li><button data-action="add">Add New Item</button></li>
// </ul>

document.addEventListener('DOMContentLoaded', () => {
  const myList = document.getElementById('myList');

  if (myList) {
    myList.addEventListener('click', (event) => {
      // Check if the clicked element is an <li> with a data-item-id
      if (event.target.tagName === 'LI' && event.target.dataset.itemId) {
        console.log(`Clicked on item with ID: ${event.target.dataset.itemId}`);
        event.target.style.backgroundColor = 'yellow';
      }
      // Check if the clicked element is a button with data-action="add"
      else if (event.target.tagName === 'BUTTON' && event.target.dataset.action === 'add') {
        const newItemCount = myList.children.length; // Approximate, assuming list items
        const newItem = document.createElement('li');
        newItem.textContent = `New Item ${newItemCount}`;
        newItem.dataset.itemId = newItemCount;
        myList.insertBefore(newItem, event.target.parentNode); // Insert before the button's parent (the li)
        console.log(`Added new item: New Item ${newItemCount}`);
      }
    });
  }
});
How it works: Event delegation is a technique where you attach a single event listener to a parent element instead of individual child elements. When an event (like a click) occurs on a child, it "bubbles up" to the parent. The listener on the parent then uses `event.target` to determine which specific child element was clicked, allowing you to handle events for dynamically added elements or a large number of similar elements efficiently.

Need help integrating this into your project?

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

Hire DigitalCodeLabs