Using ZeroClipboard on your website to Copy text to your clipboard

I've used ZeroClipboard in a couple of my projects which allows me to provide a clickable object which copies text of my choosing into the client's clipboard.  I usually use copy and paste keyboard shortcuts, but there are times when it's nice and more effecient to have a click-to-copy button.

Get the files

wget https://github.com/zeroclipboard/ZeroClipboard/raw/master/ZeroClipboard.swf
wget https://raw.github.com/zeroclipboard/ZeroClipboard/master/ZeroClipboard.min.js

Import the files and create the basic structure

<html>
<head>
</head>
<body>
<div id="copy_initiator">Click me to Copy Text!</div>
<script src="ZeroClipboard.min.js" type="text/javascript"></script>
<script type="text/javascript">

var clip = new ZeroClipboard( document.getElementById("copy_initiator"), {
  moviePath: "ZeroClipboard.swf"
} );

//this event happens upon initiating the copy 
clip.on( 'dataRequested', function ( client, args ) {
    clip.setText( "whatever text you want");
} );

//this event happens upon the copy finishing
clip.on( 'complete', function(client, args) {
  alert("Copied text to clipboard: " + args.text );
} );

</script>
</body>
</html>

And thats it! You should have a div with the id of "copy_initiator" which when clicked will copy "whatever text you want" into the client's clipboard. Using the setText() method you can use any source of text including anything object attributes, html, text via javascript or jquery.

Tagged as copy , js ZeroClipboard
Written by Andrew Konkol on August 1st, 2013

0 Comments

Log in with Twitter, Google, Facebook, LinkedIn to leave a comment.