Using execCommand (Javascript) to copy hidden text to clipboard
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>
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>