5

READ BEFORE MARKING DUPLICATE:

  1. The contenteditable div will not have child elements
  2. I do not want a cross-browser solution, only Chrome support required
  3. 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

Community
  • 1
  • 1
Gaurang Tandon
  • 6,504
  • 11
  • 47
  • 84
  • http://stackoverflow.com/a/4812022/96100 – Tim Down Jun 15 '14 at 13:58
  • @TimDown Interesting! I must have tried it, but before finding the `element.focus` [bug](http://stackoverflow.com/questions/24115860/set-caret-position-at-a-specific-position-in-contenteditable-div#comment37217865_24117242) I had. Feel free to close this as a duplicate :) I voted myself! – Gaurang Tandon Jun 15 '14 at 14:17

0 Answers0