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:


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


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

copyButton.addEventListener("click", function() {
  let range = document.createRange();

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


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