JS Tip of the Day: addEventListener Options

addEventListener Options
Level: Beginner

Old school JavaScript coders may recognize the addEventListener function signature as something looking like the following:

eventTarget.addEventListener(type, listener, useCapture)

Where the only option available is the useCapture option in the 3rd argument. Modern implementations of addEventListener, however, support an options object in place of useCapture. This options object supports the useCapture option (now capture) as well as a few others, including:

  • capture: A Boolean indicating that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree.
  • once: A Boolean indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.
  • passive: A Boolean which, if true, indicates that the function specified by listener will never call preventDefault(). If a passive listener does call preventDefault(), the user agent will do nothing other than generate a console warning. See Improving scrolling performance with passive listeners to learn more.

So presently, the signature of addEventListener is as follows:

eventTarget.addEventListener(type, listener, { capture, once, passive })

And future iterations of addEventListener could add even more options.

Curious if the browser your users are using supports this options object? It’s easy. Just use the ridiculous approach outlined in the MDN link below.

More info: