As a web developer sometimes you will need to implement the copy to clipboard function, so that the site user could quickly copy a piece of text to the clipboard with a click of a button. You would typically see this feature in the code highlighter program. Usually there is copy to clipboard button to copy the sample code.

copy-to-clipboard

There are several solutions out there, but after doing some research, I have found out that some solutions does not work for all browser, and some solution require the use of flash. However when the site user upgrade to the latest version of flash, that script may no longer work.

In Internet Explorer you could simply use a few lines of code to achieve this function. But it does not work for FireFox or Google Chrome web browser.
{codecitation class="brush:javascript"}}
var selectedHtml=(document.selection.createRange()).htmlText;
if(selectedHtml!= "")
window.clipboardData.setData("Text",selectedHtml);

{/codecitation}

A nicer solution is to use is the script Zero Clipboard. It is a flash base solution, and implemented with a javascript code.

You can download the original source code here with setup instruction on how to install it. I have recompile it with flash version 11. You can download the latest Zero Clipboard to ensure it work with Flash 11.

The code is fairly simple to use. You can see an example below. You will need to install just two files consist of ZeroClipboard.js and ZeroClipboard11.swf into your website folder.

{codecitation class="brush:html"}

<html>
<head>
<title>Copy to Clipboard with Zero Clipboard Example</title>    
<script type="text/javascript" src="/ZeroClipboard.js"></script>
<script language="JavaScript">
var clip = null;

function $(id) { return document.getElementById(id); }

function init() {
clip = new ZeroClipboard.Client();
clip.setHandCursor( false );        

clip.addEventListener('mouseOver', function (client) {
// update the text on mouse over
clip.setText( $('fe_text').value );
});            

clip.addEventListener('complete', function (client, text) {
alert("Text copied to clipboard.");
});

clip.glue( 'd_clip_button');
}

</script>
</head>
<body onLoad="init()">
<h1>Copy to Clipboard with Zero Clipboard Example</h1>

<textarea id="fe_text" cols=50 rows=5 onChange="clip.setText(this.value)">Copy me!</textarea>
</br>            
<input type="button" id="d_clip_button" value="Copy to Clipboard" />
<input type="button"/>
</body>
</html>

{/codecitation}

You can see an example of how this work at Convert String Case.

 
* iOS Development * OS X * Product Review