Create 'Automatic copy to clipboard' javascript

I want a page to copy some preset text to the clipboard for a user on load.

function myFunction() {
  var copyText = document.getElementById("myInput");
  copyText.select();
  copyText.setSelectionRange(0, 99999)
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
  console.log(copyText.value)
}

function myClick() {
  document.getElementById("myButton").click();
}
<body onload="myClick()">
    <input type="text" value="COPIED" id="myInput">
    <button onclick="myFunction()" id="myButton">Copy text</button>
</body>

The alert appears and the console logs the value – COPIED

But the text isn’t actually copied to the clipboard. Clicking on the button ‘Copy text’ – does work?

12 thoughts on “Create 'Automatic copy to clipboard' javascript”

Leave a Comment