To accomplish our goal, we are going to make use of Clipboard API. This API is used to asynchronously read from and write to the system clipboard. It is accessible via the clipboard property of the Navigator interface.
In the following example, we have 2 textarea and 2 button elements. Upon click of the copy button, we will copy the text from the first textarea element and upon click of a paste button, we will paste the copied text into the second textarea element. Please have a look over the code example and the steps given below.
HTML & CSS
We have 3 elements in the HTML file (div, textarea, and button). The div element with a class of container is just a wrapper for the rest of the elements.
We have 2 button elements with an innerText of “Copy” and “Paste”.
We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
We have selected the button element with an id of copy using getElementById() and attached a click event listener to it.
There are 2 solutions for copying the text from the textarea element.
In first solution, we are selecting entire text in the first textarea element by using getElementById() and select() methods. Then, we are executing the copy command by calling execCommand() method and passing the string “copy” as a parameter.
In the second solution, we are selecting the first textarea element by using the getElementById() method and storing it in the copyArea variable. We are copying text to the clipboard by calling navigator.clipboard.writeText() method and passing the value of the textarea element as a parameter.
We have selected the button element with an id of paste using getElementById() and attached a click event listener to it.
We are selecting the second textarea element by using the getElementById() method and storing it in the pasteArea variable.
We are setting empty string as its value to make sure the textarea element is empty.
We are using the asynchronous navigator.clipboard.readText() method to read the text from the clipboard. After reading the text, we are setting it as a value of the second textarea element.