What is JS code to copy text to clipboard?

View QuestionsCategory: QuestionsWhat is JS code to copy text to clipboard?
admin Staff asked 3 years ago

How can I copy some text into clipboard for user?

1 Answers
admin Staff answered 3 years ago

It is possible:

1
2
3
4
5
6
7
8
9
10
11
12
13
function hrc_copyToClipboard (str){
  const el = document.createElement('textarea');
  el.value = str;
  el.setAttribute('readonly', '');
  el.style.position = 'absolute';
  el.style.left = '-9999px';
  document.body.appendChild(el);
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
};

hrc_copyToClipboard("Hi anatolii!!");

credit to https://www.30secondsofcode.org/blog/s/copy-text-to-clipboard-with-javascript
above is modified version

What it does:
make text area
hide text area
copy text
delete text area when done