Categories
JavaScript Answers

How to add an event for a one time click to a function with JavaScript?

Spread the love

Sometimes, we want to add an event for a one time click to a function with JavaScript.

In this article, we’ll look at how to add an event for a one time click to a function with JavaScript.

How to add an event for a one time click to a function with JavaScript?

To add an event for a one time click to a function with JavaScript, we can call addEventListener with the once option set to true.

For instance, we write:

<button>
  click me
</button>

to add a button.

Then we write:

const button = document.querySelector('button')
button.addEventListener("click", () => {
  console.log('clicked')
}, {
  once: true
});

to select the button with querySelector.

Then we call button.addEventListener with 'click' and a click event listener callback to add a click listener to the button.

The callback will only run once since once is set to true in the object in the 3rd argument.

Conclusion

To add an event for a one time click to a function with JavaScript, we can call addEventListener with the once option set to true.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *