Treehouse

JavaScript Copy to Clipboard

By on  

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.

ydkjs-4.png

Recent Features

  • 5 More HTML5 APIs You Didn’t Know Existed

    The HTML5 revolution has provided us some awesome JavaScript and HTML APIs.  Some are APIs we knew we've needed for years, others are cutting edge mobile and desktop helpers.  Regardless of API strength or purpose, anything to help us better do our job is a...

  • Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

Incredible Demos

  • Scrolling &#8220;Agree to Terms&#8221; Component with MooTools ScrollSpy

    Remember the good old days of Windows applications forcing you to scroll down to the bottom of the "terms and conditions" pane, theoretically in an effort ensure that you actually read them? You're saying "No David, don't do it." Too late -- I've done...

  • CSS Selection Styling

    The goal of CSS is to allow styling of content and structure within a web page.  We all know that, right?  As CSS revisions arrive, we're provided more opportunity to control.  One of the little known styling option available within the browser is text selection styling....

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.

  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 ?

  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. […] Read Javascript Copy to Clipboard […]

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

  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 […]

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

  57. 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?

  58. 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?

  59. yatendra
    function ClipBoard() {
        holdtext.innerText = copytext.innerText;
        Copied = holdtext.createTextRange();
        Copied.execCommand("Copy");
    }
    
  60. 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?

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