Search code examples
javascriptrangy

Manipulate selection with rangy


I'm trying to use rangy to manipulate the selection. My ultimate goal is to select a chunk of text of known length to the immediate left of the caret, but first I'd like to understand the tools.

Here's my sample test page

<html>
<head>
  <title>TextRange Demo</title>
  <script type="text/javascript" src="../lib/rangy-core.js"></script>
  <script type="text/javascript" src="../lib/rangy-classapplier.js"></script>
  <script type="text/javascript" src="../lib/rangy-textrange.js"></script>

  <script type="text/javascript">
    window.onload = function() {
      rangy.init();
    };
    function SelectStuff(){
      var r = rangy.getSelection().getRangeAt(0);
      r.moveEnd("character", 4);
    }
  </script>
</head>

<body>
  <div id="content">
  <div unselectable="on" onclick="SelectStuff()">SelectStuff</div>
  <div contenteditable="true" style="border: solid thin blue;">
    The quick brown fox jumps over the lazy dog.
  </div>
  </div>
</body>
</html>

I expected this to select four characters to the right of the cursor when I place the cursor in the editable div and then click on SelectStuff. It doesn't, which means I haven't understood how to use this.

Could someone clue me in please? The use of moveStart and moveEnd methods is not demonstrated in the supplied samples.


Solution

  • Never mind, I found a sample for the Internet Explorer native TextRange and they work the same. The range was in fact changing, but to see the change you need to follow up with r.select();