DEV Community

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

Posted on

2 2

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);
Enter fullscreen mode Exit fullscreen mode

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 }
);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay