3

Possible Duplicate: Get caret position in contentEditable div

I have a contenteditable div and I am trying to get the caret position inside this div on non IE browsers using the following code:

  var caretPosition = 0, containerEl = null, sel, range;
  if (window.getSelection) 
  {
    sel = window.getSelection();
    if (sel.rangeCount) {
        range = sel.getRangeAt(0);
        if (range.commonAncestorContainer.parentNode == editableDiv) {
            caretPosition = range.endOffset;
         }
      }
   }

It returns the caret position correctly for text on a single line, but I have multiple lines of text and it seems that for each new line the caret position for each line begins with 0. My problem is that I need the caret position to include the number of characters found on previous lines, for example, for the second line the

caretPosition = number of characters on first line + no of characters in front of the caret on the second line.

It returns only the no of characters in front of the caret on the second line. How can I achieve this behaviour? Or how can I have another range that includes the text found on the lines above?

Any advice much appreciated, thanks!

Community
  • 1
  • 1
Crista23
  • 3,203
  • 9
  • 47
  • 60
  • Since this isn't going to be reopened :-(: You must do this calculation yourself by iterating over all previous siblings of the current DOM node. This is because `range` has no idea that a feature "contentEditable" even exists - range always only knows about the DOM nodes it spans. – Aaron Digulla Jan 31 '13 at 08:26
  • 1
    Thank you for your suggestion. Hopefully I found another post here on SO that seems to have solved my problem: http://stackoverflow.com/questions/4811822/get-a-ranges-start-and-end-offsets-relative-to-its-parent-container – Crista23 Jan 31 '13 at 14:03

0 Answers0