0

I tried the code from the following stackoverflow:

Get caret (cursor) position in contentEditable area containing HTML content

but I wanted to do it onKeyDown instead of onKeyUp (so it seems faster to the user), but chrome seems to mess up the offsets that it is returning. Could someone explain this behavior?

http://jsfiddle.net/2avyumpn/

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;
}

function showCaretPos() {
var el = document.getElementById("test");
var caretPosEl = document.getElementById("caretPos");
caretPosEl.innerHTML = "Caret position: " + getCaretCharacterOffsetWithin(el);
}

document.body.onkeydown = showCaretPos;
document.body.onmousedown = showCaretPos;

To reproduce, just click before the first letter and press the (right) key on the keyboard to go to the 1st element, but it stays on 0 for some reason. Is this a bug?

Community
  • 1
  • 1
rkrishnan2012
  • 368
  • 1
  • 2
  • 13

0 Answers0