Skip to content

Instantly share code, notes, and snippets.

@aslamanver
Created March 15, 2019 09:09
Show Gist options
  • Save aslamanver/97c104f98276f3f2e80515aaf9cde662 to your computer and use it in GitHub Desktop.
Save aslamanver/97c104f98276f3f2e80515aaf9cde662 to your computer and use it in GitHub Desktop.
Copy Strings to the Clipboard using pure JavaScript
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