DEV Community

Cover image for How to copy text to the clipboard with JavaScript (5 lines of code)?

How to copy text to the clipboard with JavaScript (5 lines of code)?

Ibrahima Ndaw on January 27, 2020

Originally posted on my blog As a developer, we know how useful and good it is to have a "copy" button sitting next to a code block. In some cases...
Collapse
 
assisfery profile image
Assis Ferreira

I made a simple library to facilitate that work, you can check and contribute in github.com/assisfery/CopyPasteJS

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

cool. looking forward to giving it a try

Collapse
 
devmount profile image
Andreas

Just curious: What exactly are the 5 lines of code?

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw • Edited
1 const copyText = document.querySelector("#copyMe")
2 const copyMeOnClipboard = () => {
3 copyText.select()
4 copyText.setSelectionRange(0, 99999) // used for mobile phone
5 document.execCommand("copy") }

That's the code that does the copy.

Collapse
 
samydoesit profile image
samydoesit • Edited

You could also use the browser Clipboard API - "navigator.clipboard"

const str = 'String to copy'

function copyToClipboard (str) {
    navigator.clipboard.writeText(str)
}
Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

Yeah it's a great one. But it's still not supported by all browsers.

Collapse
 
octopoulos profile image
octopoulos

That's the only one to use to be honest, and according to caniuse, all browsers support it except Opera Mini and UC Browser for Android.

Collapse
 
waylonwalker profile image
Waylon Walker

Had no idea it was that easy 🤯. Love the addition of the code pen.

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

I'm glad you find value on it.

Collapse
 
x777 profile image
YD

Cool)

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

👍

Collapse
 
lorenzosjb profile image
Lorenzo Jiménez • Edited

First, be sure that you review browser compatibility that you are supporting.
Also, one thing is getting data from the clipboard and putting it on it, that is very different to implement.

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

According to Can I Use 93.39% of browsers support this method.

And to paste something on the input field just do this document.execCommand("paste")

Collapse
 
madza profile image
Madza • Edited

Also there is a handy, lightweight library for this

Collapse
 
ibrahima92 profile image
Ibrahima Ndaw

Thanks for sharing the resource