2

my Question is not a duplicate, I'm not using Jquery, I'm not using a textarea. I want to copy the value of a variable into the Clipboard using vanilla javascript.

I'd like to copy a String of Text that is stored in a variable into the Clipboard using the onClick Eventlistener off a Button.

I tried modifiyng this example, which uses a input field, but it's not working. I'm only beginning to understand Javascript, so please be kind. Also I'm looking for a solution that doesn't use a library.

function myFunction() {
  var copyText = "This is a Test"
  copyText.select();
  document.execCommand("copy");

} 
<button onclick="myFunction()">Copy text</button> 
Roland
  • 1,638
  • 4
  • 18
  • 30
  • 1
    Possible duplicate of [Copying text of textarea in clipboard when button is clicked](https://stackoverflow.com/questions/37658524/copying-text-of-textarea-in-clipboard-when-button-is-clicked) – Mohammad Oct 29 '18 at 10:45
  • `copyText` is just a String, not a selectable HTML element – Luca Kiebel Oct 29 '18 at 10:46
  • true! but how to I get just the value of a variable into the Clipboard, without having to put it into a input field? – Roland Oct 29 '18 at 10:54
  • 1
    https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript – Mohammad Oct 29 '18 at 10:55
  • Hey Mohammad, I'm not using JQuery, I'm not using a textarea. I simply want to know how to copy the value of a variable into the Clipboard using Vanilla javascript, it might be a easy question, but it's a valid one and different from the duplicate. – Roland Oct 29 '18 at 10:57
  • Second link is for js – Mohammad Oct 29 '18 at 11:04

2 Answers2

2

You can try something like this.

function myFunction() {
  // variable content to be copied
  var copyText = "Test"
  // create an input element
  let input = document.createElement('input');
  // setting it's type to be text
  input.setAttribute('type', 'text');
  // setting the input value to equal to the text we are copying
  input.value = copyText;
  // appending it to the document
  document.body.appendChild(input);
  // calling the select, to select the text displayed
  // if it's not in the document we won't be able to
  input.select();
  // calling the copy command
  document.execCommand("copy");
  // removing the input from the document
  document.body.removeChild(input)
}
<button onclick="myFunction()">Copy text</button>
Zohir Salak
  • 5,738
  • 2
  • 9
  • 23
0

The HTMLInputElement.select() method selects all the text in a element or an element with a text field.

read more here.