Created
November 16, 2018 14:53
-
-
Save LucaRosaldi/584d7f51f4b8b918a66e33754897256a to your computer and use it in GitHub Desktop.
JS: Copy to Clipboard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Copy text to clipboard. | |
* | |
* @param {String} text | |
* @return {void} | |
*/ | |
const copyToClipboard = ( text ) => { | |
const activeElement = document.activeElement; | |
// create a dummy element for text selection and push it offscreen | |
const dummyInput = document.createElement( 'input' ); | |
dummyInput.value = text; | |
dummyInput.style.position = 'absolute'; | |
dummyInput.style.top = '0'; | |
dummyInput.style.left = '9999px'; | |
bodyEl.appendChild( dummyInput ); | |
dummyInput.focus(); | |
dummyInput.select(); | |
document.execCommand('copy'); | |
bodyEl.removeChild( dummyInput ); | |
activeElement.focus(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment