Copy to clipboard in Javascript — jQuery zClip

jQuery zClip

Today, a quick tutorial on how to copy to the clipboard in JavaScript. Sometimes in our web application project, may appear a requirement: allow copying of data to the clipboard programmatically from JavaScript, after the occurrence of some event.

Copy to clipboard in Javascript

For this we use my favorite JavaScript framework — jQuery.

In details it will be the jQuery zClip (jQuery ZeroClipboard) plugin.

Copy to clipboard in Javascript — using zClip

The task of copying data to the clipboard in JavaScript encounters a number of problems, mainly related to safety.

The zClip solution is based on Flash object (SWF file), which executes the right task, while the control is done in JavaScript.

Let’s try.

Step 1

Download a library:

http://www.steamdev.com/zclip/

In case of problems, we can also get the code directly from GitHub:

https://github.com/patricklodder/jquery-zclip

Then we attach jQuery and downloaded library to our project:

<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="zclip/jquery.zclip.js"></script>

Step 2

Prepare elements of simple UI:

<body>
  <h4>Clipboard test - JavaScript</h4>

  <a href="#" id="copy-link-wrap">
    <input name="toclip" id="toclip" type="text"
      value="Test data to copy …" style="width: 320px">
    <br />
    <p id="copy-link" style="cursor: hand">Copy to clipboard</p>
  </a>
…

</body>

In this example we will copy a value of the text field.

Step 3

Then we add the handling code:

$(document).ready(function() {
  $("#copy-link-wrap").zclip({
    path: 'zclip/ZeroClipboard.swf',
    copy: $('#toclip').val(),
    afterCopy: function() {
      // console.log('copied');
      alert('Data in clipboard! Now you can paste it somewhere');
    }
  });
});

Plugin has been applied to the entire element copy-link-wrap.

We must specify the correct path to the .swf file, a value to copy (copy: $(‘#toclip’).val()) and define the action to take when data is copied.

Step 4

Put it on-line and test:

http://directcode.eu/samples/javascript-clipboard/index.html

Sources to download here.

Summary

And it’s ready! We have a simple and working solution.

There are of course different good ideas and maybe soon we will see unified standard of handling clipboard from JavaScript level. In all browsers!

We also have to admit, that the creativity in finding ways by developers is high, for example:

http://stackoverflow.com/questions/400212/how-to-copy-to-the-clipboard-in-javascript

So far, we need to look for cross-browser solutions. And today we suggested one of them.

Thank you!

One Response to “Copy to clipboard in Javascript — jQuery zClip”

  1. ‫עודד קרן‬‎ says:

    in firefox its broken