Skip to content

Instantly share code, notes, and snippets.

@fedyk
Created January 13, 2014 16:18
Show Gist options
  • Save fedyk/8403047 to your computer and use it in GitHub Desktop.
Save fedyk/8403047 to your computer and use it in GitHub Desktop.
JS function to copy text in clipboard.
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