Event.target.closest | Adactio

A lot of JavaScript used on web pages simply waits for a user to click on some element on the page, and then executes a function.

The traditional way of handling this is to use event listeners, but Jeremy points out that this can get a bit hard to maintain if you're applying lots of them.

Instead, use event.target.closest and a universal event listener (e.g. apply a click listener to the whole page) to determine the target and then apply the relevant function. Much neater!

document.addEventListener('click', doSomethingSpecial, false);

function doSomethingSpecial(event) {
  if (event.target.closest('button.special')) {
    // do something
  }
}

On the problems of applying event listeners en masse:

But if you’ve got a lot of special buttons, you’ve now got a lot of event listeners.
The code you’ve written runs once, when the page loads.

If a new special button shows up on the page, it won’t have an event handler attached to it.

On how closest() can help invert that logic and (possibly) improve efficiencies:

You can switch things around. Instead of adding lots of event handlers to lots of elements, you can add one event handler to the root element. Then figure out whether the element that just got clicked is special or not.

On closest() vs matches():

There’s a similar method to closest called matches. But that will only work if the user clicks directly on the element you’re interested in.

Explore Other Notes

Older

Breaking out of the box

Patrick Brosset covers a range of new(ish) web and browser APIs that allow PWAs to benefit from OS-level functionality to style and utilise more of the browser chrome. Specifically, the Windows […]
  • A lot of JavaScript used on web pages simply waits for a user to click on some element on the page, and then executes a […]
  • Murray Adcock.
Journal permalink