JAVASCRIPT

Implement Event Delegation for Efficient Event Handling

Optimize web application performance by using event delegation in JavaScript to manage events on dynamically added or numerous elements efficiently.

<ul id="myList">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

<button id="addItem">Add New Item</button>

<script>
  const myList = document.getElementById('myList');
  const addItemBtn = document.getElementById('addItem');
  let itemCount = 3;

  // Event delegation on the parent <ul>
  myList.addEventListener('click', function(event) {
    if (event.target.tagName === 'LI') {
      alert('Clicked: ' + event.target.textContent);
      event.target.style.backgroundColor = '#e0e0e0';
    }
  });

  // Function to add a new item dynamically
  addItemBtn.addEventListener('click', function() {
    itemCount++;
    const newItem = document.createElement('li');
    newItem.textContent = 'Item ' + itemCount;
    myList.appendChild(newItem);
  });
</script>
How it works: Event delegation is a powerful technique where you attach a single event listener to a parent element, rather than individual listeners to many child elements. When an event fires on a child, it 'bubbles' up to the parent. The parent listener then checks the `event.target` to determine which child originated the event. This is highly efficient for lists with many items or dynamically added content, as it reduces memory footprint and simplifies event management.

Need help integrating this into your project?

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

Hire DigitalCodeLabs