views:

243

answers:

2

Hello guys,

A quick question: how do I programatically select the text fragment of the page in FireFox? For example, there's a paragraph of text, user clicks the button and symbols from 10-th to 15-th are selected as if user dragged a mouse in a regular way.

A: 

I'm not sure if there's a way to do it for arbitrary DOM elements like paragraphs, but for textarea elements, I believe you need to use the selectionStart and selectionEnd properties and specify where to start and end.

var textarea = document.getElementsByTagName('textarea')[0];
textarea.selectionStart = 10;
textarea.selectionEnd = 15;

Hope this helps!

jimbojw
+1  A: 

In Firefox, you can use the Range object, as specified by W3C.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">   
    <title>Range test</title>
    <style>   
        #trigger { background: lightgreen }
    </style>                 
  </head>                    
  <body>                     
    <p id="test">This is some (rather short) text.</p>
    <span id="trigger">→ Click here! ←</span>
      <!-- Yes, I know, ‘Click here!’ is an evil message -->
    <script>
var testCase = function () {
    var userSelection;

    if (window.getSelection) {  // W3C default
        userSelection = window.getSelection();
    }  // an extra branch would be necessary if you want to support IE

    var textNode = document.getElementById('test').firstChild;
    var theRange = document.createRange();

    // select 10th–15th character (counting starts at 0)
    theRange.setStart(textNode, 9);
    theRange.setEnd(textNode, 14);

    // set user selection    
    userSelection.addRange(theRange);
};

window.onload = function () {
    var el = document.getElementById('trigger');
    el.onclick = testCase;
};
    </script>
  </body>
</html>

Note that you have to get the TextNode to set the selection, which is the firstChild of the <p> element. Also note that this example will not work in IE, you have to use some proprietary methods. A nice introduction is on QuirksMode.

Marcel Korpel