addEventListener "once"

js_bits_bill

JS Bits Bill

Posted on July 23, 2020

addEventListener "once"

If you want to add an event callback but have it run only once, you can simply use the once option in the method's options object:

  document.body.addEventListener('click', () => {
    console.log('I run only once! 😇');
  }, { once: true });
Enter fullscreen mode Exit fullscreen mode

This prevents the need to otherwise immediately remove the event listener after the callback first fires (which I've been guilty of!):

  document.body.addEventListener('click', cb);

  function cb() {
    console.log('Hi! 👋');
    document.body.removeEventListener('click', cb);
  }
Enter fullscreen mode Exit fullscreen mode

The more you know! 🌈

Links

MDN Article on addEventListener()


Check out more #JSBits at my blog, jsbits-yo.com. Or follow me on Twitter!

💖 💪 🙅 🚩
js_bits_bill
JS Bits Bill

Posted on July 23, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related