Copy text to the clipboard with JavaScript in 10 lines of code
Tags: javascript, tutorial, beginners, codenewbie
Published: 2020-03-01 23:59:54

---
canonical_url: https://inspiredwebdev.com/copy-to-clipboard-with-javascript
---

> This article was originally posted on my [blog](https://inspiredwebdev.com/copy-to-clipboard-with-javascript). Head over to [inspiredwebdev.com](https://inspiredwebdev.com) for more articles and tutorials. Check out my **JavaScript course** on [Educative](https://www.educative.io/courses/complete-guide-to-modern-javascript?aff=BqmB) to learn everything from ES6 to ES2019.

&nbsp;

Hi, I am Alberto Montalesi, a full-stack self-taught developer. I create JavaScript tutorials and courses on my website [inspiredwebdev.com](https://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](https://inspiredwebdev.com/copy-to-clipboard-with-javascript).

&nbsp;

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:

```html
<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.

&nbsp;

## Write the JavaScript to copy to clipboard

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

```js
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:

```js
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.

&nbsp;

---

Thank you very much for reading. Follow me on [DevTo](https://dev.to/albertomontalesi) or on my blog at [inspiredwebdev](https://inspiredwebdev.com/) or on [twitter](https://twitter.com/montalesi). Check out [Educative.io](https://www.educative.io/explore?aff=BqmB) for interactive programming courses. 

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

<div className="promotional_banner">
<a href="http://a-fwd.to/5gUojI8" target="_blank">
<img alt="book banner" src="https://raw.githubusercontent.com/AlbertoMontalesi/The-complete-guide-to-modern-JavaScript/master/assets/banner.jpg" />
</a>
<span>Get my ebook on <a href="http://a-fwd.to/5gUojI8" target="_blank">Amazon</a> and <a href="https://leanpub.com/thecompleteguidetomodernjavascript2019" target="_blank">Leanpub</a></span>
</div>