🟨 JavaScript Intermediate

What is the Event Delegation pattern?

Answer

Event delegation is a pattern where instead of adding event listeners to each child element, you add a single listener to a parent element and use event.target to determine which child was actually clicked. This leverages event bubbling. Example: document.getElementById("list").addEventListener("click", function(event) { if (event.target.matches("li.item")) { handleItemClick(event.target); } }). Benefits: memory efficient (one listener instead of N), works for dynamically added elements (elements added after the listener was attached are also handled — no need to re-attach listeners), and simpler code. Use event.target.closest("selector") to find the nearest matching ancestor of the clicked element. Limitations: not all events bubble (blur, focus, scroll do not bubble — use capture phase or focusin/focusout instead). Event delegation is a best practice for any list, table, or dynamically generated content.