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


#1

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.


#2

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

Hope it helps,

Andres


#3

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.


#4

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


#6

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.


#7

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.


closed #8

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