Reputation: 1230
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.
Upvotes: 8
Views: 58355
Reputation: 476
You can use ClipBoard API for this,
//copy
navigator.clipboard.writeText("yuuhhhh");
//paste ,this needs user permission
navigator.clipboard.readText()
Now you can use .then function to do what ever you want.
Upvotes: 0
Reputation: 6144
have a look at this MDN article.
If you just want to copy user selected text you can do:
document.execCommand("copy");
if you need to select it previously:
document.getElementById('txToPaste').select();
In my case this code didn't work - it turns out select()
don't work for disabled
inputs.
you don't need any special permissions if you run it from an onClick
event listener, if you want another event to trigger the copy you are a bit in trubbles.
it works for me on Firefox and chrome, MDN says it won't work for safari but I haven't tested it.
Upvotes: 0
Reputation: 3106
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.
Upvotes: 1
Reputation: 9382
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.
Upvotes: 3
Reputation: 567
I think easiest way (and working in all browsers) is to watch keys pressed by user and if he press CTRL+C, save some data you want to copy into some variable.
I mean something like this:
var myClipboardVariable;
document.onkeyup = function(e){
if ((e.key == 'c') && e.ctrlKey){
// save data (you want to copy) into variable
myClipboardVariable = ....//some data
}
if ((e.key == 'v') && e.ctrlKey){
// paste saved data
.... paste your data from variable myClipboardVariable
}
}
Upvotes: 0
Reputation: 4583
Assuming you want to fetch user keyboard actions, you probably want to use Hotkeys: https://github.com/jeresig/jquery.hotkeys
Upvotes: 0