Saturday, March 22, 2008

Copy HTML contents as Text to Clipboard

Periodically it is necessary to copy the contents of an HTML control to another location in text format.  Selecting elements of an HTML page and using the "context" copy will place the contents on the clipboard in two formats; HTML and plain text.

Copy the following to your clipboard and then paste it into two different editors to see how this works:

The quick brown cat jumped over the

lazy dogs back 1234567890 times

while the sly fox

watched.

First paste this into notepad.  Notice no formatting of course.  Now paste into an HTML editor like an Outlook mail message set for HTML format or paste into MS Word.  The formatting is maintained.

Now do the same with the following:

Sub test

    
Dim myint
    
myint = 1
 
End Sub 

In some browsers just selecting this code is a bit of a problem especially if it goes off the visible page.

The following shows how to add a piece of embedded script that will copy the code to the clipboard as plain text.  It will retain it's line spacing and line ending correctly.  This will greatly simplify delivery of code content to users.

The method:

Include the following in the page scripts in any convenient place:

<script language="jscript" type="text/jscript">
<!--
    
function divout(ctl){
       
var code=ctl.innerText;
       
holdtext.innerText=code;
       
Copied = holdtext.createTextRange();
       
Copied.execCommand('Copy');
       
return false;
   
}
-->
</script>

Include a button or hyperlink like the following:

<input type="button" value="Copy To Clipboard" language="jscript"
onclick="divout(mydiv);"/>

Wrap your code display in a DIV and give it an id.  Set the argument to "divout" to the id of your codes DIV.

Include a dummy <textarea></textarea> that is hidden anywhere on teh page.  This is used to store the interim text while formatting and to allow the contents to be easily extracted to teh clipboard.

<textarea id="holdtext" style="display: none">Empty</textarea>

Press here to see it work:

 

This is a patch for the input button issue.

No comments:

Post a Comment