Create a One-Off Event Handler

When you use the addEventListener() method to add an event handler to an event of an element, the event handler will execute every time the event occurs.

To create a one-off event handler that only executes once, you use the third parameter of the addEventListener() method:

element.addEventListener(type,handler,{once: true});Code language: CSS (css)

The third parameter of the addEventListener() method is an object that has a property once. If it is set to true, then the event handler will execute only once.

The following example shows how to create a one-time event handler. Suppose that you have a button with the class .btn:

<button class="btn">Subscribe</button>Code language: HTML, XML (xml)

The following adds the one-off event handler to the click event of the button:

const btn = document.querySelector('.btn');

btn.addEventListener('click', function (e) {
  alert('Subscribed!');
}, {
  once: true
});Code language: JavaScript (javascript)

If you click the button, it will show the alert dialog only once.

Was this tutorial helpful ?