Copy to Clipboard Javascript

By Hawkee on Mar 24, 2007

This will copy the text in a given field to the clipboard. Unfortunately it only works in IE, so Firefox users will still need to do the actual copy. But it'll at least select the text for Firefox users.

Here is how you set up your HTML:

<form name=myform>
<input type=text name=mytext value='This text will be copied'>
<input onclick="javascript:copyToClipboard('myform.mytext')" type="button" value="Send to Clipboard">
</form>

You can name the form and text box anything you'd like. Just be sure to send the proper parameters to the copyToClipboard function. You may also use a textarea like we do here for our snippets.

function copyToClipboard(field)
{
    var content = eval("document."+field)
    content.focus()
    content.select()
    range = content.createTextRange()
    range.execCommand("Copy")
    window.status="Contents copied to clipboard"
    setTimeout("window.status=''",1800)
}

Comments

Sign in to comment.
jimbobjonesIII   -  Jul 29, 2011

how do I link to the javascript?

thanks

 Respond  
bkudrle   -  Jan 21, 2011

Clean code and works as is in IE. Thanks for sharing.

 Respond  
PATX   -  May 05, 2009

lol nice. i have one like this in python....

 Respond  
Hawkee   -  Dec 19, 2008

lionroar, just use a textarea and reference the name of the textarea in the function call.

 Respond  
lionroar   -  Dec 19, 2008

I had a question do you know how I can use this using the "textarea" tag. I would like to use it for copying html coding?

 Respond  
markusPHP   -  Jun 16, 2008

Works in Opera, you might add.

 Respond  
M[n]M   -  Oct 04, 2007

nice thats what i was searching for!

vigneswaranj  -  Mar 18, 2014

Copy to Clipboard Javascript ..how i will run in crome...pls give for crome

Hawkee  -  Mar 18, 2014

@vigneswaranj This is very old. I'd search Google for something more up to date. I know in the past we had to use something like ZeroClipboard which is a flash solution, but there may be something better now.

Sign in to comment

Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.