Skip to content

Instantly share code, notes, and snippets.

@LucaRosaldi
Created November 16, 2018 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LucaRosaldi/584d7f51f4b8b918a66e33754897256a to your computer and use it in GitHub Desktop.
Save LucaRosaldi/584d7f51f4b8b918a66e33754897256a to your computer and use it in GitHub Desktop.
JS: Copy to Clipboard
/**
* 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