DEV Community

Cover image for addEventListener "once"
JS Bits Bill
JS Bits Bill

Posted on β€’ Edited on

29 3 1 1

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!

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (5)

Collapse
 
salvadorweb89 profile image
Salvador Ruiz β€’

Very usefull, thanks!

Collapse
 
naozumi520 profile image
Naozumi β€’

Amazing, thanks!

Collapse
 
jyoung4242 profile image
Justin Young β€’

this just saved me a ton of headaches

Collapse
 
asosjamesinnes profile image
James Innes β€’

Keep in mind it's best practice to explicitly remove them in React (and other frameworks) to ovoid memory leaks where they might not have been removed after the callback has finished and the component has already gone through the mount/unmount lifecycle regardless.

Collapse
 
vkrms profile image
Pavel M β€’

wow dude that's pretty cool

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay