Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple copy paste function in JavaScript

How I can make simple copy and paste for text in JavaScript? I would like to achieve that when I select some text in a textarea, then I can click on a button to copy it, then I can go to another page right click in another textarea and choose paste.

like image 779
Osama khodrog Avatar asked Apr 07 '11 09:04

Osama khodrog


People also ask

How can I copy text from JavaScript?

Create the textarea element and add it to the DOM. Populate its value with the text from the paragraph - or any other element. Use the above execCommand('copy') - method to copy the textual content.

How do I copy to the clipboard in JavaScript?

To copy text with the new Clipboard API, you will use the asynchronous writeText() method. This method accepts only one parameter - the text to copy to your clipboard.


2 Answers

Take a look at this library: https://github.com/zeroclipboard/zeroclipboard

You cannot access the clipboard in JavaScript, meaning flash is more or less your only option.

like image 147
Peeter Avatar answered Oct 10 '22 18:10

Peeter


Try this:

function copy() {
 if(window.clipboardData) {
   window.clipboardData.clearData();
   window.clipboardData.setData("Text", document.getElementById('txToCopy').value);
 } 
}

function paste() {
 if(window.clipboardData) {   
   document.getElementById('txToPaste').value = window.clipboardData.getData("Text");
 } 
}
<a href="javascript:copy();">Copy</a>
<br />
<input type="text" name="txToCopy" id ="txToCopy"/>
<br /><br />
<a href="javascript:paste();">Paste</a>
<br />
<input type="text" name="txToPaste" id="txToPaste"/>

It's a simple copy and paste function. Its working well in IE.

I hope it helps you.

like image 44
Anand Thangappan Avatar answered Oct 10 '22 20:10

Anand Thangappan