Last active
December 23, 2020 19:29
-
-
Save Deityhub/638b6f1cb13ab6f0dcbf00844768ca75 to your computer and use it in GitHub Desktop.
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
/** | |
* @param {string} text the content to copy to clipboard | |
* @description copies text to clipboard | |
*/ | |
export default function(text) { | |
/* Get the text field */ | |
const el = document.createElement('textarea'); | |
el.value = text; | |
/* make it readonly and hidden from the display */ | |
el.setAttribute('readonly', ''); | |
el.style.display = 'hidden'; | |
document.body.appendChild(el); | |
// Check if there is any content selected previously | |
// Store selection if found | |
const selected = | |
document.getSelection().rangeCount > 0 | |
? document.getSelection().getRangeAt(0) | |
: false; | |
el.select(); | |
el.setSelectionRange(0, 99999); /*For mobile devices*/ | |
document.execCommand('copy'); | |
document.body.removeChild(el); | |
/* If a selection existed before copying; | |
Unselect everything on the HTML document; | |
Restore the original selection */ | |
if (selected) { | |
document.getSelection().removeAllRanges(); | |
document.getSelection().addRange(selected); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment