DEV Community

Raj Maharjan
Raj Maharjan

Posted on

2

DOM Event delegation pattern

If you have multiple button element with a similar callback function inside a div element, you can delegate event listeners to the parent div element instead of listening to each button.

// poor practice

<div>
  <button onclick="myFunction("red")">Red</button>
  <button onclick="myFunction("blue")">Blue</button>
  <button onclick="myFunction("black")">Black</button>
</div>
Enter fullscreen mode Exit fullscreen mode

// good practice

<div onclick="myFunction(event)">
  <button id="red">Red</button>
  <button id="blue">Blue</button>
  <button id="black">Black</button>
</div>
Enter fullscreen mode Exit fullscreen mode

// script

function myFunction(event) {
  let target = event.target;
  if (target.nodeName.toLowerCase() !== "button") {
    return;
  }

  // do something with id
  ...
}
Enter fullscreen mode Exit fullscreen mode

The drawback is that you have to write a bit more code to filter out unnecessary events, but it will drastically increase the performance and provide cleaner code which outweighs the drawback significantly.

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