Re: Javascript API to find caret (insertion point) position in the document.

  •  08-13-2007, 10:19 AM

    Re: Javascript API to find caret (insertion point) position in the document.

    Try this:
    <SCRIPT LANGUAGE=JAVASCRIPT>
    function getCursorPos(textElement){
     var cursorPos = -1;
     if (textElement && textElement.createTextRange) {
      var range = document.selection.createRange().duplicate();
      range.setEndPoint('StartToEnd',range);
      var start = document.body.createTextRange();
      start.moveToElementText(textElement);
      cursorPos = calcBookmark(range.getBookmark())-calcBookmark(start.getBookmark());
      var rLen = 0;
      do{
       var BrLen = rLen;
       rLen = newLine(textElement.value.substring(0,cursorPos + rLen + 1));
      }while(BrLen!=rLen);
      cursorPos += rLen;
     }
     return cursorPos;
    }
    function calcBookmark(bk){
     return (bk.charCodeAt(0)-1)+(bk.charCodeAt(3)-1)*65536+(bk.charCodeAt(2)-1);
    }
    </SCRIPT>
    <SCRIPT LANGUAGE=VBSCRIPT>
    option explicit
    function newLine(str)
     dim nl, r
     set nl = new RegExp
     nl.global = true
     nl.pattern = "\r\n"
     set r = nl.Execute(str)
      newLine = r.count
     set r = nothing
     set nl = nothing
    end function
    </SCRIPT>
    If you rather like to use pure javascript, replace the newLine function with a split('\n');
    Filed under:
View Complete Thread