clipboard.js
Modern copy to clipboard. No Flash. Just 3kb gzipped
README
clipboard.js
Modern copy to clipboard. No Flash. Just 3kb gzipped.
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.
- ```
- 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.
- ```html
- <script src="dist/clipboard.min.js"></script>
- ```
- ```js
- new ClipboardJS('.btn');
- ```
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.
- ```html
- !-- 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.
- ```html
- !-- Target -->
- <textarea id="bar">Mussum ipsum cacilds...</textarea>
- !-- Trigger -->
- <button class="btn" data-clipboard-action="cut" data-clipboard-target="#bar">
- Cut to clipboard
- </button>
- ```