Skip to main content

Event delegation (Event Delegation)

Event delegation is a technique in JavaScript where we attach a handler not to every element, but to their common parent, using event bubbling to figure out which exact element the action happened on.

In other words: one listener handles events for many child elements.


Why this is needed (key talking points for interviews)

  • Fewer handlers -> less memory, a faster page.
  • Works for dynamically added elements -> even if an element appears later, the parent handler will still "catch" it.
  • Better manageability -> all the logic sits in one place, not scattered across the DOM tree.

A simple example

We want to handle clicks on 100 buttons:

Naive:

js
document.querySelectorAll('button').forEach(btn => { btn.addEventListener('click', () => { console.log('clicked'); }); });

Correct (delegation):

js
document.body.addEventListener('click', (event) => { if (event.target.matches('button')) { console.log('clicked'); } });

How does this work?

  1. The user clicks a button.
  2. The event bubbles up the tree.
  3. The handler on body intercepts the event.
  4. We check event.target to identify the candidate element.

A common interview mistake

Confusing target and currentTarget:

  • event.target is the element that was clicked (the source).
  • event.currentTarget is the element the listener is attached to (the parent).

A short definition (if the interviewer asks for a brief answer)

Event delegation is a technique where a single handler on the parent handles events for many child elements, using event bubbling.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.