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!