[whatwg] Standard method to get/set caret position

While working on a javscript tool, I needed a way to get and set the 
caret position in a textbox.  This is the code I wound up using, with 
branches for Mozilla and IE, and fallback behavior (that only somewhat 
works) for other browsers.  In both of these functions 'inp' is a 
HTMLElement of <input type="text">.

function getcaretpos(inp)
{
    // for mozilla
    if(inp.selectionEnd)
      return inp.selectionEnd;

    // for IE
    if(inp.createTextRange)
    {
      var docrange = document.selection.createRange();
      var inprange = inp.createTextRange();
      inprange.setEndPoint('EndToStart', docrange);
      return inprange.text.length;
    }

    return inp.value.length; // other browsers don't provide a method 
that I know of
}

function setselectionto(inp,pos)
{
    // for mozilla
    if(inp.selectionStart) {
      inp.selectionStart = inp.selectionEnd = pos;
    }
    // for IE
    else if(inp.createTextRange) {
      var docrange = document.selection.createRange();
      var inprange = inp.createTextRange();
      inprange.move('character',pos);
      inprange.select();
    }
    // other browsers don't have a method that I know of
}

Some standard way of getting/setting this information would be useful.  
As it stands, this code will only work in Mozilla/IE, and with different 
codepaths for each.

-Ted

Received on Thursday, 26 August 2004 06:10:28 UTC