Search code examples
javascriptrangeselectioncontenteditablerangy

Move to the end one character with rangy


I have a contenteditable div, I want to move the range just one character after the current one.

I currently want to check if the character after caret is a certain character, and if it is then place caret after it

I use this code but it don't work

 placeCaretAfterHiddenCharacter:function(containerEl,afterCharacters) {
    var afterChar = "", sel, range, afterRange,rangeHtml;
    sel = rangy.getSelection();
    if (sel.rangeCount > 0) {
        range = sel.getRangeAt(0).cloneRange();
        var endRange = rangy.createRange();
        endRange.selectNodeContents(containerEl);
        endRange.collapse(false);

        range.setEnd(containerEl, endRange.endOffset);

        var div = this.cloneSelectionInDiv(range);
        //to get string as html as range removes the html and returns the text only
        rangeHtml = div.innerHTML;
        afterChar = rangeHtml.slice(afterCharacters-1);

        if(/[\u200B\u200C\u200D\uFEFF\u2028\u2029]/g.test(afterChar)) {
            range.setStartAfter(range.startContainer,range.startOffset);
            range.collapse(true);
            sel.addRange(range);
        }

    }
},

the afterChar gets set right but the caret does not move.

how can this be done ?


Solution

  • You could use Rangy 1.3's TextRange module. For example, to move the caret one character forwards, you could do the following:

    rangy.getSelection().move("character", 1);