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?
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?
Share Improve this question asked Mar 17, 2009 at 20:47 jsightjsight 28.5k25 gold badges110 silver badges140 bronze badges 05 Answers
Reset to default 2Cross 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. 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).
Have a look at these both: http://yangshuai.googlepages./jquerycopyplugin http://plugins.jquery./project/clipboard
<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");
}
From Here
This question may have some clues for you.
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.