Using execCommand (Javascript) to copy hidden text to clipboard

Aaron Critchley picture Aaron Critchley · Jul 23, 2015 · Viewed 88.1k times · Source

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.

Answer

Dan Stevens picture Dan Stevens · Feb 23, 2017

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>