I have a span which shows the name of the user like this and a hidden input box which contains username of the user. The input box sits right below the span on UI and has visibility hidden
<span> My Name </span>
<input type = "text" class = "hidden" value = "MyUserName">
What I want is when the user clicks on the visible span and presses Ctrl + C, I want the value of the input box to get copied on the clipboard. (MyUserName in this case). Is there any way I can do this in Javascript?
I have a span which shows the name of the user like this and a hidden input box which contains username of the user. The input box sits right below the span on UI and has visibility hidden
<span> My Name </span>
<input type = "text" class = "hidden" value = "MyUserName">
What I want is when the user clicks on the visible span and presses Ctrl + C, I want the value of the input box to get copied on the clipboard. (MyUserName in this case). Is there any way I can do this in Javascript?
Share Improve this question asked Mar 9, 2011 at 22:54 AnkitAnkit 1211 silver badge4 bronze badges 1- possible duplicate of How to Copy to Clipboard in JavaScript? – Darin Dimitrov Commented Mar 9, 2011 at 22:57
3 Answers
Reset to default 3try this
<span onClick="CopyToClipboard()"> My Name </span>
<input type = "text" id="test" class = "hidden" value = "MyUserName">
then a script
<script type="text/javascript">
function CopyToClipboard()
{
document.getElementById('test').focus();
document.getElementById('test').select();
}
</script>
Take a look here: Handling Keyboard Shortcuts in Javascript. The author has created a library of Javascript functions that make it easy to do what you're asking.
With this script library, you can do something like:
shortcut.add("Ctrl+C",function() {
//Do something here
});
I have this handy functions that works for IE and Firefox (ask a permission). For others though you need zeroclipboard flash control.
When it cannott work, it displays a prompt with text focused so user can Ctrl+c the data
function copyText(text) {
if (window.clipboardData) { // Internet Explorer
window.clipboardData.setData("Text", ""+ text);
} else if (windowscape) { // Mozilla
try {
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var gClipboardHelper = Components.classes["@mozilla/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
gClipboardHelper.copyString(text);
} catch(e) {
return prompt("Ctrl+C this text : ", text);
}
} else {
return prompt("Ctrl+C this text : ", text);
}
return false;
}