Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selecting all text within a div on a single left click with javascript

I have a simple non-clickable link within a div that looks like this: alt text

It's meant to be a sharable link that the user can copy paste into other things.

For usability purposes, I want a single left click anywhere within the div to select the entire link: alt text

I don't know much about, javascript/web programming, so I've tried the following:

<div id="share_link" onClick="select_all('share_link')"><%= request.url %></div>

and this javascript

<script type="text/javascript">
    function select_all(id) {
        document.getElementById(id).focus();
    }
</script>

This doesn't work. I'd like to know what's the simplest thing I should do to achieve what I want. I thought about changing the div to a text input or the text within to be a link, but ideally the content within should be read-only, non-editable, and non-clickable

like image 592
tstyle Avatar asked Jan 02 '11 12:01

tstyle


1 Answers

This is achieved completely differently in IE compared to other browsers. The following will work in all major browsers:

<script type="text/javascript">
    function select_all(el) {
        if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") {
            var range = document.createRange();
            range.selectNodeContents(el);
            var sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (typeof document.selection != "undefined" && typeof document.body.createTextRange != "undefined") {
            var textRange = document.body.createTextRange();
            textRange.moveToElementText(el);
            textRange.select();
        }
    }
</script>

<div onclick="select_all(this)">Link text</div>
like image 94
Tim Down Avatar answered Oct 24 '22 14:10

Tim Down