Home > Tips & Tricks > JavaScript – Fire Events Only Once

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 😉

Photo of author

About Aman Mehra

Hey there! I'm Aman Mehra, a full-stack developer with over six years of hands-on experience in the industry. I've dedicated myself to mastering the ins and outs of PHP, WordPress, ReactJS, NodeJS, and AWS, so you can trust me to handle your web development needs with expertise and finesse. In 2021, I decided to share my knowledge and insights with the world by starting this blog. It's been an incredible journey so far, and I've had the opportunity to learn and grow alongside my readers. Whether you're a seasoned developer or just dipping your toes into the world of web development, I'm here to provide valuable content and solutions to help you succeed. So, stick around, explore the blog, and feel free to reach out if you have any questions or suggestions. Together, let's navigate the exciting world of web development!

Leave a Comment