JavaScript – Fire Events Only Once

Hello friends, in this trick, we will see how we can fire the javascript events only once. We will prevent the events to trigger again when its already triggered.

This trick is useful when you need a fire any events and you don’t need further that event to be triggered.

Fire Events Using once Option

We can use the once option with boolean true value to event listeners to run the events only once.

You have to add the { once: true } option to the event listener to make sure the event will only be triggered once on a given element.

See the following trick to fire the javascript events only once.

In the above code, we get the element of the button class and add a click event listener to it. So when the user will click on the button, it will trigger but if he tries to click again, the event will not trigger this time. Because we added the once option as a true parameter to the event listener.

It is a great alternative of removeEventListener() method. You can also use this removeEventListener() method but the above trick is a great way to fire the javascript events only once.

Being Tricky 😉

Leave a Reply

Your email address will not be published.