Me
  • 1 min read

Handling an Event Callback Once

An interesting tidbit I stumbled upon recently is the ability to remove an event listener once called.

In the past, I would have added an event listener to an element and then removed it within the callback function. It would have looked something like this:

const button = document.querySelector('button')

button.addEventListener('click', function onClick() {
  console.log('clicked')
  button.removeEventListener('click', onClick)
})

In this example, an event listener is attached to the button element, and once clicked, the listener is removed.

This code can be cleaned up by passing one additional argument to the event listener, { once: true }.

const button = document.querySelector('button')

button.addEventListener(
  'click',
  function onClick() {
    console.log('clicked')
  },
  {once: true}
)

This example functions precisely like the example above, except requires less code. Less code equals less potential bugs to fix later 😁.


Last updated on
Found a typo or problem? Edit on Github