I'm trying to copy to clipboard without using Flash, I plan to fall back onto Flash with the use of ZeroClipboard if the browser is incompatible with the javascript approach.
I have an onClick listener for the button which looks like:
$(buttonWhereActionWillBeTriggered).click(function(){
var copyDiv = document.getElementById(inputContainingTextToBeCopied);
copyDiv.focus();
document.execCommand('SelectAll');
document.execCommand("Copy", false, null);
}
and an input field as follows:
<input type="text" name="Element To Be Copied" id="inputContainingTextToBeCopied" value="foo"/>
This currently works as expected but the design requires that the field containing the text to be copied is invisible. I have tried both setting type="hidden"
and style="display: none"
neither of which have succeeded. Both result in the button selecting the whole page and copying the whole content to the user's clipboard.
I'm relatively confident the cause is not browser-based but just in case, I am testing on Chrome (Version 43.0.2357.134 (64-bit)) on Mac OS X 10.10.4.
Is there a way that I can maintain the functionality of when the < input> is visible whilst hiding it? or if not an alternate route I can take?
I'm aware of similar questions, none of which address my problem, either from being too old, not actually using Javascript, or not fitting the particular scenario. Here's a good answer for anyone having similar, less specific issues.
Select the text or graphics you want to copy, and press Ctrl+C. Each selection appears in the Clipboard, with the latest at the top. Optionally, repeat step 2 until you've copied all the items you want to use. Tip: After you open the Clipboard, it stores content that you copy or cut from anywhere.
To copy output of a JavaScript variable to the clipboard, we can use the navigator. clipboard. writeText method. const copyToClipboard = (text) => { return navigator.
Here's my solution that doesn't use jQuery:
function setClipboard(value) {
var tempInput = document.createElement("input");
tempInput.style = "position: absolute; left: -1000px; top: -1000px";
tempInput.value = value;
document.body.appendChild(tempInput);
tempInput.select();
document.execCommand("copy");
document.body.removeChild(tempInput);
}
<!DOCTYPE html>
<html>
<head>
<title>Set Clipboard</title>
</head>
<body>
<button onclick="setClipboard('foo loves bar')">Set Clipboard</button>
</body>
</html>
2019 - was still looking for an answer without offscreen stuff.
What I did is first change the input text field to type="text", copy the text and then change it back to type="hidden". That works well.
<input id="dummy" name="dummy" type="hidden">
<script>
var copyText = document.getElementById("dummy");
copyText.type = 'text';
copyText.select();
document.execCommand("copy");
copyText.type = 'hidden';
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With