Copy to Clipboard Without Flash With Clipboard.js

Copy to Clipboard without Flash with Clipboard.js

Well, in this article I gonna show you how to easily implement the ability to copy data to the clipboard. In order to implement it I will clipboard.js javascript library, let get started with me:

Installation

The first thing I need to do is include the clipboard.js library file in head tag of the application:

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

If you don’t wish to use a CDN, you can download the clipboard in 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.

Usage

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.

1
2
3
4
5
6
7
<!-- Target -->
<input id="foo" value="https://github.com/zenorocha/clipboard.js.git">

<!-- Trigger -->
<button class="btn" data-clipboard-target="#foo">
    <img src="assets/clippy.svg" alt="Copy to clipboard">
</button>

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.

1
2
3
4
5
6
7
<!-- Target -->
<textarea id="bar">Mussum ipsum cacilds...</textarea>

<!-- Trigger -->
<button class="btn" data-clipboard-action="cut" data-clipboard-target="#bar">
    Cut to clipboard
</button>

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

Copy text from attribute: Truth is, you don’t even need another element to copy its content from. You can just include a data-clipboard-text attribute in your trigger element.

1
2
3
4
<!-- Trigger -->
<button class="btn" data-clipboard-text="Just because you can doesn't mean you should — clipboard.js">
    Copy to clipboard
</button>

Events

There are cases where you’d like to show some user feedback or capture what has been selected after a copy/cut operation.

That’s why we fire custom events such as success and error for you to listen and implement your custom logic.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var clipboard = new Clipboard('.btn');

clipboard.on('success', function(e) {
  console.info('Action:', e.action);
  console.info('Text:', e.text);
  console.info('Trigger:', e.trigger);

  e.clearSelection();
});

clipboard.on('error', function(e) {
  console.error('Action:', e.action);
  console.error('Trigger:', e.trigger);
});

So far so good, That’s it!!! See ya!!! :)