READ BEFORE MARKING DUPLICATE:
- The contenteditable div will not have child elements
- I do not want a cross-browser solution, only Chrome support required
- Only vanilla JS, no libraries.
I have looked up almost all the posts on Stackoverflow (would be quite surprising for me if this post turns out to be a duplicate), and found this fiddle: http://jsfiddle.net/cpatik/3QAeC/
Its getSelectionBegin
code was:
function getSelectionBegin(element) {
var caretOffset = 0;
if (w3) {
}
else if (ie) {
var textRange = document.selection.createRange();
var preCaretTextRange = document.body.createTextRange();
preCaretTextRange.moveToElementText(element);
preCaretTextRange.setEndPoint("EndToStart", textRange);
caretOffset = preCaretTextRange.text.length;
}
return caretOffset;
}
Notice the w3
part (which I require) is blank. Seemed to me like there's no method for getting selectionStart, but I assume someone might have developed a hack to get round this.
So the question:
How do I get the
selection start
in a content editable div ?
UPDATE:
As it turns out, there was a solution, but apparently missed by me due to the bug I had before