Saturday, April 27, 2024
 Popular · Latest · Hot · Upcoming
70
rated 0 times [  74] [ 4]  / answers: 1 / hits: 142964  / 15 Years ago, thu, july 23, 2009, 12:00:00

How to highlight/select the contents of a DIV tag when the user clicks on the DIV...the idea is that all of the text is highlighted/selected so the user doesn't need to manually highlight the text with the mouse and potentially miss a bit of the text?



For example, say we've got a DIV as below:



<div id=selectable>http://example.com/page.htm</div>


...and when the user clicks on any of that URL the whole URL text is highlighted so they can easily drag the selected text around in the browser, or copy the complete URL with a right click.



Thanks!


More From » css

 Answers
29



function selectText(containerid) {
if (document.selection) { // IE
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(containerid));
range.select();
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementById(containerid));
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
}

<div id=selectable onclick=selectText('selectable')>http://example.com/page.htm</div>





Now you have to pass the ID as an argument, which in this case is selectable, but it's more global, allowing you to use it anywhere multiple times without using, as chiborg mentioned, jQuery.


[#99068] Sunday, July 19, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jensenb

Total Points: 634
Total Questions: 102
Total Answers: 102

Location: Bosnia and Herzegovina
Member since Thu, Jun 24, 2021
3 Years ago
;