4 min read
•Question 34 of 50mediumWhat is Event Delegation?
Understanding efficient event handling pattern.
What You'll Learn
- What event delegation is
- Why it's useful
- Implementation
What is Event Delegation?
Instead of attaching listeners to each element, attach one listener to a parent and use event bubbling.
Without Delegation
code.jsJavaScript
// Bad: One listener per button
const buttons = document.querySelectorAll('.btn');
buttons.forEach(btn => {
btn.addEventListener('click', handleClick);
});
// Problem: New buttons won't have listenersWith Delegation
code.jsJavaScript
// Good: One listener on parent
document.getElementById('button-container').addEventListener('click', (e) => {
if (e.target.matches('.btn')) {
handleClick(e);
}
});
// Works for dynamically added buttons too!Benefits
- Less memory - One listener instead of many
- Dynamic elements - Works for elements added later
- Less code - Simpler setup
Practical Example
code.jsJavaScript
// Todo list with delegation
const todoList = document.getElementById('todo-list');
todoList.addEventListener('click', (e) => {
const target = e.target;
const li = target.closest('li');
if (!li) return;
if (target.matches('.delete-btn')) {
li.remove();
} else if (target.matches('.complete-btn')) {
li.classList.toggle('completed');
}
});
// Adding new todos works automatically
function addTodo(text) {
const li = document.createElement('li');
li.innerHTML = `
${text}
<button class="complete-btn">✓</button>
<button class="delete-btn">×</button>
`;
todoList.appendChild(li);
}