-4

So I am trying to find a code that will automatically copy a text when you click on it with no button.

What I mean by this:

Say we have a symbol and this symbol is "T". When you click on T it should copy "T" to your clipboard. I do not want a button either.

D. Doke
  • 3
  • 4
  • What did you try? What happened? – SLaks Nov 29 '17 at 21:30
  • 2
    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) – Obsidian Age Nov 29 '17 at 21:30
  • Obsidian Age, this is not a duplicate. Please reread what I said. I don't want to copy it manually. I want it to be automatic. – D. Doke Nov 29 '17 at 21:33
  • Define "*automatic*". Should it happen as you type? Then just call the JavaScript method `onkeyup`. Automation is only an additional `1%` of the above duplicate. And yes, this has to be done in JavaScript; it cannot be done in raw HTML. – Obsidian Age Nov 29 '17 at 21:37
  • 1
    Automatic? Yet your question says "when you **click** on it". The copy is triggered by a user event. You respond to that event. Just how much more automatic do you want to get? –  Nov 29 '17 at 21:45

1 Answers1

1

In general, you can copy selected text to the clipboard using document.execCommand("copy") (part of the Clipboard API), and you can detect when the user selects text by listening for the selectionchange event (part of the Selection API).

However, these features don't work together. At least in Chrome, the copy command only works when a script is running as the direct result of a user interaction, like a click or keypress -- and selectionchange events don't seem to count as user interactions. So you may be out of luck, unless there's something I've overlooked.