Skip to content

Instantly share code, notes, and snippets.

@AitorAlejandro
Created November 15, 2020 13:35
Show Gist options
  • Save AitorAlejandro/85e6d2238df85400d0a3e716f066ac7f to your computer and use it in GitHub Desktop.
Save AitorAlejandro/85e6d2238df85400d0a3e716f066ac7f to your computer and use it in GitHub Desktop.
How to copy a string to the clipboard
const 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);
const selected =
document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
el.select();
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
};
// Example
copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment