DEV Community

loading...

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

yobretyo profile image Bret ・1 min read

how do you "copy" the text that's within a class or id?
I want to build a app, that I can add custom snippets to, that I can just click a button... to copy... the snippet to paste.

what would that look like?

Discussion (3)

pic
Editor guide
Collapse
juneikerc profile image
Juneiker

there are different ways to do that, personally I use navitagor.clipboard but you can also use Document.execCommand.

developer.mozilla.org/en-US/docs/W...
30secondsofcode.org/blog/s/copy-te...

Collapse
rishitkhandelwal profile image
Rishit Khandelwal • Edited

Well, navigator.clipboard ig?

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…