-1

How can I copy a simple string (for instance "foobar") to clipboard using JavaScript?

(jQuery is also accepted, since I already use it)

I've searched half an hour and still haven't found an easy solution, I can't believe it's so hard.

Quuzuu
  • 131
  • 1
  • 8
  • 4
    Possible duplicate of [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – notvita Jan 23 '18 at 01:38
  • 3
    I'm a little bit puzzled. [Just entering your question title into google](https://www.google.de/search?q=How+to+copy+a+string+into+clipboard+in+JavaScript) yields pages of good results for me. – phihag Jan 23 '18 at 01:38
  • 2
    Did you even search? – epascarello Jan 23 '18 at 01:38
  • **I proposed this answer to copy to clipboard:** https://stackoverflow.com/a/48371326/1715121 – Ele Jan 23 '18 at 01:38

1 Answers1

0

Here you have:

function copyText(text) {
  var $input = $("<input>");
  $("body").append($input);
  $input.val(text).select();
  document.execCommand("copy");
  $input.remove();
}

// Usage:
copyText("try!");

you can try this by pasting it in dev console and you'll have the text in your clipboard.

Luis Gonzalez
  • 531
  • 5
  • 16
  • Thanks! But why does it only work in console but not in html+js? It's really weird. I also found a vanilla js version very similar to yours, and it's the same problem, only works in console – Quuzuu Jan 23 '18 at 12:50
  • Yes I tried, it doesn't work, super strange. I've never seen anything like this – Quuzuu Jan 23 '18 at 18:34
  • where is the data you want to copy?, has value of an input? – Luis Gonzalez Jan 23 '18 at 21:37