0

I want to copy a default value to clipboard, without using input. Thats something wrong with my function, but I don't know what it is.

var copyText = "Default value";
const showText = document.querySelector(".copied");

const copyMeOnClipboard = () => {
  copyText;
  document.execCommand("copy")
  showText.innerHTML = `Copied!`
  setTimeout(() => {
    showText.innerHTML = ""
  }, 1000)
}
      
<button class="submitBtn" onclick="copyMeOnClipboard();">Copy link</button>
<p class="copied"></p>
  • 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) – Solomon Feb 27 '21 at 01:25

1 Answers1

1

From MDN's page on execCommand, emphasis added:

Copies the current selection to the clipboard. Conditions of having this behavior enabled vary from one browser to another, and have evolved over time.

You'll want to use the Clipboard API's writeText instead, like so:

var copyText = "Default value";
const showText = document.querySelector(".copied");

const copyMeOnClipboard = () => {
    navigator.clipboard.writeText(copyText).then(() => {
        showText.innerHTML = `Copied!`
        setTimeout(() => {
            showText.innerHTML = ""
        }, 1000)
    })
}
<button class="submitBtn" onclick="copyMeOnClipboard();">Copy</button>
<p class="copied"></p>
Solomon
  • 336
  • 4
  • 14