How to copy to the clipboard on button click with JavaScript?

Spread the love

To copy to the clipboard on button click with JavaScript, we use the Clipboard API.

For instance, wwe write

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

to call navigator.clipboard.writeText with the textToCopy to copy the string to the clipboard.

We call addEventListener to add the function with the code as the click listener for the element with class copy-text.

Leave a Reply

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