Copy to clipboard in JavaScript
The code above has two parts.
- Copy the text you want directly.
- Copy the text from the element you want to copy from
If you want to copy certain text without displaying them your browser, use the “copy.js”. Or if you want to copy from the input or textarea or contenteditable texts, you can select the text from the “select.js” and then use the “copyFromElement.js”.
The above code run in most modern browsers. It may not support in some of the mobile browsers.
Detailed Explaination
- copy.js
Copying text is a tricky work. The real trick here is to create a text area with css positioning on the left of the screen. Due to the positioning of the textarea, the textarea will not be visible in the browser. Now, I execute a command to copy the content in the textarea. After my copy is finished, I removed the textarea from the document body.
2. copyFromElement.js
It is similar to the previous one. The only difference is to select the text from the given element and execute copy command.
Reference:
