Adam5
Adam5

Reputation: 67

HTML buttons that copy their own .innerHTML text content to the clipboard

Does anyone know how to make buttons that copy their own text to the clipboard with JavaScript?

My Code:

function myFunction() {
  var copyText = document.getElementByClassName("copy");
  
  copyText.select();
  document.execCommand("copy");
}
<button class="copy">Click to copy this text data to clipboard.</button>
<button class="copy">Click to copy this different text data to clipboard.</button>

Upvotes: 1

Views: 776

Answers (2)

ggorlen
ggorlen

Reputation: 57013

select is defined on text in an <input> or <textarea> element only. You could create the node element dynamically and set its innerText with the value of the button:

const copyToClipboard = text => {
  const ta = document.createElement("textarea");
  ta.textContent = text;
  document.body.appendChild(ta);
  ta.select();
  document.execCommand("copy");
  document.body.removeChild(ta);
};

for (const elem of document.querySelectorAll(".copy")) {
  elem.addEventListener("click", e => {
    copyToClipboard(e.target.innerText);
  });
}
<button class="copy">Click to copy this text data to clipboard.</button>
<button class="copy">Click to copy this different text data to clipboard.</button>

A more elegant option exists and is Chrome/FF compatible: Clipboard.writeText.

You'll need "clipboard-write" permission on the frame to perform the copy, which might not work in the stack snippet below.

for (const elem of document.getElementsByClassName("copy")) {
  elem.addEventListener("click", e => 
    navigator.clipboard.writeText(e.target.innerText)
      .catch(err => console.error(err))
  );
}
<button class="copy">Click to copy this text data to clipboard.</button>
<button class="copy">Click to copy this different text data to clipboard.</button>

Upvotes: 2

Javad Ebrahimi
Javad Ebrahimi

Reputation: 209

HTML:

<button id="btn" onclick="myFunction()">Copy text</button>

JS:

function myFunction() {
  var copyText = document.getElementById("btn");
  navigator.clipboard.writeText(copyText.textContent)
}

Upvotes: 1

Related Questions