How can you select text in a div (for copy to clipboard) from javascript?

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

+3
source share
5 answers

- Javascript Flash Firefox/Netscape, . jQuery, clipboard . Javascript jQuery, dojotoolkit.org. , , . Flash, (Safari, IE, Firefox Opera).

+2
<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");
    }

+1

.

0

div, -, ( ).

In the end, I just did this:

function selectIncidentIDText (incidentIDTxtEl) {
    incidentIDTxtEl.select();
}
<h:inputText value="(IncidentID: #{ViewIncidentBean.incident.id})" readonly="true" onclick="selectIncidentIDText(this);"/>

This works well enough for what I wanted, although it is a bit ugly.

0
source

Source: https://habr.com/ru/post/1704924/


All Articles