clipboard.js

Modern copy to clipboard. No Flash. Just 3kb gzipped

README

clipboard.js


Build Status
Killing Flash

Modern copy to clipboard. No Flash. Just 3kb gzipped.


Demo

Why


Copying text to the clipboard shouldn't be hard. It shouldn't require dozens of steps to configure or hundreds of KBs to load. But most of all, it shouldn't depend on Flash or any bloated framework.

That's why clipboard.js exists.

Install


You can get it on npm.

  1. ```
  2. npm install clipboard --save
  3. ```

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

Setup


First, include the script located on the dist folder or load it from a third-party CDN provider.

  1. ```html
  2. <script src="dist/clipboard.min.js"></script>
  3. ```

Now, you need to instantiate it by passing a DOM selector, HTML element, or list of HTML elements.

  1. ```js
  2. new ClipboardJS('.btn');
  3. ```

Internally, we need to fetch all elements that matches with your selector and attach event listeners for each one. But guess what? If you have hundreds of matches, this operation can consume a lot of memory.

For this reason we use event delegation which replaces multiple event listeners with just a single listener. After all, #perfmatters.

Usage


We're living a _declarative renaissance_, that's why we decided to take advantage of HTML5 data attributes for better usability.

Copy text from another element


A pretty common use case is to copy content from another element. You can do that by adding a data-clipboard-target attribute in your trigger element.

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

example-2

  1. ```html
  2. !-- Target -->
  3. <input id="foo" value="https://github.com/zenorocha/clipboard.js.git" />
  4. !-- Trigger -->
  5. <button class="btn" data-clipboard-target="#foo">
  6.   <img src="assets/clippy.svg" alt="Copy to clipboard" />
  7. </button>
  8. ```

Cut text from another element


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

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

example-3

  1. ```html
  2. !-- Target -->
  3. <textarea id="bar">Mussum ipsum cacilds...</textarea>
  4. !-- Trigger -->
  5. <button class="btn" data-clipboard-action="cut" data-clipboard-target="#bar">
  6.   Cut to clipboard
  7. </button>
  8. ```

As you may expect, the `cut` action only works on `` or `