JAVASCRIPT

Implementing Efficient Event Delegation in JavaScript

Optimize event handling for dynamic lists or numerous elements by using event delegation. Attach a single listener to a parent element to manage events on its children.

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

  if (parentList) {
    parentList.addEventListener('click', (event) => {
      // Check if the clicked element is a list item (li)
      if (event.target.tagName === 'LI') {
        const listItem = event.target;
        console.log('List item clicked:', listItem.textContent);

        // Example: Toggle a class on the clicked item
        listItem.classList.toggle('selected');
      }
      // You can also check for specific classes or data attributes
      if (event.target.classList.contains('delete-btn')) {
        event.target.closest('li')?.remove();
        console.log('Delete button clicked, item removed.');
      }
    });

    // Example: Add a new item to demonstrate dynamic event handling
    const addItemButton = document.getElementById('addItemButton');
    if (addItemButton) {
      addItemButton.addEventListener('click', () => {
        const newItem = document.createElement('li');
        newItem.textContent = `New Item ${parentList.children.length + 1} <button class="delete-btn">X</button>`;
        parentList.appendChild(newItem);
      });
    }
  }
});
How it works: This snippet demonstrates event delegation, a powerful technique for handling events on multiple child elements efficiently. Instead of attaching a listener to each `li` item, a single `click` listener is attached to their common parent (`parentList`). When a click occurs, the `event.target` is checked to determine which child was clicked, allowing dynamic elements added later to also respond without needing new event listeners.

Need help integrating this into your project?

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

Hire DigitalCodeLabs