JS Bits with Bill
JS Bits with Bill


JS Bits with Bill

addEventListener "once"

addEventListener "once"

JS Bits with Bill's photo
JS Bits with Bill
ยทJul 23, 2020ยท

1 min read

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 });

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);

The more you know! ๐ŸŒˆ


MDN Article on addEventListener()

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

Share this