Event Delegation is a technique in JavaScript where a single event listener is added to a parent element to handle events for multiple child elements. Instead of attaching listeners to each child, you take advantage of event bubbling to catch events higher in the DOM tree.
💡 Why use Event Delegation?
- Improves performance by reducing the number of event listeners.
- Allows dynamic elements added later to be handled without extra code.
- Simplifies code and maintenance.
How it works: When an event occurs on a child element, it bubbles up to its ancestors. By listening on the parent, you can detect which child triggered the event using event.target.
| Event Delegation | Individual Listeners |
|---|---|
| One listener on parent handles many children | Each child has its own listener |
| Works with dynamic elements added later | Listeners must be added for new elements |
| Better memory and performance | More memory usage and slower startup |
Basic example: A list with many buttons. Instead of attaching a click handler to each button, attach one to the list:
📌 Deep Dive: Delegated Click Handler
const list = document.querySelector('#button-list');
list.addEventListener('click', (event) => {
if (event.target.tagName === 'BUTTON') {
alert(`Clicked button: ${event.target.textContent}`);
}
});
Key points:
event.targetidentifies the actual element clicked.- Check
event.targetmatches your selector (e.g., tagName, class). - Add listener on a common ancestor, not on individual child elements.
⚠️ Beware of event.target vs event.currentTarget
event.target is the element that triggered the event (e.g., the button clicked).
event.currentTarget is the element the listener is attached to (e.g., the parent).
When to use Event Delegation:
- Handling many similar child elements (e.g., lists, tables, menus).
- When child elements are created or removed dynamically.
- To keep your code cleaner and improve performance.
💡 Summary
Event Delegation leverages event bubbling to efficiently handle events on multiple child elements through a single parent listener, simplifying code and improving performance.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What property do you check to find which child element triggered the event in delegation?
Question 2 of 2
Which is a main advantage of event delegation over adding listeners to each child?
Loading results...
