[Javascript]How to write One-Time EventListener

In modern major browsers, you don’t need removeEventListener or flags to execute an event only once in JavaScript.
There’s a fantastic option available, so let’s take a closer look.

The wonderful {once: true}

Just by adding {once: true} to the third argument, it will execute the event only once. Wonderful!

window.addEventListener('scroll', () => {
}, {once: true})

In the case of jQuery

In the case of jQuery, the “one” method is available.

$(window).one('scroll', () => {

Browser support for {once: true}

It appears that {once: true} is already supported in major browsers.

Reference:“once” event listener option” | Can I use…

If IE support is required

If IE support is necessary, we have no choice but to use removeEventListener.
It seems to be supported in IE9 and above.

Reference:“removeEventListener” | Can I use…

window.addEventListener('scroll', hoge = () => {
    // Perform some operation before executing removeEventListener.
    this.removeEventListener('scroll', hoge)

That is all, it was about how to write One-Time EventListener.

Sponsored Link

You can subscribe by SNS

Sponcerd Link

Leave a Reply