Clipboard.js Library

Clipboard.js is a small JavaScript library that allows you to copy text to the clipboard without using Flash. It is a lightweight library that is only about 3kb gzipped, and it works in all modern browsers.
How to Setup Clipboard.js
First, add the following script code to your page to activate the library.
<script src="https://clipboardjs.com/dist/clipboard.min.js"></script>
And use the JS code below.
new ClipboardJS('.btn');
Usage of Clipboard.js
Using HTML5’s data attributes, data inside an HTML element can be copied or deleted with clipboard.js.
With data-clipboard-target
, the element that will copy the text is targeted.
<button class="btn" data-clipboard-target="#copy-text">Copy</button>
<textarea id="copy-text">Lorem ipsum dolor sit amet.</textarea>
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.11/clipboard.min.js"></script>
<script>var clipboard = new ClipboardJS('.btn');</script>
Example
The data-clipboard-action
property specifies that the text in the element will be copy or cut.
data-clipboard-action=”copy” (Copy Content)
Using data-clipboard-action="copy"
is used to copy the text.
Note: There is no need to use this feature because by default the copy function works.
<button class="btn" data-clipboard-target="#copy-text" data-clipboard-action="copy">Copy</button>
<textarea id="copy-text">Lorem ipsum dolor sit amet.</textarea>
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.11/clipboard.min.js"></script>
<script>var clipboard = new ClipboardJS('.btn');</script>
Example
data-clipboard-action=”cut” (Cut Content)
Using data-clipboard-action="cut"
is used to cut the text.
Note: The cut action only work on <input>
or <textarea>
tags.
<button class="btn" data-clipboard-target="#copy-text" data-clipboard-action="cut">Cut</button>
<textarea id="copy-text">Lorem ipsum dolor sit amet.</textarea>
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.11/clipboard.min.js"></script>
<script>var clipboard = new ClipboardJS('.btn');</script>
data-clipboard-text
In some cases, another element may not be needed to copy text. With the data-clipboard-text
feature, text can be added to the button and copied.
<button class="btn" data-clipboard-text="Lorem ipsum dolor sit amed.">Copy</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.11/clipboard.min.js"></script>
<script>var clipboard = new ClipboardJS('.btn');</script>
Example
Note: If you are going to use more than one copy button on a page, make sure that the id’s of the elements targeted by these buttons are different. Otherwise, the buttons may not work correctly.
Supported Browsers for Clipboard.js
- Google Chrome 42+ Version
- Microsoft Edge 12+ Version
- Mozilla Firefox 41+ Version
- Opera 29+ Version
- Safari 10+ Version