Implementing Clipboard Functionality

This article will show you how to use the clipboard in your web application.


Published on:August 13, 2016

Introduction

In this article we will show you how to easily implement the ability to cut or copy data to the user's clipboard. In order to implement this we will use clipboard.js. An easy to use clipboard library. Let's get started.

Initial Setup

The first thing we need to do is include the clipboard.js file in our application. The easiest way to do this is include the line listed below before the closing </body> tag of your HTML (or app/views/layouts/application.html.erb if you are using Ruby On Rails.) You can click 'Copy to Clipboard to copy this content to your clipboard. This is an example usage of the functionality.


<script src="https://cdn.jsdelivr.net/clipboard.js/1.5.12/clipboard.min.js"></script>

If you do not wish to use a CDN, you can download the clipboard in a couple other ways:

  • Using npm, by running npm install clipboard --save
  • Using bower, by running bower install clipboard --save
  • by downloading a zip file from The clipboard.js github page and referencing it in your HTML.

Once you've referenced clipboard.js in your project, usage is easy! First, add the following lines to your HTML file:


<script>
new Clipboard('.btn');
</script>

You will notice we are targetting elements with a CSS class of .btn here. Add some HTML with the data you want to cut or copy (only data in an input element can be cut, but any data can be copied):


<pre class="prettyprint" id='script-tag'>
&lt;script src="https://cdn.jsdelivr.net/clipboard.js/1.5.12/clipboard.min.js"&gt;&lt;/script&gt;
</pre>

Notice that I've given the pre element a css class of script-tag. Next, include a button that sets the action and target via data attributes:


<button class='btn btn-default' data-clipboard-action='copy' data-clipboard-target='#script-tag'>Copy to Clipboard</button>

The button above has a CSS class of btn. This was referenced when we initialized the library above. You will also notice that we set the clipboard action via data-clipboard-action and the target of the action via data-clipboard-target. If you click the button, the element with the id of script-tag will have it's contents copied to the clipboard.

Events

Sometimes we may wish to trigger certain events when the user cuts or copies data to the clipboard. Fortunately, we can do this easily! Simply change the lines that say:


<script>
new Clipboard('.btn');
</script>

To the code listed below, adding your own event based code where the comments are.


<script>
  var clipboard = new Clipboard('.btn');

  clipboard.on('success', function(e) {
    // Add your custom success code here.
  });

  clipboard.on('error', function(e) {
    // add your custom error code here.
  });
</script>

Pretty easy, right? If you have any questions or comments, feel free to leave them in the comments section below. Thanks for reading!