Get Caret Position

Get Cursor position respective to the editable DIV element.

by sauravmishra

HTML

<div id="test" class="ddTagged" contenteditable="true" style="-webkit-user-select:text;"><b><i>Hello,</i></b> I am <b>DIV</b> and <i>free</i> text section 1</div>
<br>
<div id="test" class="ddTagged" contenteditable="true" style="-webkit-user-select:text;">Hello, I am <b>DIV 2</b> and free text section 2</div>
<div id="caretPos"></div>

JavaScript

/*
style="-webkit-user-select:text;" is needed for iPad

*/
function getCaretPosition() {
  if (window.getSelection && window.getSelection().getRangeAt) {
    var range = window.getSelection().getRangeAt(0);
    var selectedObj = window.getSelection();
    var rangeCount = 0;
    var childNodes = selectedObj.anchorNode.parentNode.childNodes;
    for (var i = 0; i < childNodes.length; i++) {
      if (childNodes[i] == selectedObj.anchorNode) {
        break;
      }
      if (childNodes[i].outerHTML || childNodes[i].nodeType == 3)
        rangeCount += childNodes[i].textContent.length;
				/* globalRange += 1; */
				/* console.log('childNodes[i].textContent.length: ', childNodes[i].textContent.length);
				console.log('rangeCount: ', rangeCount); */
    }
    return range.startOffset + rangeCount; // range.startOffset
		// console.log('globalRange: ', globalRange);
		// return globalRange;
  }
  return -1;
}

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

document.body.onkeyup = showCaretPos;
document.body.onmouseup = showCaretPos;