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

albertomontalesi

AlbertoM

Posted on March 1, 2020

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

💖 💪 🙅 🚩
albertomontalesi
AlbertoM

Posted on March 1, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

JavaScript Math()
javascript JavaScript Math()

June 21, 2023

Why 0.1+0.2==0.3 False?
javascript Why 0.1+0.2==0.3 False?

August 29, 2022

Creating and Consuming Custom Events
javascript Creating and Consuming Custom Events

August 10, 2022

Utilizing a Nested GET Request
javascript Utilizing a Nested GET Request

July 3, 2022