JavaScript Copy to Clipboard

By  on  

"Copy to clipboard" functionality is something we all use dozens of times daily but the client side API around it has always been lacking; some older APIs and browser implementations required a scary "are you sure?"-style dialog before the content would be copied to clipboard -- not great for usability or trust.  About seven years back I blogged about ZeroClipboard, a solution for copying content to the clipboard in a more novel way...

...and by novel way I mean using Flash.  Hey -- we all hate on Flash these days but functionality is always the main goal and it was quite effective for this purpose so we have to admit it was a decent solution.  Years later we have a better, Flash-free solution:  clipboard.js.

The clipboard.js API for copy to clipboard is short and sweet.  Here are a few uses:

Copying and Cutting Values of Textarea and Input

/* Textarea - Cut


*/
var clipboard = new Clipboard('.copy-button');

/* Input - Copy


*/
var clipboard = new Clipboard('.copy-button');

Copying Element innerHTML

/* HTMLElement - Copy
hello
*/ var clipboard = new Clipboard('.copy-button');

Target and Text Functions

// Contents of an element
var clipboard = new Clipboard('.copy-button', {
    target: function() {
        return document.querySelector('#copy-target');
    }
});

// A specific string
var clipboard = new Clipboard('.copy-button', {
    text: function() {
        return 'clipboard.js is awesome!';
    }
});

Events

var clipboard = new Clipboard('.btn');

clipboard.on('success', function(e) {
    console.log(e);
});

clipboard.on('error', function(e) {
    console.log(e);
});

No Flash with a simple API and working in all major browsers makes clipboard.js a huge win for the web and its users.  The days of Flash shimming functionality on the client side are over -- long live web technology!

Recent Features

  • By
    9 Mind-Blowing WebGL Demos

    As much as developers now loathe Flash, we're still playing a bit of catch up to natively duplicate the animation capabilities that Adobe's old technology provided us.  Of course we have canvas, an awesome technology, one which I highlighted 9 mind-blowing demos.  Another technology available...

  • By
    Camera and Video Control with HTML5

    Client-side APIs on mobile and desktop devices are quickly providing the same APIs.  Of course our mobile devices got access to some of these APIs first, but those APIs are slowly making their way to the desktop.  One of those APIs is the getUserMedia API...

Incredible Demos

  • By
    jQuery Chosen Plugin

    Without a doubt, my least favorite form element is the SELECT element.  The element is almost unstylable, looks different across platforms, has had inconsistent value access, and disaster that is the result of multiple=true is, well, a disaster.  Needless to say, whenever a developer goes...

  • By
    MooTools Flashlight Effect

    Another reason that I love Twitter so much is that I'm able to check out what fellow developers think is interesting. Chris Coyier posted about a flashlight effect he found built with jQuery. While I agree with Chris that it's a little corny, it...

Discussion

  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.

    • jitendra

      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.

    • Roven

      Doesn’t ZeroClipboard depend on Flash?

  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. Ben

    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. Amit

    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. eddie

    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. Loo

    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. Jammer

    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

    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

    @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

    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

    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

    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

    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. rayphi

    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. Ntmd8r

    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 ?

    • Try this:

      /* HTMLElement - Copy*/
      ...
      Copy
      
      var clipboard = new Clipboard('.copy-button');
  31. Vilmondes Eracton

    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. Sumit

    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. Ult

    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. andy

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

  39. Yogesh

    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

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

  42. Franz

    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

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

  44. Hey guys not working ..

  45. Parth Shah

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

    • The SWF is the bridge between the browser and the clipboard — it is required.

  46. Parth Shah

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

  47. Lisa

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

  48. PT

    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

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

  50. Vipul Sharma

    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. SABARISH

    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. raafat

    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

  53. Shiv

    This is a giant pain to get working with ASP:Button. I also don’t know if I can draw copy text from other ASP controls. It gave me a headache for a few hours so I dropped it for other more integral project elements.

    Anyone have any feedback on this?

  54. Satish Lakhani

    Hey,
    I’m using zclip to copy data from webpage and paste it to LibreOfficeCalc, for this i need to set encoding type of data to be copied.

    How can i set the encoding type of data to be copied?

  55. yatendra
    function ClipBoard() {
        holdtext.innerText = copytext.innerText;
        Copied = holdtext.createTextRange();
        Copied.execCommand("Copy");
    }
    
  56. Unopoo

    zeroclipboard works fantastic while in http:// or https:// schema, but do you know is there anyway to let js access clipboard in file:/// schema?

  57. So recently somebody discovered copy() in the console (Blink/WebKit only). Doesn’t work directly from JavaScript though!

  58. Jugal

    When i set ZeroClipboard.setMoviePath(‘G:/ZeroClipBoard/zeroclipboard-2.2.0/dist/ZeroClipboard.swf’);
    Its giving me error UnCaughtType Error: Undefined is not a function.

    “G:/ZeroClipBoard/zeroclipboard-2.2.0/dist/ZeroClipboard.swf” is my path to ZeroClipboard.swf.
    What should i do? Please help..

  59. Wolden

    sorry for the missing tags, please read: once the “button” or the “a” …. changing the “button/a” datas.

  60. shanker

    Zclip functionality not working in firefox.
    Please specify solution of that, so that zclip will also running in firefox.

  61. William

    http://davidwalsh.name/demo/ZeroClipboard.swf can everyone use this as the movie path?

  62. tulsiram

    Hi,

    I would like to confirm about ZeroClipboard.js & ZeroClipboard.swf. Are these library open source or need licence?

    Thanks in advance.

  63. Soo the days of Flash is going to be over!

  64. My theme suddenly stop responding to copy to clipboard functionality. Its maybe because of caching plugins on wordpress??

  65. Rachel

    Seems like a lot of code for a simple action. Can it be boiled down to one or two lines?

  66. Is there any JavaScript editor available with live user interface ?

  67. Thanks David I was looking for the solution without using Flash. And by clipboard.js you can acheive this. nice code !

  68. I was searching for how to implement without Flash and using clipboard.js we can achieve this. Thanks for the post. Nice code !

  69. Steve Hansen

    Well done David!

  70. Robert

    IS this for copying only text to the clipboard.

    I am working whit JSXGraph and I would like to have the ability to copy the vector graph to the clipboard.

  71. Its not working in mobile phone :/

  72. ubkdev

    i want to use it to copy texts from textarea in a loop but its not working.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!