JS Shorts — Event Delegation

Prakhar Jaiswal
2 min readNov 28, 2020

Event delegation is a technique of adding a single event listener on a parent element instead of adding a separate one on each of the child elements.

Event delegation comes in handy when we want a similar behaviour on all the descendants of an element without adding an event listener on all the child nodes. This is possible due to the fact that every event on an element is propagated both downwards in the chain to the children and upwards in the chain to the parents all the way to the document and window.

This process of propagating an event upwards to the parent is called Bubbling while propagating an event downwards to the children is called Trickling or Capturing.

Whenever any element is clicked, the event propagates in 3 phases

  • Capture Phase (Trickling down) — The event starts at the topmost hierarchy usually the window, document and trickles down the DOM tree through the ancestors of the element. (1 through 5)
  • Target Phase — The event is triggered on the element on which the click is performed. (Point 6)
  • Bubble Phase — Finally, the event bubbles up through the ancestors of the element all the way up to the document and window. (7 through 11)

The event listeners don’t listen for the capture phase by default, but we can specify the behaviour while creating the event listener.

element.addEventListener(eventType, handler[, captureOrOptions]); 

If the third argument is true, then the listener listens for events on the capture phase. If the argument is false, then the listener captures the events of target and bubble phases.

For the example shown, notice how we’ve used a single event listener and capturing the events on all the buttons. Depending on which button was clicked, we are logging I was clicked <buttonName>. This is again possible due to event delegation.

Image by Free-Photos from Pixabay

— That’s all for today

--

--