We are looking for a JavaScript code that would onClick copy the content of a given DIV ID into the Clip board.
We have found this JS code, which works fine in FireFox but works sometimes on Chrome and just about never on IE.
function CopyToClipboard(containerid) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(containerid));
range.select().createTextRange();
document.execCommand("copy");
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementById(containerid));
window.getSelection().addRange(range);
document.execCommand("copy");
// alert("text copied")
}}
I must admit I enjoyed more rolling my own as I do normally, but if what you need is get the job done quickly then use that script. It’s actually really simple and I think basically what it does is make it really explicit that you need a user generated click of a button (a virtually triggered event would not do the trick) in order to perform the copying
After some time spent on this, we decided to spend no more time on this and just tell users that not all browsers allow copy to clipboard upon click on button. And just stay with the JS code we have for now.