DEV Community

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

Posted on • Updated on • Originally published at ibrahima-ndaw.com

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

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, it helps a lot in increasing the usability of our website.

In this post, we are going to make the text copiable to the clipboard with just a few lines of JavaScript.

The markup

To make this post quick and easy to digest, I will use Tailwind CSS to style the app and make everything look nice.

So, for the HTML part, it will be very simple (except the bunch of classes added by Tailwind CSS).

<main class="flex flex-col h-screen justify-center items-center bg-gray-100">
  <div class="bg-white max-w-sm p-5 rounded shadow-md mb-3">
    <input
      class="border-blue-500 border-solid border rounded py-2 px-4"
      type="text"
      placeholder="Enter some text"
      id="copyMe"
    />
    <button
      class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 border border-blue-700 rounded"
      onclick="copyMeOnClipboard()"
    >
      Copy
    </button>
  </div>
  <p class="text-green-700"></p>
</main>
Enter fullscreen mode Exit fullscreen mode

Here, there are 3 important things to retain:

  • The id of the input tag copyMe
  • The function copyMeOnClipboard() of the button tag
  • The p tag

The id copyMe will help us to access to the value entered by the user. And when he clicks on the Copy button, it will trigger the copyMeOnClipboard() method which will handle the copy and show a success message dynamically with JavaScript.

With that being said, we can now move on to the JS file and do the final touch.

JavaScript is awesome

awesome

JavaScript

Of course, JavaScript is cool. And its document object has some very handy methods.

const copyText = document.querySelector("#copyMe")
const showText = document.querySelector("p")

const copyMeOnClipboard = () => {
  copyText.select()
  copyText.setSelectionRange(0, 99999) // used for mobile phone
  document.execCommand("copy")
  showText.innerHTML = `${copyText.value} is copied`
  setTimeout(() => {
    showText.innerHTML = ""
  }, 1000)
}
Enter fullscreen mode Exit fullscreen mode

As you can see here, we start by selecting our needed elements copyText and showText. It's respectively the input and the paragraph tags. Then, we use the copyMeOnClipboard() function to handle the logic.

The copyText element (remember it's the input tag) gives us access to the select() method and as you might guess it selects the content of the input text field.

And finally, we execute the copy command with document.execCommand("copy") and get the text on the clipboard.

It's too easy

easy

We've now done, but we can still improve it a little bit by showing to the user a success message. It's quite easy because we already have the showText element. The only thing we have to do is append the success message with innerHTML and remove it after 1 second with setTimeout().

And That's all folks!

Thanks for reading it.

Top comments (15)

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