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
npm install clipboard --save
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
<scriptsrc="dist/clipboard.min.js"></script>
Now, you need to instantiate it by passing a DOM selector, HTML element, or list of HTML elements.
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.
Each application has different design needs, that’s why clipboard.js does not include any CSS or built-in tooltip solution.
The tooltips you see on this demo site were built using GitHub’s Primer . You may want to check that out if you’re looking for a similar look and feel.
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.
Also, if you 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.
1 2
var clipboard = newClipboard('.btn'); clipboard.destroy();
Browser Support
This library relies on both Selection and execCommand APIs. The first one is supported by all browsers while the second one is supported in the following browsers.
Chrome 42+
Edge 12+
Firefox 41+
IE 9+
Opera 29+
Safari 10+
The good news is that clipboard.js gracefully degrades if you need to support older browsers. All you have to do is show a tooltip saying Copied! when success event is called and Press Ctrl+C to copy when error event is called because the text is already selected.
You can also check if clipboard.js is supported or not by running Clipboard.isSupported(), that way you can hide copy/cut buttons from the UI.
Bonus
A browser extension that adds a “copy to clipboard” button to every code block on GitHub, MDN, Gist, StackOverflow, StackExchange, npm, and even Medium.