0
0
JavascriptConceptBeginner · 3 min read

What is Event Delegation in JavaScript: Simple Explanation and Example

Event delegation in JavaScript is a technique where a single event listener is added to a parent element to handle events for its child elements. Instead of attaching listeners to each child, the parent catches events bubbling up from children, improving performance and simplifying code.
⚙️

How It Works

Imagine you have a group of buttons inside a box. Instead of putting a listener on each button, you put one listener on the box. When you click a button, the event travels up from the button to the box. The box's listener catches the event and checks which button was clicked.

This works because of a feature called event bubbling, where events move from the deepest element clicked up through its ancestors. Event delegation uses this to listen once on a parent and handle many child events.

💻

Example

This example shows event delegation by adding one click listener to a list. When any list item is clicked, the listener shows which item was clicked.

javascript
const list = document.getElementById('myList');

list.addEventListener('click', event => {
  if (event.target && event.target.nodeName === 'LI') {
    console.log('Clicked item:', event.target.textContent);
  }
});
Output
Clicked item: Item 1 Clicked item: Item 2 Clicked item: Item 3
🎯

When to Use

Use event delegation when you have many similar elements that need the same event handling, like lists, tables, or menus. It saves memory and makes your code easier to manage because you add fewer listeners.

It is also helpful when elements are added dynamically after the page loads, as the parent listener will catch events from new children without extra code.

Key Points

  • Event delegation uses one listener on a parent to handle many child events.
  • It relies on event bubbling to catch events as they move up the DOM.
  • It improves performance by reducing the number of listeners.
  • It works well with dynamic content added after page load.

Key Takeaways

Event delegation uses one parent listener to handle events from many child elements.
It works by catching events as they bubble up through the DOM tree.
This technique improves performance and simplifies event management.
Event delegation is ideal for dynamic content and large numbers of similar elements.