Answers for "get caret position javascript"

2

get caret position javascript

function getCaretCharacterOffsetWithin(element) {
    var caretOffset = 0;
    var doc = element.ownerDocument || element.document;
    var win = doc.defaultView || doc.parentWindow;
    var sel;
    if (typeof win.getSelection != "undefined") {
        sel = win.getSelection();
        if (sel.rangeCount > 0) {
            var range = win.getSelection().getRangeAt(0);
            var preCaretRange = range.cloneRange();
            preCaretRange.selectNodeContents(element);
            preCaretRange.setEnd(range.endContainer, range.endOffset);
            caretOffset = preCaretRange.toString().length;
        }
    } else if ( (sel = doc.selection) && sel.type != "Control") {
        var textRange = sel.createRange();
        var preCaretTextRange = doc.body.createTextRange();
        preCaretTextRange.moveToElementText(element);
        preCaretTextRange.setEndPoint("EndToEnd", textRange);
        caretOffset = preCaretTextRange.text.length;
    }
    return caretOffset;
}
Posted by: Guest on May-15-2020
1

get caret index js

function getCaretIndex(inputField) {
  const startPos = inputField.selectionStart;
  const endPos = inputField.selectionEnd;
  const dir = inputField.selectionDirection;

  if (startPos === endPos) {
    return startPos;
  }
  if (dir === "forward") {
    return endPos;
  } else {
    return startPos;
  }
}
Posted by: Guest on June-23-2020

Code answers related to "Javascript"

Browse Popular Code Answers by Language