Create a copy to clipboard button in JavaScript (w/wo Input)

In this tutorial, we will be discussing how to create a copy to clipboard button. Often in websites , you may have seen such buttons that allow us to copy the content present in the text-area or that particular box. There are numerous scenarios in web development where users have to be provided with a copy to clipboard button. Though they can select the content and Ctrl+C to copy the content but sometimes, that’s a bit hectic and time taking process if the content is too long. In such situations, the copy to clipboard button comes to rescue. We can create a copy button to copy the data given to the clipboard by using navigator.clipboard.writeText() function. This function writes/copies the data fed to it as a parameter into the clipboard.

We will discuss two examples in this blog. In the first , the user can copy the content already present on the webpage and in the second example , the user can copy the text written by them.

Let’s get started.

Text Copy to Clipboard in JavaScript

Copy text to clipboard in JavaScript without Input

The below demo with help you learn about copying the plain text (without html tag) from a div using the Clipboard API with JavaScript.

Demo (Review On Codepen)

See the Pen Copy to Clipboard using JavaScript in HTML by Arpit Mittal (@codingiseasy) on CodePen.

Copy to Clipboard JavaScript with Input

Demo (Review On Codepen)

See the Pen Text copy the content of an input field with JavaScript by Arpit Mittal (@codingiseasy) on CodePen.

Hope you have learnt how to create a copy to clipboard button using JavaScript. And hope you had fun doing the two examples provided in this tutorial. Feel free to comment below with your queries and doubts.

Leave a Comment