How to copy the content of a DIV into the Clip board?

Hello,

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") 
}}

What suggestions do you have?

Thanks.

Hi @WorldNews, do you know about clipboard.js? It supports IE9 and above.

Hope it helps,

Andres

2 Likes

We also have this, which goes into detail on how to roll your own:

FWIW, I’d go with the library mentioned by Andreas, but I though the link might be interesting nonetheless.

3 Likes

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

Yes, the clipboard belongs to the user not the site. So it’s more or less protected from script that wants to work with it.

2 Likes

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.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.