How to Create a Copy Button in HTML and JavaScript?

Estimated read time 1 min read

Here’s an example of how you can create a copy button in HTML and JavaScript:

HTML:

<p id="text">This is the text to be copied.</p>
<button id="copy-button">Copy</button>

JavaScript:

let copyButton = document.querySelector("#copy-button");
let text = document.querySelector("#text");

copyButton.addEventListener("click", function() {
  let range = document.createRange();
  range.selectNode(text);
  window.getSelection().addRange(range);

  try {
    document.execCommand("copy");
  } catch (error) {
    console.error("Unable to copy text.", error);
  }

  window.getSelection().removeAllRanges();
});

When the copy button is clicked, the text in the <p> element with the id “text” will be selected, then copied to the clipboard using the document.execCommand("copy") method. If the method is not supported by the user’s browser, an error message will be logged to the console.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply