Search code examples
javascriptdomrangy

Rangy - restore cursor position when replacing innerHTML


I am using Rangy to select and restore the cursor position.

It does an excellent job but it has not been designed for when user input is manipulated programmatically and a shorter string is replaced in the innerHTML of the DIV.

I created an example on jsbin showing what happens when user types a space at the end of the selection and the space is stripped out programmatically: http://jsbin.com/ebeqoj/4/edit

The replaced innerHTML is shorter than the one Rangy tries to restore so it fails and the DIV loses focus.

I would appreciate suggestions on how to handle this. For example, is there a way to instruct Rangy to restore the cursor at the end of the new string? (I have tried using rangy.getSelection().move("character", userInput2.length-1)without success)

Thanks


Solution

  • Putting the caret at the end of the contents of the <div> is quite easy:

    var sel = rangy.getSelection();
    sel.selectAllChildren(el);
    sel.collapseToEnd();
    

    For the more general case, you can create a range that encompasses the content from the start of the <div> to the caret position, get its text using the text() method of Rangy ranges, remove white space from that text and measure its length. Demo:

    http://jsbin.com/ebeqoj/5/edit