Created
January 13, 2014 16:18
-
-
Save fedyk/8403047 to your computer and use it in GitHub Desktop.
JS function to copy text in clipboard.
This file contains hidden or 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
function copyText (text) { | |
var div = document.getElementById('__special_copy_div'), | |
saveSelection, | |
selection, | |
rng, | |
i; | |
if (!div) { | |
div = document.createElement('pre'); | |
div.id = '__special_copy_div'; | |
div.style.opacity = 0; | |
div.style.position = 'absolute'; | |
div.style.top = '-10000px'; | |
div.style.right = 0; | |
document.body.appendChild(div); | |
} | |
div.innerText = text; | |
if (document.createRange) { | |
rng = document.createRange(); | |
rng.selectNodeContents(div); | |
saveSelection = []; | |
selection = window.getSelection(); | |
for (var i = 0; i < selection.rangeCount; i++) { | |
saveSelection[i] = selection.getRangeAt(i); | |
} | |
window.getSelection().removeAllRanges(); | |
window.getSelection().addRange(rng); | |
} else { | |
return alert('Copy not work. :('); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment