How to copy text to the clipboard with JavaScript 

April 19, 2022

How to copy text to the clipboard with JavaScript 

In this article you will learn how to copy text to the clipboard with JavaScript in a simple way, to use in your programs!

copy text to the clipboard with JavaScript thumb

Hey you programmer, ok? Let’s learn better how to create the function to copy texts with JavaScript!

To solve this problem we will use the execCommand function with the copy parameter

But first let’s create our HTML structure:

<textarea class="text">Text to copy</textarea>
<button id="copy">Copy</button>

In the example we have a textarea which is probably where you will copy the texts from and also an action button

And now for the JavaScript logic:

let btn = document.querySelector('#copy');

btn.addEventListener('click', function(e) {
 let textArea = document.querySelector('.text');;

Here we select the button element and then we attach a click event to it, to make the copy action

Inside the event, we assign the textarea to a variable, we perform the selection and copy of the text, through the execComand method with the copy parameter

In this way the text will be copied to the clipboard and with a Ctrl + v or paste from the right click we can insert the text anywhere

Cool huh? 😀


In this article we learned how to copy text to the clipboard with JavaScript, the famous Clipboard

The idea is to select the text that should be copied by the select method

And finally make the copy with execCommand

The most interesting thing is that all these features are native to JavaScript, in a simple way we can copy the text into an input!

Do you want to learn more about JS and web development? Click here!

Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x