DEV Community

Jyoti Prakash Pradhan
Jyoti Prakash Pradhan

Posted on

3 1

Event Delegation in JS

Event delegation is a concept to handle events in JS in more performant way. It uses the concept of event bubbling to achieve the same. Event capturing concept can also be used but event bubbling is the preferred approach.

Suppose there is list of items, i.e. lis inside an uland clicking on each li some action is expected to occur. So the common approach is to add event listener to each li in the list.

HTML

<ul id='list'>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  ...
</ul>
Enter fullscreen mode Exit fullscreen mode

Without event delegation

const items = document.querySelectorAll('#list li');
const handleClick = () => {
  // do something here ...
};

// listener added to each li
items.forEach(item => {
  item.addEventListener('click', handleClick)
});
Enter fullscreen mode Exit fullscreen mode

In this approach the number of event handlers attached are same as the number of lis present in the list, which will consume more JS memory.
So to solve this issue we can use the Event delegation approach here.

With event delegation

const list = document.querySelector('#list');

const handleClick = (event) => {
  if (event.target.tagName === 'LI') {
    // do something here
  }
};

// listener added to ul
list.addEventListener('click', handleClick);
Enter fullscreen mode Exit fullscreen mode

In the above sample code, only one event handler is being added to the parent ul#list. Now in the handler if the target.tagName is a LI then the required task is performed. Thus the number of handlers are reduced to one, which consumes less JS memory.

For more info about event bubbling

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay