0

I'm using this code right now to find the caret position

getCaretCharacterOffsetWithin(element) {
    let caretOffset = 0;
    let doc = element.ownerDocument || element.document;
    let win = doc.defaultView || doc.parentWindow;
    let sel;
    if (typeof win.getSelection != "undefined") {
      sel = win.getSelection();
      if (sel.rangeCount > 0) {
        let range = this.window.getSelection().getRangeAt(0);
        let selected = range.toString().length; // *
        let preCaretRange = range.cloneRange();
        preCaretRange.selectNodeContents(element);
        preCaretRange.setEnd(range.endContainer, range.endOffset);
        caretOffset = preCaretRange.toString().length - selected; // *
      }
    } else if ((sel = doc.selection) && sel.type != "Control") {
      let textRange = sel.createRange();
      let preCaretTextRange = doc.body.createTextRange();
      preCaretTextRange.moveToElementText(element);
      preCaretTextRange.setEndPoint("EndToEnd", textRange);
      caretOffset = preCaretTextRange.text.length;
    }
    return caretOffset;
  }

which works if my text is on one line, but if I press enter and move to a new line with text like this;

test1 test2 test3 test4 test5 test6 test7 test8 test9 test10
test11 test12 test13 testy14 test15 @x| test16 test17 test18 test19 test20

where | is my caret position, the index is wrong by a few digits, here when it should be 100 I get the value 105.

Any changes I can make to this function to make it work? I have an alternate function that inserts a special character at the caret, finds its index and then removes it, but that also gives almost the same result.

flyingfox
  • 13,414
  • 3
  • 24
  • 39
Steve Chacko
  • 95
  • 11

0 Answers0