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!
To select all text inside an element such as DIV, we can simply use JavaScript document. createRange() method to create a range, and than using range. selectNodeContents() we can set node range (start and end), after which use selection. addRange() to select the range of the element.
The answer is definitely yes, but you will need to write javascript code for it. We can use a click handler on the div element to make it clickable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With