JavaScript Notes
What is event delegation in JavaScript? Learn event delegation pattern with examples, best practices, and interview questions in comprehensive 2026.
Introduction
Event Delegation is a powerful JavaScript pattern where we attach a single event listener to a parent element, instead of attaching multiple listeners to individual child elements.
Real-World Analogy
Imagine an office with 50 employees. If a separate phone line were installed at each employee's desk — it would be very costly! Instead, the office has a receptionist who takes all incoming calls and forwards them to the right person.
Event Delegation works exactly the same way:
- Office = Parent Element (like
<ul>or<div>) - Employees = Child Elements (like
<li>or<button>) - Receptionist = Single Event Listener (parent par attached)
- Phone Call = Event (click, keypress, etc.)
A receptionist (parent listener) handles all calls (events) and forwards them to the right employee (child element) — that's Event Delegation!
Why Event Delegation Matters
- Memory Efficient — Ek listener instead of hundreds
- Dynamic Elements — Newly added elements are automatically covered
- Cleaner Code — Less repetition, better maintainability
- Performance — Less memory usage, faster page load
How Event Delegation Works
Event Delegation is based on 3 core concepts:
1. Event Bubbling
When an event fires, it starts from the target element and bubbles upward — to the parent, grandparent, and all the way to the document.
Child clicked Parent clicked Grandparent clicked
2. event.target vs event.currentTarget
event.target— Actual element on which the click occurred (source of event)event.currentTarget— The element on which the listener is attached (parent)
document.querySelector('#parent-list').addEventListener('click', function(event) {
console.log('target:', event.target.tagName);
console.log('currentTarget:', event.currentTarget.tagName);
console.log('target text:', event.target.textContent);
});
// When any <li> is clicked:target: LI currentTarget: UL target text: Item 1
3. Delegation Pattern
The parent element listens for events, checks event.target, and takes the appropriate action.
Code Examples
Example 1: Basic Event Delegation
The simplest delegation pattern — attach a listener to a <ul> and handle list item clicks:
// HTML: <ul id="fruits"><li>Apple</li><li>Banana</li><li>Mango</li></ul>
const fruitList = document.getElementById('fruits');
fruitList.addEventListener('click', function(event) {
// Check if clicked element is an LI
if (event.target.tagName === 'LI') {
console.log('Selected fruit:', event.target.textContent);
event.target.style.backgroundColor = '#e0ffe0';
}
});
// User clicks "Mango":
console.log('--- User clicks Mango ---');
const mockEvent1 = { target: { tagName: 'LI', textContent: 'Mango', style: {} } };
if (mockEvent1.target.tagName === 'LI') {
console.log('Selected fruit:', mockEvent1.target.textContent);
}
// User clicks "Apple":
console.log('--- User clicks Apple ---');
const mockEvent2 = { target: { tagName: 'LI', textContent: 'Apple', style: {} } };
if (mockEvent2.target.tagName === 'LI') {
console.log('Selected fruit:', mockEvent2.target.textContent);
}--- User clicks Mango --- Selected fruit: Mango --- User clicks Apple --- Selected fruit: Apple
Example 2: Dynamic Elements Handling
The biggest advantage of event delegation — newly added dynamic elements are automatically handled without adding a new listener:
Added: Button 2 Added: Button 3 Added: Button 4 --- Clicking Button 3 (dynamically added) --- Clicked: Button 3
Example 3: Todo List with Event Delegation
Real-world example — complete todo list with add, complete, and delete functionality using single delegated listener:
Initial todos: [ "Learn JavaScript", "Practice Delegation", "Build Projects" ] --- Complete "Practice Delegation" --- ✓ Completed: "Practice Delegation" --- Delete "Learn JavaScript" --- ✗ Deleted: "Learn JavaScript" Remaining todos: [ "Practice Delegation", "Build Projects" ]
Example 4: Navigation Menu with Delegation
Tab-based navigation menu where delegation manages the active tab:
Current page: home --- Click "Services" tab --- Navigated to: services --- Click "Contact" tab --- Navigated to: contact
Example 5: Removing Items from a List with Delegation
Shopping cart style — remove items using a delegated click handler:
Initial cart: [ "iPhone 15", "AirPods Pro", "MacBook Air", "iPad Mini" ] --- Remove AirPods Pro --- Removing: AirPods Pro Cart (3 items): [ "iPhone 15", "MacBook Air", "iPad Mini" ] --- Remove iPad Mini --- Removing: iPad Mini Cart (2 items): [ "iPhone 15", "MacBook Air" ]
Example 6: Multi-Action Delegation with data-action Pattern
Handle multiple actions on a single parent using the data-action attribute:
--- Click Edit --- Action triggered: "edit" 📝 Opening edit form... --- Click Share --- Action triggered: "share" 📤 Opening share dialog... --- Click Bookmark --- Action triggered: "bookmark" 🔖 Added to bookmarks!
Benefits of Event Delegation
1. Memory Efficiency
Listeners without delegation: 1000 Listeners with delegation: 1 Memory saved: ~999 function references
2. Performance Benefits
- Faster Page Load — Fewer listeners to attach when the DOM is ready
- Less Garbage Collection — Kam objects memory mein
- Smoother Scrolling — Fewer event listeners = less overhead
3. Dynamic Element Support
Without delegation, you would have to manually add a listener for every new element. Delegation solves this problem automatically.
4. Simplified Code Maintenance
- Change logic in one place → all elements are affected
- Remove/add elements freely without listener management
- Easier debugging — only one listener to check
When NOT to Use Event Delegation
Event delegation is not always the right choice. Here are cases where you should avoid delegation:
1. Events That Don't Bubble
// ❌ focus, blur, mouseenter, mouseleave — these do NOT bubble
// Delegation will not work:
container.addEventListener('focus', function(e) {
// This will NOT fire on child focus!
console.log('This may not work for child focus events');
});
// ✅ Solution: Use focusin/focusout (these DO bubble)
container.addEventListener('focusin', function(e) {
console.log('focusin bubbles! Target:', e.target.tagName);
});
console.log('Non-bubbling events: focus, blur, mouseenter, mouseleave');
console.log('Bubbling alternatives: focusin, focusout, mouseover, mouseout');Non-bubbling events: focus, blur, mouseenter, mouseleave Bubbling alternatives: focusin, focusout, mouseover, mouseout
2. When stopPropagation is Used
If child elements call event.stopPropagation(), the event won't reach the parent.
3. High-Frequency Events on Specific Elements
If mousemove or scroll is needed only for a specific element, attach it directly — delegation adds unnecessary overhead.
4. When Target Identification is Complex
In deeply nested elements with similar structures, identifying event.target can become difficult.
5. Events Requiring Immediate Response
In gaming or animation where microseconds matter — the extra check adds overhead.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Event Delegation in JavaScript – Complete Guide with Examples (2026).
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, events, event, delegation
Related JavaScript Master Course Topics