tags:

views:

324

answers:

3

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&lt;/div&gt;

...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!

A: 

Using a text area field, you could use this: (Via Google)

<form name="select_all">

    <textarea name="text_area" rows="10" cols="80" 
    onClick="javascript:this.form.text_area.focus();this.form.text_area.select();">

    Text Goes Here 

    </textarea>
</form>

This is how I see most websites do it. They just style it with CSS so it doesn't look like a textarea.

Chacha102
+1  A: 

This snippet provides the functionality you require. What you need to do is add an event to that div that which activates fnSelect in it. A quick hack that you totally shouldn't do and possibly might not work, would look like this:

document.getElementById("selectable").onclick(function(){
    fnSelect("selectable");
});

Obviously assuming that the linked to snippet had been included.

Simon Scarfe
+2  A: 
   <script type="text/javascript">
    function selectText() {
     if (document.selection) {
     var range = document.body.createTextRange();
            range.moveToElementText(document.getElementById('selectable'));
     range.select();
     }
     else if (window.getSelection) {
     var range = document.createRange();
     range.selectNode(document.getElementById('selectable'));
     window.getSelection().addRange(range);
     }
    }
    </script>

<div id="selectable" onclick="selectText()">http://example.com/page.htm&lt;/div&gt;
Denis Sadowski
Looks like Simon beat me to it.
Denis Sadowski