Search code examples
javascriptrangy

Select next N words using Rangy


I can select next one word using Rangy like so:

$(function () {
    $("#select-next-one-word").click(function () {
        var selection = rangy.getSelection();
        selection.expand("word", {
            wordOptions: {
                includeTrailingSpace: true
            }
        });

        selection.collapseToEnd();
        selection.expand("word");
    });
});

JsFiddle demo

But how can I extend the selection to next N words?


Solution

  • I'd suggest obtaining a range from the selection, expanding it to encompass whole words, collapse it to the end, moving the whole range again two words forward and then moving the start of the range back two words using moveStart(). A little convoluted but achieves the desired result as I understand it.

    Demo: http://jsfiddle.net/u4337/81/

    Code:

    var selection = rangy.getSelection();
    var range = selection.getRangeAt(0);
    
    // Expand to whole words and collapse
    range.expand("word", {
        wordOptions: {
            includeTrailingSpace: true
        }
    });
    
    range.collapse(false);
    
    // Move the whole range two words ahead
    range.move("word", 2);
    
    // Move the start two words back
    range.moveStart("word", -2);
    
    // Re-select the range
    selection.setSingleRange(range);