JAVASCRIPT

Implement Efficient Event Delegation in the DOM

Optimize event handling in the DOM by using event delegation, attaching a single listener to a parent to manage events from multiple child elements.

// HTML structure example:
// <ul id="myList">
//   <li data-item-id="1">Item 1</li>
//   <li data-item-id="2">Item 2</li>
//   <li data-item-id="3">Item 3</li>
//   <li data-item-id="4">Item 4</li>
// </ul>
// <button id="addItemBtn">Add New Item</button>

const myList = document.getElementById('myList');
const addItemBtn = document.getElementById('addItemBtn');
let itemCounter = 4; // Start after existing items

// Use event delegation on the parent <ul> element
myList.addEventListener('click', function(event) {
  // Check if the clicked element (event.target) is a list item (or a descendant thereof)
  // and if it has the data-item-id attribute
  const clickedItem = event.target.closest('li[data-item-id]');

  if (clickedItem) {
    const itemId = clickedItem.dataset.itemId;
    console.log(`Clicked item with ID: ${itemId}, Text: ${clickedItem.textContent}`);
    // Add specific logic for each item here
    clickedItem.style.backgroundColor = 'yellow';
    setTimeout(() => {
      clickedItem.style.backgroundColor = ''; // Reset background after a short delay
    }, 300);
  }
});

// Add new items dynamically (these will also be covered by event delegation)
addItemBtn.addEventListener('click', function() {
  itemCounter++;
  const newItem = document.createElement('li');
  newItem.textContent = `Item ${itemCounter}`;
  newItem.dataset.itemId = itemCounter; // Custom data attribute
  myList.appendChild(newItem);
  console.log(`Added new item: Item ${itemCounter}`);
});
How it works: This snippet demonstrates event delegation, a powerful technique to handle events for multiple child elements efficiently. Instead of attaching a separate event listener to each list item, a single click listener is added to the parent `<ul>`. When a click occurs, `event.target.closest('li[data-item-id]')` identifies if a list item was clicked. This approach significantly reduces memory footprint and simplifies code, especially when dealing with dynamically added elements, as new items automatically inherit the parent's event listener.

Need help integrating this into your project?

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

Hire DigitalCodeLabs