DEV Community


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)

Editor guide
juneikerc profile image

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

rishitkhandelwal profile image
Rishit Khandelwal • Edited

Well, navigator.clipboard ig?

christophermoura profile image
Christopher Moura

I like the document.execCommand approach, but you should look for the solution created by Zeno Rocha :

GitHub logo zenorocha / clipboard.js

✂️ Modern copy to clipboard. No Flash. Just 3kb gzipped 📋


Build Status Killing Flash

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



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.


You can get it on npm.

npm install clipboard --save

Or if you're not into package management, just download a ZIP file.


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…