When an event occurs on a DOM element, it does not execute in isolation. The event travels through the document hierarchy in a process known as Event Propagation. Understanding event propagation unlocks Event Delegation—the single most important performance optimization in frontend web development.
Figure 7: The 3 phases of event flow: Phase 1 Capturing (Downwards) -> Phase 2 Target -> Phase 3 Bubbling (Upwards).
window) and travels downwards through document, <html>, <body>, reaching towards the target. (Captured via { capture: true }).window, triggering any listener registered on ancestor elements.Imagine an e-commerce table or shopping cart with 1,000 product rows. Attaching 1,000 separate event listeners wastes massive memory. With Event Delegation, you attach ONE listener to the parent <table>:
// HTML Structure:
// <table id="product-table">
// <tr><td>Book</td><td><button class="btn-delete" data-id="1">Delete</button></td></tr>
// <tr><td>Pen</td><td><button class="btn-delete" data-id="2">Delete</button></td></tr>
// </table>
const table = document.getElementById("product-table");
// A SINGLE listener handles clicks for ALL existing and FUTURE rows!
table.addEventListener("click", (e) => {
// Check if clicked element was a delete button:
if (e.target.classList.contains("btn-delete")) {
const productId = e.target.getAttribute("data-id");
console.log(`Deleting Product #${productId} from inventory!`);
// Remove row from DOM
const tableRow = e.target.closest("tr");
tableRow.remove();
}
});
Exam Question: "What are the benefits of Event Delegation?"
How do you validate user form input in real-time before sending data to backends? Proceed to: JavaScript Form Validation & Input Handling →