Event Delegation and Bubbling
Event delegation is a technique where you attach a single event listener to a parent element to handle events on its children, leveraging event bubbling.
Event Bubbling
<div id="parent">
<button id="child">Click me</button>
</div>
document.getElementById('parent').addEventListener('click', e => {
console.log('Parent clicked');
});
document.getElementById('child').addEventListener('click', e => {
console.log('Child clicked');
// e.stopPropagation(); // Stops bubbling
});
// Clicking button logs:
// "Child clicked"
// "Parent clicked"Event Delegation Example
<ul id="todo-list">
<li>Task 1</li>
<li>Task 2</li>
<li>Task 3</li>
</ul>
// Instead of:
document.querySelectorAll('li').forEach(li => {
li.addEventListener('click', handleClick);
});
// Use delegation:
document.getElementById('todo-list').addEventListener('click', e => {
if (e.target.tagName === 'LI') {
handleClick(e);
}
});
// Works for dynamically added items too:
todoList.innerHTML += '<li>New Task</li>';Advanced Delegation
// Multiple actions using data attributes
<div id="actions">
<button data-action="save">Save</button>
<button data-action="delete">Delete</button>
<button data-action="edit">Edit</button>
</div>
document.getElementById('actions').addEventListener('click', e => {
const action = e.target.dataset.action;
if (action) {
handlers[action](e);
}
});Key Concepts
- Events bubble up through the DOM tree
- Delegation reduces memory usage
- Works with dynamic elements
- Improves performance with many elements
Common Interview Follow-up Questions
- What's the difference between bubbling and capturing?
- How do you stop event propagation?
- When should you not use event delegation?
- How does event delegation improve performance?
Best Practices
- Use delegation for lists and tables
- Check target elements carefully
- Consider using closest() for better matching
- Be aware of events that don't bubble
- Use data attributes for flexible handling