Thanh Tran March 19, 2023

There are so many websites where you might have seen the copy button or the Copy To Clipboard button.

These "Copy text" buttons come in handy when you click a button and it copies the text of an input field or a textarea.

These "Copy Text" buttons improve the overall user experience giving users easy to copy text from input fields.

We will build one of these "Copy Text" buttons in this blog post using the Clipboard API that browsers give us.

Creating The HTML for Copy Button Javascript

For this blog post, we will create a simple input element and provide a default value for the input field.

The two main elements in the above image to look out for are the input field which has a value and the button, which will be used to copy the text.

When we click the button, the script will copy the text from the input field using the Clipboard API.

The elements above look like this. We have applied some basic CSS styles for this demo which is totally optional.

If you are curious, the CSS styles we have added are as below: (totally optional)

Let's see what the above javascript code is doing:

Line 6 - In this line, we are reading the document and finding the button that we need to click.

Line 7 - In this line, we are reading the document and finding the input field using the document.querySelector command


You must be signed in to comment.