Event Delegation: Real-World Examples
Real-world examples of event delegation in action.
Event Delegation: Real-World Examples
Todo List (Add/Remove)
todoList.addEventListener("click", (e) => { if (e.target.matches(".delete-btn")) e.target.closest("li").remove(); if (e.target.matches(".toggle-btn")) e.target.closest("li").classList.toggle("done"); });
Shopping Cart
cart.addEventListener("click", (e) => { if (e.target.matches(".increase")) updateQty(e.target.dataset.id, 1); if (e.target.matches(".decrease")) updateQty(e.target.dataset.id, -1); if (e.target.matches(".remove")) removeItem(e.target.dataset.id); });
Data Table
table.addEventListener("click", (e) => { const row = e.target.closest("tr"); if (e.target.matches(".sort-btn")) sortTable(e.target.dataset.column); if (e.target.matches(".edit-btn")) editRow(row.dataset.id); if (e.target.matches(".delete-btn")) deleteRow(row.dataset.id); });
Tab Navigation
tabs.addEventListener("click", (e) => { if (e.target.matches(".tab")) switchTab(e.target.dataset.tab); });
The Takeaway
Real-world examples: todo list (delete/toggle), shopping cart (increase/decrease/remove), data table (sort/edit/delete rows), and tab navigation (switch tabs). All use one listener on the parent and check e.target.matches() or e.target.closest().
todoList.addEventListener('click', e => { if (e.target.matches('.delete-btn')) e.target.closest('li').remove(); if (e.target.matches('.toggle-btn')) e.target.closest('li').classList.toggle('done'); }). One listener handles delete and toggle for all items.
cart.addEventListener('click', e => { if (e.target.matches('.increase')) updateQty(e.target.dataset.id, 1); if (e.target.matches('.decrease')) updateQty(e.target.dataset.id, -1); if (e.target.matches('.remove')) removeItem(e.target.dataset.id); }).
table.addEventListener('click', e => { const row = e.target.closest('tr'); if (e.target.matches('.sort-btn')) sortTable(e.target.dataset.column); if (e.target.matches('.edit-btn')) editRow(row.dataset.id); }).
tabs.addEventListener('click', e => { if (e.target.matches('.tab')) switchTab(e.target.dataset.tab); }). One listener on the tab container handles all tab clicks. Check e.target.matches('.tab') and use dataset.tab to identify which tab.
Yes. Use e.target.matches() to check for different buttons: if (e.target.matches('.delete-btn')) deleteItem(); if (e.target.matches('.edit-btn')) editItem();. One listener handles all actions.
Ready to master React completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.
Master React
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course.

