Skip to content

Instantly share code, notes, and snippets.

@quickshiftin
Created April 9, 2018 15:26
Show Gist options
  • Save quickshiftin/6241a7ba1e3cf4e5c16be737a6dcd6f8 to your computer and use it in GitHub Desktop.
Save quickshiftin/6241a7ba1e3cf4e5c16be737a6dcd6f8 to your computer and use it in GitHub Desktop.
Copy to clipboard in Javascript using document.execCommand('copy')
/**
* @param {string} value The text to copy to the clipboard
* This method is designed to circumvent the inability to copy test from an inactive textarea,
* Hopefully it gets the keyboard to drop off on mobile too
*/
copyToClipboard = () => {
const tmpTextArea = document.createElement('textarea');
const newContent = document.createTextNode(this.props.getText());
tmpTextArea.appendChild(newContent);
tmpTextArea.style.width = 0;
tmpTextArea.style.height = 0;
tmpTextArea.style.border = 0;
document.body.appendChild(tmpTextArea);
tmpTextArea.select();
document.execCommand('copy');
document.body.removeChild(tmpTextArea);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment