Aaron Mazie
Aaron Mazie

Reputation: 763

Copy To Clipboard Function With Javascript

New to JavaScript and I'm trying to have a button copy some text in the code to the clipboard. This doesn't seem to work.. Please let me know what I'm missing. Thanks!

<!DOCTYPE html>
<html>
<body>

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

<script>
function myFunction() {
  var copyText = "myText";
  copyText.select();
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
}
</script>

</body>
</html>

Upvotes: 1

Views: 705

Answers (1)

Dodo
Dodo

Reputation: 228

The reason it wasnt working is because you cant do to a varaible .select() so when you do a document.execCommand("copy") your copying any other selected text try putting the stuff in a input box and then try .select()

<!DOCTYPE html>
<html>
<body>
<input id="myId" value="myText"> </input>
<button onclick="myFunction()">Copy text</button>

<script>
function myFunction() {
  var copyText = document.getElementById("myId");
  copyText.select();
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
}
</script>

</body>
</html>

and if you want to hide the textbox do

<!DOCTYPE html>
<html>
<body>
<input id="myId" value="myText" style="display:none;"> </input>
<button onclick="myFunction()">Copy text</button>

<script>
function myFunction() {
  var copyText = document.getElementById("myId");
  copyText.style = "display:inline";
  copyText.select();
  copyText.style = "display:none";
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
}
</script>

</body>
</html>

Upvotes: 2

Related Questions