DEV Community

Cover image for One Time Event Listeners in JavaScript
Naveen.S
Naveen.S

Posted on

One Time Event Listeners in JavaScript

It is very easy to add an event to any object in JavaScript by using addEventListener(). We can even add multiple event listeners to a single object that too of the same type. These events will not override each other and will execute properly as expected without affecting each other’s working.

// Syntax
element.addEventListener(event, functionName, useCapture);

Event listeners are great, addEventListener() is used everywhere. But, there is a problem. The listener gets executed every time the event is fired. We may not want this to happen in each and every scenario.

The options parameter is an object that specifies configurations about the event listener. This allows us to configure the event listener with a once option to use it just for a single time. This is a cleaner approach and also we don’t have to keep track of the element or node.

const button = documentgetElementById('button');

button.addEventListener(
  "click", () => {
    console.log('I will fire only once')
  },
  { once: true }
);

Top comments (0)