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.
-
1copy and paste text ; description : when a select some text in textArea , then click for a button to make copy it , when go to another page right click in textarea and choose paste .Osama khodroj– Osama khodroj2011-04-07 10:02:41 +00:00Commented Apr 7, 2011 at 10:02
6 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.
Comments
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.
1 Comment
Assuming you want to fetch user keyboard actions, you probably want to use Hotkeys: https://github.com/jeresig/jquery.hotkeys
Comments
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
}
}
1 Comment
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 fordisabledinputs.you don't need any special permissions if you run it from an
onClickevent 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.