I'm currently working on releasing a nice front-end to [https://passwordutility.net](https://passwordutility.net" target="_blank). PasswordUtility.net is an OSS tool that allows users to check their passwords' strength. You can also generate strong passwords using the same tool. If you're ever stuck for a password, head over to the site and give it a go! There's also a funky API and free OSS library release as NuGet package so you don't have to re-invent the wheel.
With the shameless plug out of the way, I'll get to the chase. How do you add a copy-to-clipboard feature to your site? Some popular sites such as Azure and GitHub offer this feature too. This feature can used every time you want to minimize user effort when copying complex data/values.
How do I implement this feature?
It turns out that it's quite simple to add this through a 3rd party library that works consistently cross-platform. The library that does all the magic, so you won't have to, is called: Zero Clipboard. You can find the code repot of this Open Source project on [GitHub](https://github.com/zeroclipboard/zeroclipboard" target="_blank). But what is Zero Clipboard?
The steps to add the feature are fairly simple:
- Add the .swf (flash movie) to your project
- Include a reference to the library in your page
- Initialize the library and assign a DOM element to it.
If you'd like to use ZeroClipboard hosted via a CDN (content delivery network), you can try:
- cdnjs: [http://cdnjs.com/libraries/zeroclipboard](http://cdnjs.com/libraries/zeroclipboard" target="_blank)
- jsDelivr: [http://www.jsdelivr.com/#!zeroclipboard](http://www.jsdelivr.com/#!zeroclipboard" target="_blank)
Include the reference to the library in HTML
This is a particularly easy task. You only need to add the following line inside
With the references in place, we can now initialize our code to respond to user input and copy the data to the clipboard.
The HTML code
The simplest way to set and test the sample page is to create a folder with an
index.html page. You should also place the
.swf movie in the same location. The HTML code is shown below with a placeholder for the ZeroClipboard script
Pretty simple, a text box and a button.
Place the sample code in the placeholder location in the html file. You can also place it on a separate file. However, since this is only a sample, I've put everything together for brevity:
Now, when you click on the button, any value entered on the textbox will be copied to the clipboard. The code will also show a popup message with the copied value.
NOTE: you need to deploy and run the sample code either in IISExpress or IIS. Due to flash security restrictions the code won't work if you run it from the disk. You've been warned!
- Full ZeroClipboard API [documentation](https://github.com/zeroclipboard/zeroclipboard/blob/master/docs/instructions.md" target="_blank)