Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Copying Text to the Windows Clipboard - JavaScript

RSS
Modified on Wed, Jan 19, 2011, 2:14 PM by Administrator Categorized as JavaScript, jQuery, and Angular
The following code demonstrates how to provide a "link" on a web page to allow the user to copy document text to the Windows Clipboard. Note that this only works in IE.

<html>
<head>
<style>
.hidden
{
    display:none;
    height=100px;
    width=300px;
}
.copyLink
{
    text-decoration:underline;
    color:blue;
    cursor:hand;
    font-size:9pt;
}
</style>
<script language="javascript">
document.write(
    '<textarea id="holdtext" class="hidden"></textarea>');

function CopyCode()
{    
    var eventSource;
    var codeSource;
    var stagingArea;
    var clipboard;
    
    eventSource = window.event.srcElement;
    codeSource = eventSource;
    
    // ignore whitespace and carriage returns
    do 
        codeSource = codeSource.nextSibling
    while (codeSource && codeSource.nodeType != 1);
    
    stagingArea = document.getElementById("holdtext");
    stagingArea.innerText = codeSource.innerText;
    clipboard = stagingArea.createTextRange();
    //clipboard.execCommand("RemoveFormat");
    clipboard.execCommand("Copy")
}
</script>
<body>
<form id="uxMyForm">
<a onclick="CopyCode();" class="copyLink">Copy Code</a>
<pre id="first">
<script language="javascript">document.write(document.lastModified);
</script>
</pre>
<br/>
<br/>
<a onclick="CopyCode();" class="copyLink">Copy Code</a>
<pre id="second">
<script language="javascript">document.write(document.URL);
</script>
</pre>
<br/>

<br/>
<br/>
</form>
</body>
</html>

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2018, Patrick Jasinski.