Event Bubbling, Capturing, and Delegation
Instead of attaching 100 individual event listeners to 100 list items, event delegation lets you attach a single listener to their parent container.
What is it?
Event Bubbling is the process where an event triggered on a child element propagates ('bubbles') upward through its ancestors in the DOM tree. Event Delegation is a technique that leverages bubbling to handle events at a parent level.
Why is it used?
Improves memory performance and automatically handles dynamically created elements added to the DOM later.
Detailed Explanation
Syntax Structure
parentContainer.addEventListener('click', (e) => {
const btn = e.target.closest('.delete-btn');
if (btn) {
// Handle button action
}
});
Code Example
const chapterList = document.getElementById("chapterAccordionList");
// Single Event Listener on parent container handles all chapters
chapterList.addEventListener("click", (e) => {
// Find clicked chapter header toggle button
const headerBtn = e.target.closest(".chapter-header-btn");
if (!headerBtn) return; // Ignore clicks elsewhere inside container
const chapterContent = headerBtn.nextElementSibling;
const isExpanded = headerBtn.getAttribute("aria-expanded") === "true";
// Toggle accordion state
headerBtn.setAttribute("aria-expanded", !isExpanded);
chapterContent.classList.toggle("collapsed");
});
Explanation of the Code
Expected Output
Real-World Application
Used across sidebar menus, data tables, and kanban boards with hundreds of interactive rows.
Common Mistakes to Avoid
Quick Practice Challenge
Create an event delegation listener on a `<ul>` that logs the text of whichever `<li>` was clicked.