Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you select the text in a div (for copying into the clipboard) from javascript?

I have a div containing some text that I would like the user to be able to easily copy from the page (via the clipboard). Is there a cross browser way to select all of the text within a div on a mouseclick?

like image 544
jsight Avatar asked Sep 11 '25 18:09

jsight


1 Answers

Cross browser support for clipboard copying via Javascript requires using Flash to get around Firefox/Netscape's security, which denies access to the clipboard. If you are using jQuery you can easily make use of the clipboard plugin. If you are rolling your own Javascript without using jQuery then this blog post may help.

In addition, you can actually adjust Firefox's security permissions to allow scripts access to your clipboard. A good walkthrough is available at dojotoolkit.org. This usually isn't the path pursued as it would require each of your users to make this adjustment. Much easier to use Flash as it works with all modern browsers (Safari, IE, Firefox, and Opera).

like image 91
nascent.cognition Avatar answered Sep 14 '25 08:09

nascent.cognition