How to Copy to Clipboard with JavaScript

Copying content from an element in a web page is a really useful feature of a JavaScript-supporting browser, however, this is not the case if a random website you visit decides to automatically copy content into your clipboard. As a result, copying to the clipboard in JavaScript is limited to being triggered by a user action such as a click event.

 

In this tutorial, we will learn how to copy to clipboard with JavaScript using an example.

 

Copy Text to Clipboard

The plan is to have a textarea containing some text that will be copied when a user clicks the copy button. Let's start with the HTML elements, which will be a textarea with an ID of content and a button with an ID of copy.

 

<textarea id="content">Some text to copy.</textarea>
<button id="copy">Copy</button>

 

Next, we will get both of the elements using the JavaScript getElementById function and store them in the variables btn and element.

 

var content = document.getElementById("content");
var btn = document.getElementById("copy");

 

Now we will create a function to copy the text in the content element. It will be initiated when a user clicks the copy button.

 

btn.addEventListener('click',function () {

  content.select();
  content.setSelectionRange(0, 99999);

  document.execCommand("copy");

  document.getSelection().removeAllRanges();
});

 

There are a few things occurring in the function above so let's take a look at what is happening here.

 

  • Firstly we are selecting the text in the content element using select()
  • If the user is on a mobile device we are also selecting text with setSelectionRange()
  • Then we are copying the selected text using execCommand
  • Finally, we are deselecting the text using removeAllRanges

 

Conclusion

You now know how to create a function that copies the content of an element to the clipboard when a user clicks a button with pure JavaScript. Of course, there was no styling or instructions to add a tooltip here - I feel that falls out of the scope of how to copy to the clipboard using JavaScript.

 

With that said it is relatively easy to add a tooltip to the copy button with a CSS ::before or ::after selector and putting some logic in the JavaScript btn click function to display the appropriate message after copying.

copy browser