showing results for - "get caret position javascript"
Lilly
25 Jun 2020
1function getCaretCharacterOffsetWithin(element) {
2    var caretOffset = 0;
3    var doc = element.ownerDocument || element.document;
4    var win = doc.defaultView || doc.parentWindow;
5    var sel;
6    if (typeof win.getSelection != "undefined") {
7        sel = win.getSelection();
8        if (sel.rangeCount > 0) {
9            var range = win.getSelection().getRangeAt(0);
10            var preCaretRange = range.cloneRange();
11            preCaretRange.selectNodeContents(element);
12            preCaretRange.setEnd(range.endContainer, range.endOffset);
13            caretOffset = preCaretRange.toString().length;
14        }
15    } else if ( (sel = doc.selection) && sel.type != "Control") {
16        var textRange = sel.createRange();
17        var preCaretTextRange = doc.body.createTextRange();
18        preCaretTextRange.moveToElementText(element);
19        preCaretTextRange.setEndPoint("EndToEnd", textRange);
20        caretOffset = preCaretTextRange.text.length;
21    }
22    return caretOffset;
23}
Emil
18 Jul 2018
1function getCaretIndex(inputField) {
2  const startPos = inputField.selectionStart;
3  const endPos = inputField.selectionEnd;
4  const dir = inputField.selectionDirection;
5
6  if (startPos === endPos) {
7    return startPos;
8  }
9  if (dir === "forward") {
10    return endPos;
11  } else {
12    return startPos;
13  }
14}