Friday, May 1, 2009

Use JavaScript to get the position of the caret in a Text Box

If you have an <input type=”text” /> on your web page and that element currently is in focus, you can use this cross-browser function to retrieve the current position of the caret/cursor:

function GetCaret(input)
{
if(document.selection)
{
var range = document.selection.createRange().duplicate();
//moveStart returns the # of characters moved.
return -range.moveStart("character", -input.value.length);
}
else if(input.selectionStart)
return input.selectionStart;
return -1;
}



Internet Explorer doesn't support the selectionStart property used by FireFox (I've heard Opera uses selectionStart and I believe Safari does as well) so instead we get the currently selected range via document.selection, use the selection object's createRange method to create a TextRange object which is what IE uses to manipulate text data. There doesn't seem to be a direct way to get the position of the TextRange within the parent object, but we can use the moveStart method to move the start point of the range. This method returns the number of characters moved, which happens to be the position of the caret - technically the negative of the position of the caret since you had to move the selection backwards to reach the start.



This method could easily be modified to get the ending position of the selection by using range.text in IE to retrieve the text selected (range.text.length would be the length of text selected) or use input.selectionEnd in other browsers.