How to click a button to copy to clipboard with JavaScript?

Spread the love

Sometimes, we wanmt to click a button to copy to clipboard with JavaScript.

In this article, we’ll look at how to click a button to copy to clipboard with JavaScript.

How to click a button to copy to clipboard with JavaScript?

To click a button to copy to clipboard with JavaScript, we can use the navigator.clipboard.writeText method.

For instance, we write

document.querySelector(".copy-text").addEventListener("click", async () => {
  await navigator.clipboard.writeText(textToCopy);
  window.alert("Success! The text was copied to your clipboard");
});

to select the button with querySelector.

Then we add a click event listener to it with addEventListener.

We set the click listener to a function that calls navigator.clipboard.writeText to copy the textToCopy string to the clipboard.

It returns a promise so we use await to wait for the promise to resolve.

Conclusion

To click a button to copy to clipboard with JavaScript, we can use the navigator.clipboard.writeText method.

Leave a Reply

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