JavaScript Copy to Clipboard

Written by David Walsh on October 19, 2009 · 60 Comments

Providing your users the ability to copy text to the clipboard can make your website much more convenient and valuable. Unfortunately Flash 10 broke most of the methods for doing so. Luckily a great library named ZeroClipboard exists. ZeroClipboard uses a pinch of Flash and touch of JavaScript to make copying to the clipboard happen.

The Sample HTML

<script type="text/javascript" src="ZeroClipboard.js"></script>
<textarea name="box-content" id="box-content" rows="5" cols="70">
	The David Walsh Blog is the best blog around!  MooTools FTW!
</textarea>
<br /><br />
<p><input type="button" id="copy" name="copy" value="Copy to Clipboard" /></p>

The above HTML features a form element with the ID "box-content" and a button with the ID "copy". Both of those element IDs will come into play with ZeroClipboard.

The ZeroClipboard JavaScript

//set path
ZeroClipboard.setMoviePath('http://davidwalsh.name/demo/ZeroClipboard.swf');
//create client
var clip = new ZeroClipboard.Client();
//event
clip.addEventListener('mousedown',function() {
	clip.setText(document.getElementById('box-content').value);
});
clip.addEventListener('complete',function(client,text) {
	alert('copied: ' + text);
});
//glue it to the button
clip.glue('copy');

With the ZeroClipboard object loaded we:

  • Set the path to the SWF file.
  • Create what ZeroClipboard calls a "client": A client is a single instance of the clipboard library on the page, linked to a particular button or other DOM element.
  • Add a mousedown event listener that places text from inside our textarea into the clipboard.
  • Add an optional complete event where we can add functionality to execute once the text has been successfully added to the clipboard.
  • "Glue" the button to the functionality we've added in the steps above.

That's it! ZeroClipboard is an outstanding utility to allow copy to the clipboard functionality on any website.

