W3C home > Mailing lists > Public > whatwg@whatwg.org > August 2004

[whatwg] Standard method to get/set caret position

From: Ted Mielczarek <luser_whatwg@perilith.com>
Date: Thu, 26 Aug 2004 08:10:28 -0500
Message-ID: <20040826131028.GG17719@mavra.perilith.com>
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

This archive was generated by hypermail 2.4.0 : Wednesday, 22 January 2020 16:58:36 UTC