DEV Community

Cover image for Copy text to the clipboard with JavaScript in 10 lines of code
AlbertoM
AlbertoM

Posted on • Edited on • Originally published at inspiredwebdev.com

JavaScript Copy to Clipboard Copy text to the clipboard with JavaScript in 10 lines of code

This article was originally posted on my blog. Head over to inspiredwebdev.com for more articles and tutorials. Check out my JavaScript course on Educative to learn everything from ES6 to ES2019.

 

Hi, I am Alberto Montalesi, a full-stack self-taught developer. I create JavaScript tutorials and courses on my website inspiredwebdev.com to inspire other developers to grow and build the career that they want.

In this short tutorial, we are going to look at how to implement the copy to clipboard functionality in your website or app with just a few lines of JavaScript.

There are various reasons why you would prefer to have a button to copy to the clipboard rather than simply have your user have to highlight and manually copy text and fortunately for you, it's a very simple feature to implement.

Before diving into the code, you can view a demo on my original article.

 

The way we are going to do that is by creating an invisible textarea into which we are going to copy our string and execute a 'copy' command to save the value to our clipboard. Once done, we will delete that DOM element.

First of all, let's start creating our dummy content:

<div>
    <p id="item-to-copy">I copied this text from InspiredWebDev.com</p>
    <button onclick="copyToClipboard()">Copy</button>
<div>
Enter fullscreen mode Exit fullscreen mode

Nothing much to see here, a p tag with some dummy content and a button with an onclick function.

I had to put an id on my p tag to be allowed to target it with my function.

 

Write the JavaScript to copy to clipboard

Now let's write our function and then we'll go over each line of code:

function copyToClipboard() {
    const str = document.getElementById('item-to-copy').innerText;
    const el = document.createElement('textarea');
    el.value = str;
    el.setAttribute('readonly', '');
    el.style.position = 'absolute';
    el.style.left = '-9999px';
    document.body.appendChild(el);
    el.select();
    document.execCommand('copy');
    document.body.removeChild(el);
}
Enter fullscreen mode Exit fullscreen mode

Let's go over the code line by line:

Firstly, we get the content of the target element, you can omit this line if you are already passing a string to your function. In this case, the content is derived from a specific element of the page so we need to get it upon click.

We then proceed to create a new textarea element and set some properties onto it:

  • we set the value to match the content of our string
  • we set readonly, position absolute and left -9999px just to make our textarea invisible to the user

We then append the element to the DOM so that right after we do that, we can call select() onto it.

What select does is simply select the content of our element. You may be asking: why didn't we simply call select() on the p tag? Why did we have to create a new textarea?

The answer to that is very straightforward, we can only call select() on textarea and input elements.

If you are implementing copy to clipboard on a comment field, for example, which may be already using a textarea element, then you can call select() directly onto it, without having to create a new DOM element as we are doing in this tutorial.

After we are done with select() we are calling document.execCommand('copy') which will copy the selected content.

Lastly, we remove the textarea from the DOM with removeChild(el).

Now, if you try to press 'ctrl + v' or simply right-click and select paste you will see that the content of the p tag got copied to the clipboard;

Let's make it more visual and add one more line to our function, right after the removeChild() call:

alert(`Copied: ${str}`);
Enter fullscreen mode Exit fullscreen mode

Now, go ahead and try again. You will see an alert telling you what content you just copied.

Awesome! In just 10 lines of code, you created a simple yet very useful functionality.

 


Thank you very much for reading. Follow me on DevTo or on my blog at inspiredwebdev or on twitter. Check out Educative.io for interactive programming courses.

Disclaimer: Links to Amazon and Educative are affiliate links, purchases you make will generate extra commissions for me. Thank you


book banner

Get my ebook on Amazon and Leanpub

Top comments (4)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Might be worthwhile discussing navigator.clipboard too

Collapse
 
albertomontalesi profile image
AlbertoM

You need to add it to the DOM so that you can then select its content. As I said, if the element you want to copy to clipboard is an input field you don't need to do that.

Collapse
 
_akshaym profile image
Akshay Mahajan

I built a reusable React component using the same method. You can check it out at npmjs.com/package/react-copy-content

Collapse
 
trippymonk profile image
Blake Stansell

This is cool Is it how various web clippers work? Like Evernote and Notion?