214-564-5316
Tuesday, May 20, 2008

Copy to Clipboard Script using Javascript and the PRE tag

You simply click the Clipboard icon to copy the text into the clipboard--
all ready for you to paste into notepad or your html editor.
Here is the code to make this "Copy to Clipboard" script work for you:

Use the Icon to copy the code!

Put this javascript in between the <head> and </head> tags:

<script language="JavaScript" type="text/JavaScript">
//
function selectThis(src) {
	document.selection.clear;
	txt = eval(src +".innerText");
	theObj = document.all(txt);
	txtRange = document.body.createTextRange();
	txtRange.moveToElementText(eval(src));
	txtRange.select();
	//txtRange.execCommand("RemoveFormat");
	txtRange.execCommand("Copy");
}
//
</script>
copy 
   
Now place your content into the Pre tag code:

<pre id="preSpan1">--Content you want to have copied goes here--</pre>
copy
   
Here is a text link to call the javascript function and copy the content in between the <pre> and </pre> tags:

 
<a href="javascript:selectThis('preSpan1')">Click to Copy</a>
copy

This is what the link would look like:
Click to Copy
**Hint--You can rename the id of the pre tag and the hyperlink so that multiple instances of the javascript can be used on the same page (e.g. preSpan1, preSpan2, and preSpan3).

To use an image instead of a text link the code would look like this:

 
 <a href="javascript:selectThis('preSpan1')"><img src="image.gif" border="0"></a>
copy