Download
User Rating: 4.8/5 ( 1 votes)
Clipboard.js is a modern approach to copy text to clipboard
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.
Browser Support
This library relies on both Selection and execCommand APIs. The second one is supported in the following browsers.
-
Chrome 42+
-
Firefox 41+
-
IE 9+
-
Opera 29+
-
Safari ✘
Although copy/cut operations with execCommand aren't supported on Safari yet (including mobile), it gracefully degrades because Selection is supported.
That means you can show a tooltip saying Copied! whensuccess event is called and Press Ctrl+C to copy when errorevent is called because the text is already selected.
For a live demonstration, open this site on Safari.
Source: zenorocha.github.io
1. INCLUDE JS FILES
<script src="dist/clipboard.min.js"></script>
2. HTML
you need to instantiate it using a DOM selector. This selector corresponds to the trigger element(s)
<!-- 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>
3. JAVASCRIPT
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.
new Clipboard('.btn');
4. 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.
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);
});
For a live demonstration, just open your console :)
5. ADVANCED USAGE
If you don't want to modify your HTML, there's a pretty handy imperative API for you to use. All you need to do is declare a function, do your thing, and return a value.
For instance, if you want to dynamically set a target, you'll need to return a Node.
new Clipboard('.btn', {
target: function(trigger) {
return trigger.nextElementSibling;
}
});
If you want to dynamically set a text, you'll return a String.
new Clipboard('.btn', {
text: function(trigger) {
return trigger.getAttribute('aria-label');
}
});
Also, with are working with single page apps, you may want to manage the lifecycle of the DOM more precisely. Here's how you clean up the events and objects that we create.
var clipboard = new Clipboard('.btn');
clipboard.destroy();