Copy to Clipboard !!! using Javascript

by Noman Muhammad

Copy to clipboard functionality is very useful when we want to copy any particular content of a web page automatically. I search over the net to know how to implement it. I found that almost every tutorial use the javascript function "execCommand()". Here is an example how I use it:


<body>
<script type="text/javascript">
function ClipBoard()
{
holdtext.innerText = copytext.innerText;
Copied = holdtext.createTextRange();
Copied.execCommand("RemoveFormat");
Copied.execCommand("Copy");
}
</script>


<SPAN ID="copytext" STYLE="background-color:pink">
COPY This Line!
</SPAN>

<TEXTAREA ID="holdtext" STYLE="display:none;"></TEXTAREA>
<BUTTON onClick="ClipBoard();">Copy to Clipboard</BUTTON>
</body>


When I click on the button the line "COPY This Line!" will be copied to the clipboard and then I can paste it anywhere.
But its not a solution of my problem when i open my page on Mozilla Firefox browser.
As per I know Firefox doesn't support the javascript function "execCommand()".

After some googling I find this link which solve my problem both for IE and FireFox. Here is my implementation of this:

<html>
<head>Copy to Clipboard</head>
<body>
<script type="text/javascript">
function copy_to_clipboard(text)
{
if(window.clipboardData)
{
window.clipboardData.setData('text',text);
}
else
{
var clipboarddiv=document.getElementById('divclipboardswf');
if(clipboarddiv==null)
{
clipboarddiv=document.createElement('div');
clipboarddiv.setAttribute("name", "divclipboardswf");
clipboarddiv.setAttribute("id", "divclipboardswf");
document.body.appendChild(clipboarddiv);
}
clipboarddiv.innerHTML='<embed src="clipboard.swf" FlashVars="clipboard='+
encodeURIComponent(text)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
}
}
</script>

<input type="text" id="rt" value="" />
<input type="button" value="Copy" onclick="copy_to_clipboard(document.getElementById('rt').value);" />

</body>
</html>


To use it for firefox I have to download the flash (.swf) file from here and placed at path where this function is placed or else source parameter for embed tag to be changed to correct path where the flash file is been placed.
I also need firefox plugins for flash player as it depends on flash.
Now if I write something on the text box and then press the button the written text on the input box will be copied to the clipborad.

It works very fine. :)

This entry was posted on Tuesday, May 12, 2009 and is filed under , . You can leave a response and follow any responses to this entry through the Subscribe to: Post Comments (Atom) .

0 comments