Problem on "Finding cursor position" function

Posted by sanceray3 on Stack Overflow See other posts from Stack Overflow or by sanceray3
Published on 2010-03-14T20:09:29Z Indexed on 2010/03/14 20:15 UTC
Read the original article Hit count: 386

Hi all,

Few days ago, I have found a solution to obtain the cursor position on a div with contentedit="true". I use the solution defined on this web site : Finding cursor position in a contenteditable div

      function getCursorPos() {
        var cursorPos;
        if (window.getSelection) {
            var selObj = window.getSelection();
            var selRange = selObj.getRangeAt(0);       
            cursorPos =  findNode(selObj.anchorNode.parentNode.childNodes, selObj.anchorNode) + selObj.anchorOffset;
        /* FIXME the following works wrong in Opera when the document is longer than 32767 chars */
        }

        else if (document.selection) {
            var range = document.selection.createRange();
            var bookmark = range.getBookmark();
            /* FIXME the following works wrong when the document is longer than 65535 chars */
            cursorPos = bookmark.charCodeAt(2) - 11; /* Undocumented function [3] */
        }
        return cursorPos;
    }

function findNode(list, node) {
    for (var i = 0; i < list.length; i++) {
        if (list[i] == node) {            
            return i;
        }
    }
    return -1;
}

It functions well, but when I use html tags inside the div the pointer doesnt show the correct position. For example if I try to find cursor position on the <strong>cat</strong> is black, the function doesn't return me the good position.

But if I try on the cat is black, it functions.

Any ideas how to get the position with html tags ?

Thanks for your help.

© Stack Overflow or respective owner

Related posts about div

Related posts about contenteditable