Event delegation in Javascript

Content

Rajan Lagah
3 min readNov 24, 2021
  • Event bubbling and Capturing
  • Event delegation

When the user interacts with dom with an event like click / keyup that event is propagated in cycle

Event bubbling and Capturing

Capturing is when the event is traveling down to the clicked item and bubbling is when the event is going up ( like a bubble in water ) from the clicked item.

for example in

const grandParent = document.getElementById('grandparent')
const parent = document.getElementById('parent')
const child = document.getElementById('child')
let isBubbling = false
grandParent.addEventListener('click',()=>{
console.log("GRAND PARENT IS CLICKED")
},isBubbling)
parent.addEventListener('click',()=>{
console.log("parent IS CLICKED")
},isBubbling)
child.addEventListener('click',()=>{
console.log("child IS CLICKED")
},isBubbling)

If we create a simple nested div UI (like one in the image) and add an event listener to all divs then click on the child the output in the console will be.

When you set variable ‘isBubbling’ to true then the output will be

Event delegation

In event delegation, we use Event bubbling to use the event listener of the parent instead of assigning the event listener to every child. In this way, we have few event listeners which is good for performance.

For example

<ul class="event-delegation">
<li id="item1">ITEM 1</li>
<li id="item2">ITEM 2</li>
<li id="item3">ITEM 3</li>
</ul>

We want to fire some events on the list item click. One way is to add event listener ‘click’ on each list item which will create 3 event listeners ( and more if we have more list items ). To optimize here we can

const eventDelegation = document.querySelector('.event-delegation')eventDelegation.addEventListener('click',e =>{
console.log('Clicked on ',e.target)
})

use this code instead.

Here we are having 1 event listener which is on the parent component. And now when we click on each list item we will see.

This way we optimize our code.

Note

  • preventDefault function doesn't stop event propagation.

Drawbacks

  • we have event.stopPropagation() method will stop the cycle of events so we have to take care of this in our code. Because if a child calls this method then the parent will not fire the event.
  • Not all events are propagated like scroll and window resize.

This article is my notes from this video. Go check out this and hope you get something new to learn out of this.

--

--