Home > shorts > Add the option to addEventListener() to call it once

Add the option to addEventListener() to call it once


You can add the option { once: true } to an event listener to automatically remove it when has been invoked.

A Boolean indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.

const regularButton = document.getElementById('regular')
regularButton.addEventListener('click', () => {
  console.log("Always works")
})

const onceButton = document.getElementById('once')
onceButton.addEventListener('click', () => {
  console.log("Just one time")
}, {
  once: true
})

Check the demo here => CodePen

© 2021, Andrew Losseff