I\'m finding tons of good, crossbrowser anwers on how to SET the cursor or caret index position in a contentEditable
element, but none on how to GET or find its
window.getSelection - vs - document.selection
This one works for me:
function getCaretCharOffset(element) {
var caretOffset = 0;
if (window.getSelection) {
var range = window.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element);
preCaretRange.setEnd(range.endContainer, range.endOffset);
caretOffset = preCaretRange.toString().length;
}
else if (document.selection && document.selection.type != "Control") {
var textRange = document.selection.createRange();
var preCaretTextRange = document.body.createTextRange();
preCaretTextRange.moveToElementText(element);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
caretOffset = preCaretTextRange.text.length;
}
return caretOffset;
}
// Demo:
var elm = document.querySelector('[contenteditable]');
elm.addEventListener('click', printCaretPosition)
elm.addEventListener('keydown', printCaretPosition)
function printCaretPosition(){
console.log( getCaretCharOffset(elm), 'length:', this.textContent.trim().length )
}
some text here italic text here some other text here bold text here end of text
The calling line depends on event type, for key event use this:
getCaretCharOffsetInDiv(e.target) + ($(window.getSelection().getRangeAt(0).startContainer.parentNode).index());
for mouse event use this:
getCaretCharOffsetInDiv(e.target.parentElement) + ($(e.target).index())
on these two cases I take care for break lines by adding the target index