Created
October 5, 2016 14:05
-
-
Save saghul/349cfedff53d1423f21588ae61e02e23 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
// partially borrowed from clipboard.js | |
// Must call it from a click event handler | |
// returns true if the text was copied, false otherwise | |
function copyToClipboard(text) { | |
const isRTL = document.documentElement.getAttribute('dir') == 'rtl'; | |
const fakeElem = document.createElement('textarea'); | |
let success = true; | |
// Prevent zooming on iOS | |
fakeElem.style.fontSize = '12pt'; | |
// Reset box model | |
fakeElem.style.border = '0'; | |
fakeElem.style.padding = '0'; | |
fakeElem.style.margin = '0'; | |
// Move element out of screen horizontally | |
fakeElem.style.position = 'absolute'; | |
fakeElem.style[ isRTL ? 'right' : 'left' ] = '-9999px'; | |
// Move element to the same position vertically | |
fakeElem.style.top = (window.pageYOffset || document.documentElement.scrollTop) + 'px'; | |
fakeElem.setAttribute('readonly', ''); | |
fakeElem.value = text; | |
// Add element to the body | |
document.body.appendChild(fakeElem); | |
// Select the element | |
fakeElem.select(); | |
// Copy to clipboard | |
try { | |
document.execCommand('copy'); | |
} catch(e) { | |
success = false; | |
} | |
// De-select the element | |
fakeElem.blur(); | |
// Remove from body | |
document.body.removeChild(fakeElem); | |
return success; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment