0

I have the following function that tracks the cursor position in an editable div:

  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-1;
    }

The issue is that if my editable div has the following html:

hello <span contenteditable='false'>Abderrahmane Benbachir</span>  

and I put the cursor next to the span, it starts counting the cursor from 0. Why is this? How do I fix this?

adit
  • 32,574
  • 72
  • 229
  • 373

1 Answers1

0

In this case, to get the caret position use this Tim Down's code instead. Which also has restoreSelection function in it which restores the caret position.

I asked the same question recently, which you can check here.

Community
  • 1
  • 1
Mr_Green
  • 40,727
  • 45
  • 159
  • 271
  • I don't understand how that code is supposed to help that problem. That Tim Down's code doesn't have a solution/function for finding the caret position.. please elaborate – adit May 17 '13 at 07:33
  • Are you also saying that I'd have to call restoreSelection ? – adit May 17 '13 at 07:34
  • @adit yes. The code which I provided has a function called `restoreSelection`. use that. (I am average in english so please ask again if you can't understand). – Mr_Green May 17 '13 at 07:36
  • thanks for helping out. In my case what should I pass into the restoreSelection function? – adit May 17 '13 at 07:38
  • Sorry, `_savedSel = saveSelection(this);` where `this` is the reference of editable div. – Mr_Green May 17 '13 at 07:51
  • @adit saveSelection is another function in the same provided code. – Mr_Green May 17 '13 at 07:52