FrontendIntermediateJavaScript
Event Delegation
Pronunciationih-VENT del-ih-GAY-shun
Definition
Event delegation means attaching one event listener to a parent element instead of one to every child, and using the event's target to find which child was clicked. It relies on event bubbling.
Where you hear it
In vanilla JavaScript code, performance reviews of long lists and interview questions about the DOM.
Examples
Attach the click listener to the
<ul>and checkevent.targetfor the<li>.Items added later work automatically with delegation.
One listener on the table handles clicks on all of its rows, even the new ones.
Common mistake
Using it for events that don't bubble (like focus). Use focusin or attach directly.
Don't confuse with
Event bubbling, the behaviour that makes events travel upward. Delegation is the technique that uses it.
Say it at work
- In a meeting or chat
Delegate the click handling to the container.
- In an email or ticket
Check
event.target.closest('button').