DEV Community

Raj Maharjan
Raj Maharjan

Posted on

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)