Skip to content

Instantly share code, notes, and snippets.

@mitchmoser
Created December 25, 2018 09:25
Show Gist options
  • Save mitchmoser/3aeaa853f14c078e88be56bf0263cd39 to your computer and use it in GitHub Desktop.
Save mitchmoser/3aeaa853f14c078e88be56bf0263cd39 to your computer and use it in GitHub Desktop.
/*
* Source:
* https://stackoverflow.com/questions/13899299/write-text-to-clipboard#18258178
*/
function copyStringToClipboard(str) {
// Create new element
var el = document.createElement('textarea');
// Set value (string to be copied)
el.value = str;
// Set non-editable to avoid focus and move outside of view
el.setAttribute('readonly', '');
el.style = {position: 'absolute', left: '-9999px'};
document.body.appendChild(el);
// Select text inside element
el.select();
// Copy text to clipboard
document.execCommand('copy');
// Remove temporary element
document.body.removeChild(el);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment