Copy text to clipboard on click using JavaScript

By Faruque Ahamed Mollick

In this post, I am going to tell you how to copy text to the clipboard by clicking a button so that the text can use the text anywhere just by pasting it there. Most probably, you have used on many websites.

Some ad network, API provider or any other websites let you copy their ad code or API by clicking a button. Also, some coding tutorial websites let us copy their code just by clicking a copy to clipboard button.

How to get value from input box in JavaScript?

Play/Pause Button For HTML5 Video Using JavaScript

Now you can also build the same copy to clipboard button on your web page or website by using JavaScript. We are going to see how to copy text on click in JavaScript. Today we are going to see how to do this.

In this tutorial, we will first create an HTML textarea with some text inside it. After that, we are going to create a button. When we click the button, the text content of textarea will be copied into clipboard and if we can paste it anywhere we like.

Now I am going to show you the code.



Below is the HTML code of text area and a button:

<textarea id="myText" rows="6" cols="22">This is the text content that will be copied to the clipboard.</textarea><br/>
<button id="btnCopy">Copy text</button>

We have set the id for both text area and button which will be used in our JavaScript code.

Below is the JavaScript code:

<script>
 document.getElementById("btnCopy").addEventListener("click", function(){
   var copyText = document.getElementById("myText");
   copyText.select();
   document.execCommand("Copy");
   alert("Copied to clipboard!");
 });
</script>

We have applied the click event listener to the button by selecting it by its id. Inside the event listener, we have used document.execCommand() method to copy the text from the text area box.

That’s it. Now if we run our work on a modern browser, we will be able to copy the text content inside the text box just by clicking on the “Copy text” button. We have set a JavaScript alert which will show a message “Copied to clipboard!” after clicking the button.

Convert seconds to HH-MM-SS format in JavaScript

Make a div element draggable using jQuery UI

Now, we can test if it is working or not by pasting it anywhere. After we paste it somewhere we will see the same text there what we saw at the time of clicking the “Copy text” button.

Well, the document.execCommand() method is not supported in IE9 and earlier. But all the modern browsers like chrome, opera, firefox, safari supports this.

So we have successfully created our own copy to clipboard functionality by using JavaScript code. I hope, you liked it.

Leave a Reply

Your email address will not be published. Required fields are marked *