I am working with a contenteditable div that will have the option to have inline html elements such as tags in the text flow.
At certain points I need to grab the caret position but have found that with the example code the position returned is incorrect if the caret is after an html child element.
I need a cross browser solution that will allow me to store the position of the caret so that it can be restored a split second later even with the presence of html elements in the text flow.
Example:
function getCaretPosition(editableDiv) {
var caretPos = 0, containerEl = null, sel, range;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
if (range.commonAncestorContainer.parentNode == editableDiv) {
caretPos = range.endOffset;
}
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
if (range.parentElement() == editableDiv) {
var tempEl = document.createElement("span");
editableDiv.insertBefore(tempEl, editableDiv.firstChild);
var tempRange = range.duplicate();
tempRange.moveToElementText(tempEl);
tempRange.setEndPoint("EndToEnd", range);
caretPos = tempRange.text.length;
}
}
return caretPos;
}
$('div').keyup(function(){
alert(getCaretPosition(this));
});
div{width:300px; height:100px; border:solid 1px #DDD;}
div a{background:#333; color:#FFF;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<div contenteditable=true>
some example text <a>anchor tag</a>
</div>
Original JSFiddle: http://jsfiddle.net/wPYMR/2/