clipboard.js

A modern approach to copy & cut to the clipboard

No Flash. No dependencies. Just 2kb

Install

You can get it on npm.

npm install clipboard --save

Or bower, too.

bower install clipboard --save

If you're not into package management, just download a ZIP file.

Setup

First, include the script located on the dist folder

<script src="dist/clipboard.min.js"></script>

Now, you need to instantiate it using a DOM selector. This selector corresponds to the trigger element, i.e. <button>.

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

Usage

There are different options for you to use and they all take advantage of HTML5 data attributes.

Copy text from attribute

The easiest way to copy some content to the clipboard, is to include a data-text attribute in your trigger element.

<!-- Trigger -->
<button class="btn" data-text="Heya!">Copy</button>

Copy text from another element

Alternatively, you can copy content from another element by adding a data-target attribute in your trigger element.

The value you include on this attribute needs to match another's element id attribute.

<!-- Target -->
<input id="foo" value="https://git.io/vn3cM">

<!-- Trigger -->
<button class="btn" data-target="foo">Copy</button>

Cut text from another element

Additionally, you can define a data-action attribute to specify if you want to either copy or cut content.

If you omit this attribute, copy will be used by default.

<!-- Target -->
<textarea id="bar">clipboard.js rocks!</textarea>

<!-- Trigger -->
<button class="btn" data-action="cut" data-target="bar">
    Copy
</button>

As you may expect, the cut action only works on <input> or <textarea> elements.

Browser Support

This library relies on both Selection and execCommand APIs. When combined, they're supported in the following browsers.