DEV Community

Discussion on: how do you onClick, COPY text? (im making a app)

Collapse
 
christophermoura profile image
Christopher Moura

I like the document.execCommand approach, but you should look for the solution created by Zeno Rocha : github.com/zenorocha/clipboard.js

GitHub logo zenorocha / clipboard.js

βœ‚οΈ Modern copy to clipboard. No Flash. Just 3kb gzipped πŸ“‹

clipboard.js

Build Status Killing Flash

Modern copy to clipboard. No Flash. Just 3kb gzipped.

Demo

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.

<script src="dist/clipboard.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

Now, you need to instantiate it by passing a DOM selector, HTML element, or list of HTML elements.

new ClipboardJS('.btn');
Enter fullscreen mode Exit fullscreen mode

Internally, we need to fetch all elements that matches with your selector and attach event listeners for each one. But guess…