views:

90

answers:

2

Hello

who would know of a possibility to automatically select Paragaph text as it gets rendered in a browser, preferably using JavaScript?

In my case I have an amount of text in <p></p> tags and would like the page to appear with the text fully selected, just as if someone had done it manually with the mouse.

Many thanks for your suggestions!

+2  A: 

Insert this near the very end of your page:

<script type='text/javascript'>

ptags = window.document.getElementsByTagName("p");
current_selection = window.getSelection();

for (i=0; i< ptags.length; i++)
{
    var r1 = document.createRange();
    r1.setStartBefore(ptags[i]);
    r1.setEndAfter(ptags[i]) ;
    current_selection.addRange(r1);
}

</script>

Tested in Firefox 3.07 --> not really sure about cross-browser compatibility, although I think IE should be all right.

ChristopheD
Tested and working in latest Fx and Opera, but not IE7. http://jsbin.com/etabe
strager
+2  A: 

According to this article, the W3C range (ChristopheD's code) isn't supported by IE6/7, so you'll have to do a browser check and use createTextRange for IE6/7.

As a small addition, maybe you could define a function to encapsulate the code written by ChristopheD and do something like <body onload="selectPs()"> or maybe $(document).ready(function() {}); if you use jQuery. May be more effective than placing the script at the end of the html code.

evilpenguin