How to Copy JavaScript with a Click of a Button?

Estimated read time 1 min read

You can copy text in JavaScript with the click of a button by using the clipboard.writeText() method from the Clipboard API. Here’s an example:

<button id="copy-button">Copy Text</button>

<script>
  const copyButton = document.getElementById("copy-button");

  copyButton.addEventListener("click", function() {
    navigator.clipboard.writeText("This text will be copied.").then(function() {
      console.log("Text copied successfully.");
    }, function(err) {
      console.error("Failed to copy text: ", err);
    });
  });
</script>

In this example, we get a reference to the button element and attach a click event listener to it. When the button is clicked, the writeText() method is called with the text that we want to copy. The method returns a promise that resolves if the text was copied successfully and rejects if an error occurred.

Note that this feature is supported in modern browsers, but may not work in older browsers.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply