Intermediate LevelJavaScript & TypeScript
What is Event Bubbling, Event Capturing, and Event Delegation in JavaScript?
❓ Interview Prompt: Explain the 3 phases of DOM event propagation and how Event Delegation optimizes event listener performance.
DOM events propagate through the document tree in 3 distinct phases:
1
Capturing Phase: Event travels down from
window to the target element.2
Target Phase: Event arrives at the actual target element.
3
Bubbling Phase: Event bubbles back up from the target element to
window.Event Delegation Pattern:
Instead of attaching individual event listeners to hundreds of child elements (e.g. list items), attach ONE listener to a common parent. Use e.target to identify which child triggered the event.
Code Implementation Example
javascript
// Event Delegation: single listener on parent <ul>
const userList = document.getElementById('user-list');
userList.addEventListener('click', (event) => {
// Check if click originated from a button inside an <li>
const deleteBtn = event.target.closest('.delete-btn');
if (deleteBtn) {
const userId = deleteBtn.dataset.id;
console.log('Deleting user:', userId);
event.stopPropagation(); // Stop further bubbling if needed
}
});💡Event delegation using closest() to handle dynamic list item clicks efficiently.
🎯 Interview Key Takeaway
Event delegation handles clicks on dynamic or numerous child elements using a single parent listener via event bubbling.
#DOM#Events#Delegation#Intermediate
Back to all JavaScript & TypeScript Questions→