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.
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)
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
Line 9 - Now, we will create an event listener on the button click and we will create a function.
When the button is clicked, we will first copy the text of the input element.
Line 11 - using the input element reference, we will use the select command and select the text of the input element.
Line 12 - We use another command setSelectionRange(0,9999) for selecting input for mobile devices.
Line 13 - This is where the magic happens. We use the Clipboard API and write the value of the input field into the clipboard.
Line16 - Then we use the same Clipboard API and use the readText function to read the data. This method returns a promise so we will use ".then" to read the text and then do what we want to do.
For this example, we will write the copied text to the console.
This is what the end result looks like. When you click on the "Copy Text" button, it copies the text in the input field into the console.