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?
views:
248answers:
5<SPAN ID="copytext" STYLE="height:150;width:162;background-color:pink">
This text will be copied onto the clipboard when you click the button below. Try it!
</SPAN>
<TEXTAREA ID="holdtext" STYLE="display:none;">
</TEXTAREA>
<BUTTON onClick="ClipBoard();">Copy to Clipboard</BUTTON>
function ClipBoard()
{
holdtext.innerText = copytext.innerText;
Copied = holdtext.createTextRange();
Copied.execCommand("Copy");
}
Have a look at these both: http://yangshuai.googlepages.com/jquerycopyplugin http://plugins.jquery.com/project/clipboard
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).
I couldn't find a way to select text in a div, and didn't really want to use the flash approach to just copy it (though that is a nice tool to have available).
I ended up just doing this:
function selectIncidentIDText (incidentIDTxtEl) {
incidentIDTxtEl.select();
}
<h:inputText value="(IncidentID: #{ViewIncidentBean.incident.id})" readonly="true" onclick="selectIncidentIDText(this);"/>
That works well enough for what I wanted, albeit it is a bit ugly.