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

Copy text to the clipboard with JavaScript in 10 lines of code
Check out my Github for my free-to-read JavaScript Ebook that covers all the new features from ES6 to 2019. If you want find a great place for interactive tutorials, i recommend Educative where I'm currently finishing to build my JavaScript course.
This website contains affiliate links. See my disclosure about affiliate links here

Create a copy to clipboard button

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 try this simple demo below.

I copied this text from InspiredWebDev.com

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>

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);
}

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}`);

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 Twitter for more.

complete guide to modern javascript alberto montalesi ebook bannerGet my ebook on Amazon and Leanpub or get my course on Educative


NEWEST ARTICLES




ABOUT ME

author alberto montalesi profile picture

Alberto is a software developer specialized in building enterpise software using Angular and author of the 'Complete guide to Modern JavaScript' ebook and course. In his free time he writes articles and tutorials on InspiredWebDev.com and Dev.to

You can read more about him here