Gyaan

Event Delegation

intermediate DOM events patterns

Event Delegation is basically a pattern to handle events efficiently. Instead of adding an event listener to each and every similar element, we can add an event listener to a parent element and call an event on a particular target using the .target property of the event object.

For example, if we have a list of 100 items, instead of adding 100 click listeners, we add one listener on the parent <ul> and use event.target to identify which <li> was clicked.

ul#todo-list ← listener here
li
Task 1
li
Task 2
li
Task 3
click on any li → event bubbles up → parent catches it via event.target
<ul id="todo-list">
  <li>Task 1</li>
  <li>Task 2</li>
  <li>Task 3</li>
</ul>
// Without delegation — adding listener to each item
document.querySelectorAll('#todo-list li').forEach(item => {
  item.addEventListener('click', function() {
    console.log(this.textContent);
  });
});

// With delegation — single listener on the parent
document.getElementById('todo-list').addEventListener('click', function(event) {
  if (event.target.tagName === 'LI') {
    console.log(event.target.textContent);
  }
});

The delegated approach is better because it uses only one event listener instead of many. And the best part is, if we add a new <li> to the list later, the click handler will automatically work for it without adding any new listener.

In simple language, event.target is the element that was actually clicked (the <li>), and event.currentTarget is the element where we attached the listener (the <ul>).