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



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();

} else if (window.getSelection) {
    var range = document.createRange();
     // alert("text copied") 

What suggestions do you have?



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

Hope it helps,



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.


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.


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.