«   Previous tip Next tip   »

JavaScript: Automatically remove an event listener after it has executed

Last updated: 19th July 2020
Automatically remove an event listener after it has executed

In your JavaScript code, you can automatically remove an event listener after it has executed. Here's the code:

el.addEventListener('click', console.log, {
    once: true
})

Removing event listeners, assuming they're not needed anymore, with {once: true} will improve performance, and help your web app feel more responsive.

As shown on MDN, the once flag is defined as follows:

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.

Browser support is great apart from Internet Explorer.

«   Previous tip Next tip   »

Sign up to receive a developer tip, in the form of a gif, in your inbox each week