Skip to content

Instantly share code, notes, and snippets.

@paulund
Created August 26, 2018 12:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulund/07c66550320991743aaeb42ddb891310 to your computer and use it in GitHub Desktop.
Save paulund/07c66550320991743aaeb42ddb891310 to your computer and use it in GitHub Desktop.
Copy variable contents to the user clipboard
copyText (textToCopy) {
this.copied = false
// Create textarea element
const textarea = document.createElement('textarea')
// Set the value of the text
textarea.value = textToCopy
// Make sure we cant change the text of the textarea
textarea.setAttribute('readonly', '');
// Hide the textarea off the screnn
textarea.style.position = 'absolute';
textarea.style.left = '-9999px';
// Add the textarea to the page
document.body.appendChild(textarea);
// Copy the textarea
textarea.select()
try {
var successful = document.execCommand('copy');
this.copied = true
} catch(err) {
this.copied = false
}
textarea.remove()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment