Search code examples
javascriptwebkitrangetextrange

In Webkit, how do I add another word to the range?


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?


Solution

  • 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>