2

Suppose I've made my range so that it covers a word, using range.expand('word'). Typically to add the next word, I would write range.moveEnd('word', 1). But this seems not to work in Webkit. Perhaps it should be implemented differently?

Tim Down
  • 318,141
  • 75
  • 454
  • 536
tofutim
  • 22,664
  • 20
  • 87
  • 148

1 Answers1

3

You're talking about TextRanges, which are only fully implemented in IE. Other browsers use the DOM Level 2 Range objects instead, which while being vastly superior to TextRanges in most ways have no equivalent of text-based methods such as expand(). However, recent WebKit browsers do implement a version of expand() and both Webkit and Firefox 4 have the modify() method of the Selection object which provides similar functionality.

Example: http://jsfiddle.net/bzU22/1/

<script type="text/javascript">
    function expandSelection() {
        if (window.getSelection && window.getSelection().modify) {
            var sel = window.getSelection();
            sel.modify("extend", "forward", "word");
        } else if (document.selection && document.selection.type == "Text") {
            var range = document.selection.createRange();
            range.moveEnd("word", 1);
            range.select();
        }
        document.getElementById("test").focus();
    }
</script>

<input type="button" unselectable onclick="expandSelection();" value="Expand">
<p contenteditable="true" id="test">Hello, this is some test text.
    Select a word and then press the 'Expand' button.</p>
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Thanks Tim. I was using var range = document.caretRangeFromPoint(x,y) before. Is there an equivalent so that I can use sel.modify? – tofutim Jan 17 '11 at 05:43
  • Browsers have varying APIs for this. This question has more info: http://stackoverflow.com/questions/3189812/creating-a-collapsed-range-from-a-pixel-position-in-ff-webkit – Tim Down Jan 17 '11 at 09:39