Thursday, 29 May 2008

Javascript: Copy text to clipboard function

<SPAN ID="copytext" STYLE="height:150;width:162;background-color:pink">
This text will be copied onto the clipboard when you click the button below. Try it!
</SPAN>
<TEXTAREA ID="holdtext" STYLE="display:none;"></TEXTAREA>
<BUTTON onClick="ClipBoard();">Copy to Clipboard</BUTTON>

<SCRIPT LANGUAGE="JavaScript">

function ClipBoard()
{
holdtext.innerText = copytext.innerText;
Copied = holdtext.createTextRange();
Copied.execCommand("Copy");
}

</SCRIPT>

Extract description from site:

The script, as it is currently written, copies whatever text is within the SPAN tags. If there is code, like a
command created to display using & commands, those will copy right along. If you've got formatting in the text and you only want the user to copy the text, then you need to add a command that will remove that formatting. Luckily, there's an execCommand that will do that for you. It's important that you place it in the script before the copy process.

<SCRIPT LANGUAGE="JavaScript">

function ClipBoard()
{
holdtext.innerText = copytext.innerText;
Copied = holdtext.createTextRange();
Copied.execCommand("RemoveFormat");
Copied.execCommand("Copy");
}

</SCRIPT>

NOTE: due to mozillas tight security setting this script only works in IE.

Other variation

var x = document.getElementById("EncodedString").value;
window.clipboardData.setData('text', x);

No comments: