VarjuOrg

Linux / Windows – what’s the difference…

Copying text to clipboard with javascript or jQuery

With javascript:

<div id="ctxt_XXX" style="display:none">Text needed to be copied</div>
<a href="" onclick="tCopyTxt('ctxt_XXX')">Copy text</a>

<script>
function tCopyTxt(element) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(element));
range.select().createTextRange();
document.execCommand("Copy");

} else if (window.getSelection) {
var range = document.createRange();
document.getElementById(element).style.display = "block";
range.selectNode(document.getElementById(element));
window.getSelection().addRange(range);
document.execCommand("Copy");
document.getElementById(element).style.display = "none";
}
}
</script>

With jQuery (and with spaces being left intact):
(NB! jQuery should be included in page!)

<div id="ctxt_XXX" style="display:none">Text needed to be copied</div>
<a href="" onclick="tCopyTxt('#ctxt_XXX')">Copy text</a>

<script>
function tCopyTxt(element) {
var text = $(element).clone().find('br').prepend('\r\n').end().text()
element = $('<textarea>').appendTo('body').val(text).select()
document.execCommand('copy')
element.remove()
}
</script>

Leave a Reply

Your email address will not be published.