0

I've been trying to copy text to the clipboard when clicking on an image but after many failed attempts, I'm stuck. Here's where I am now:

function myFunction() {
  var copyText = document.getElementById("myInput");
  copyText.select();
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
}
<input type="text" value="text which you want copy" id="myInput" hidden>
<img src="nameofimage.jpg" onclick="myFunction()"></img>

Does anyone have a solution?

vanowm's solution below works perfectly.

  • https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand is deprecated. https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API – Roko C. Buljan Aug 07 '21 at 23:13
  • It works fine on macbook pro and chrome. It actually copied the text "text which you want copy" to my clipboard. I actually pasted that in. – norcal johnny Aug 07 '21 at 23:20
  • Maybe you want to read: web.dev/async-clipboard Under "Security and permissions" you will find "As with many new APIs, the Clipboard API is only supported for pages served over HTTPS.." – A.J.Bauer Aug 08 '21 at 05:17
  • vanowm's answer works perfectly. – Warren Rosenfeld Aug 08 '21 at 17:24
  • Does this answer your question? [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – Elias Aug 08 '21 at 17:28

1 Answers1

0

You can temporary unhide the input field:

function myFunction() {
  var copyText = document.getElementById("myInput");
  copyText.hidden = false;
  copyText.select();
  document.execCommand("copy");
  copyText.hidden = true;
  alert("Copied the text: " + copyText.value);
}
<input type="text" value="text which you want copy" id="myInput" hidden>
<img src="nameofimage.jpg" onclick="myFunction()">
vanowm
  • 9,466
  • 2
  • 21
  • 37