Comments

  1. nice code, thanks!!

  2. I have used ZeroClipboard in a project and it does what it has to with no problems.

    P.S. The ZeroClipboard link goes to the demo rather than http://code.google.com/p/zeroclipboard/ .

    Thanks for reminding me this handy resource.

    • hello umut,
      i am using the same script,but when i right click on the movie,it shows movie not loaded.
      how to solve this issue.
      thnx in advance.

  3. Updated. Thanks Umut!

  4. Useful and clean, … but we still need to use flash anyway … Hopefully we’ll find a flash free way ot do that…

  5. @Opi: A few browsers have their own method of allowing Copy to Clipboard. I didn’t mention those because this solution works in all browsers.

  6. Nice hint, thx!
    I only need the “ZeroClipboard.js” and “ZeroClipboard.swf” from the tar.gz from the ZeroClipboard Homepage right?

  7. @derschreckliche: Yep, just those two files.

  8. I used this a few weeks ago on a little internal web app. It seems ok, but I have had the odd random bug – it has attached the client to the wrong DOM element, or the client has disappeared completely.

    Is this what bit.ly uses?

  9. Great tutorial! Very easy to follow and really nice stuff, keep up the good work.

  10. Сool trick Devid ))

  11. Hey ya Buddy
    How can i use this Funtion in my Blog Posts :(

    is any way ? plz tell :)

  12. I’ve tried to code but didn’t worked for me… something its wrong on it;
    Please check!

  13. Hey David, how would I go about following through with a direct link? I want users on my website to be able to copy the text and then followed by a link to a website.. where it loads it when you click on the copy.

  14. Hello !
    I’ve tried to make it work but no way ! No errors but nothing happens.
    Do you know if there’s a conflict with jQuery 1.3.2 ?

    Thanks in advance :)

  15. Hi,

    How to give the anchor (link), so that we can open another site and copy the information same time.

    I found this at retailmenot.com site….

    can u please do this

  16. Quang Nguyen January 11, 2010

    Hi David,
    Thank you very much for really nice tutorial. I made it works myself.
    However still wondering if Zeroclipboard can work with more than one text field and button on one page. Do you have any experience on this?

    Thanks again.
    Quang

  17. Thank, David) Very useful and clean thing.

  18. hi,

    This script not work on IE7 browser. Please check

  19. @shiyam:

    The script is very useful. It works perfectly on all browser except the IE7

    This script not work on IE7 browse. It displayed the operation aborted error message.

    Please check .

  20. Hi David.. thanks for sharing this. Just a quick not saying that the script is not working for Firefox 3.6.2.

    Thanks

  21. DaveKingsnorth April 15, 2010

    Ye unfortunately it’s not working in latest version of Chrome or Safari 3.2.2 on Windows XP.

    I thought this would be a 2 minute google job but it looks like there is no straight forward solution

  22. Mohammad JUNED May 1, 2010

    Hi David,
    Thanks for the good code, but is it working on Firefox, Google chrome, Opera etc.
    I see, it only works on IE.

    Thanks

  23. Dhruv May 20, 2010

    Yeah, your demo page only works with IE. On FF & Chrome, it’s not working.

    Although demo page at

    http://bowser.macminicolo.net/~jhuckaby/zeroclipboard/

    is working fine. I don’t know what’s wrong with your demo page but now I believe that trick should work.

  24. andrew June 4, 2010

    It works on FF also, but the div containing the embedded flash is a couple pixels “over” the button. Try clicking between the button and the textbox.

    Thanks for posting this! Neat piece of code.

  25. @David Walsh: Yup, all the other methods are not that great. There are a few which only work in IE geez :| Anyway, great share.. thanks a ton David. You and Chris always save me sometime or the other :P

  26. well , i was wondering how to get this working in regards to wordpress content , as i want to apply it in the loop and add a copy to clipboard button for copying the content

    please can you help me out

  27. is there any way to clear the clipboard automatically?

  28. Do you know the JS-only solution for the copy button?

    • Hi Sergey,

      Were you able to design ‘Copy to Clipboard’ purely using javascript? Can you please share the sample code or any hint would help ?

      Regards,

  29. Thanks, perfect!

  30. This is a great start (for me).
    However, I need to be able to copy an entire page to the clipboard,
    so the user can email it to others.
    Javascript has a “Window.Print()” method.

    Why can’t we have a similar “Window.Copy()” method.????

    Or perhaps I should use a “Save as…” facility for the page,
    and then have them email that saved file as an attachment.

    Any thoughts or suggestions ?

  31. Vilmondes Eracton April 6, 2011

    It has helped me a lot! Great job!

    Thanks!

  32. I cannot get this to work in anyway in my web app. The movie object is hidden somewhere under my website main navigation.
    element.style {
    height: 0;
    left: 0;
    position: absolute;
    top: 0;
    width: 0;
    z-index: 99;
    }

    The DOM loads some clip client and some text but I have no idea how to fix this.
    Clicking the button nothing happens.

    Any ideas?
    Danny

  33. demo have errors ?

  34. I tried to implement this code on a normal text box and a button, I was able to do that, but when I tried it on a label and button inside a asp.net modalpopup I was not able to do that. PLease tell how can I implement in modalpopup ?

  35. Perfect!
    I’ve been trying to implement this for a while, but with the developer’s site’s download links I just couldn’t get it to work (maybe the latest releases aren’t supported by Flash 11?), anyway with your code, your ZeroClipboard swf + js files, your example source code and demo page’s source code + the developer’s intructions page, it was pretty easy to get it working the way I wanted!

    Also, it IS possible to reposition a clip which was glued to a div/span (as opposed to what the developer’s intructions say). All you have to do is create a global javascript var (I’ll call it “c”) at the start of your page code, then copy the object reference to this global var after you create the zeroclip client, like this:

    var clip = new ZeroClipboard.Client();
    c1 = clip;

    Then, just call a function when the user resizes the browser window, simplest option would be putting the reposition function call in the

    The function would look something like this:

    function repos(){
    c.destroy(); //global var "c" references clip instance, calls its destroy method
    var clip = new ZeroClipboard.Client(); //creates new zeroclip client/object/instance
    clip.addEventListener('mousedown',function() {
    clip.setText("text string you want to copy to clipboard");
    });
    clip.glue("id of whatever you want to glue this zeroclip client to");
    c = clip; //updates "c" to reference the newly created zeroclip client
    }

    This way the flash client is always being referenced by a global var, and with the destroy+(re)create+glue again function being called everytime the user resizes his browser window, you can glue it to a or without any problem.

    I’ve implemented this into an AJAX page, for dynamically generated pages you’d just have to check if whatever control “c” references still exists before doing the destroy+recreate function, or just empty the variable after destroying it and check if it’s empty before the destroy+recreate function etc., it’s not complicated. Hope this helps. =]

  36. How to use it on blogger.com ?

  37. Thank you for code. This will help me with clipboard.

    • Were you able to design ‘Copy to Clipboard’ purely using javascript? Can you please share the sample code or any hint would help ?

      Regards,

  38. Can’t make it work with pre tags. Is that possible?

  39. Yogesh July 16, 2012

    Thanks for the code but its not working in mozila anf firefox also

  40. I have tried It is not compatible with mobile browser.Is their any solution to do that?

  41. an0maly October 1, 2012

    Too bad this relies on Flash, which is being made obsolete with HTML5

  42. I need to alter the code to copy shipping label data (xml structure) into the Clipboard. How can i use it if at the time of the Click the data is not yet present? A click on “Print Label” Button reloads form, xml data gets created based on several selections on the page and should than be copied to Clipboard. Thanks for any suggestions.

  43. shaheen March 10, 2013

    Where should we copy the above codes in blogger posts. ? and How ?

  44. Hey guys not working ..

  45. Parth Shah May 24, 2013

    what is the .swf we have to add. Is it required. I dont understand the reason of putting it.

  46. Parth Shah May 25, 2013

    Ok, then if I want to apply this code to my website, which shock wave file I have to use?

  47. How to add to wordpress pages? Doesn’t seem to work.

  48. For some reason it’s not respecting line breaks/carriage returns for me. I’m trying to copy paragraphs from this site:

    http://www.catipsum.com/

    I’m using Windows 7 Pro 64bit
    Fire Fox 21.0

  49. Vipul Sharma December 20, 2013

    Is there any way by which I can copy content after ajax call without clicking any button click event?

  50. Vipul Sharma December 20, 2013

    I’m trying it by creating hidden data element and button and then triggering click event, $(‘#btn_copy_map_data’).trigger(‘click’); but its not working. I have tried everything and now don’t have any option to make it work. Please advice.

  51. i am used in android and pc it works very fine but i used in iphone it doesn’t work due to ios doesn’t support swf format files how to solve this issue

  52. [...] Read Javascript Copy to Clipboard [...]

  53. I don’t know what’s the problem here :
    i have downloaded ZeroClipboard.swf then i have done this :

    //set path
    ZeroClipboard.setMoviePath('/static/flash/ZeroClipboard.swf');
    
    //create client
    var clip = new ZeroClipboard.Client();
    
    function CopyThis(id) {clip.setText("blah");
                           alert("Done copying blah..."+id);}
    

    so that when someone click the button the CopyThis fuction will be raised

    Any an idea ?

    thank you

  54. […] published a post a year ago detailing how you can copy to the clipboard using JavaScript.  The post was very popular and why would it be?  Copying content from a webpage without needing […]

  55. […] JavaScript Copy to Clipboard […]

Be Heard

Tip: Wrap your code in <pre> tags or link to a GitHub Gist!

Use Code Editor
Older
Form Element AJAX Spinner Attachment Using jQuery
Newer
Dynamically Create Charts Using MooTools MilkChart and Google Analytics