CodeBlanks Logo Icon CodeBlanks

once and passive options

JavaScript course · Intermediate · Lesson 41/134

Learn to run a listener once and gain performance with passive.

The once option

If you want a listener to run only once, use the once: true option. After the first trigger, the browser removes the listener automatically; it does not fire again.

button.addEventListener('click', handleClick, { once: true });

This option is useful when you want to start an action once on the first click. No manual removeEventListener call is needed.

The passive option

The passive: true option tells the browser that the listener will not call preventDefault inside. This way the browser can start scrolling immediately without waiting for the listener. This improves performance especially for events like scroll and touchmove.

box.addEventListener('scroll', handleScroll, { passive: true });

If you still call preventDefault in a passive: true listener, the browser prints a warning and the call is ignored.

Exercise Add a once: true listener for button

Define a button variable and select the #button element. Add a click listener and pass { once: true } as the third parameter.

Show example solution
const button = document.querySelector('#button');
button.addEventListener('click', () => {
  console.log('clicked');
}, { once: true });

Test yourself

  1. What does the once: true option do?

    button.addEventListener('click', () => {
      console.log('clicked');
    }, { once: true });
    • Disables the listener
    • The listener runs only once
    • The listener runs twice
    • Removes the listener immediately
    Show answer

    The listener runs only once — Correct! once: true limits the listener to a single run.

  2. Add the single-run option

    button.addEventListener('click', handleClick, {____: true });
    Show answer
    button.addEventListener('click', handleClick, {once: true });
  3. Match options to their effects

    once: true
    Runs only once
    passive: true
    preventDefault is ignored
    { }
    Listener options

All lessons in Intermediate