Once again, IE proves that it can't do anything in a standard way.
Retrieving the caret position from a text control in Firefox and Opera is a very simple job - you simply use the selectionStart and selectionEnd parameters of the control itself.
Retrieving the caret position from a text control in IE is not quite so simple. There are no parameters that give you this information, so you have to work it out for yourself. As it happens, there are a number of ways of doing this available on the internet. Unfortunatly, none of them work properly.
The "official" method of doing it according to the Microsoft Web Team in the article
Yule Not Want to Miss this One (See "O Cursor, Where Art Thou—finding yourself in a text box") is just horrible:
- Save the input field value in a temporary variable.
- Create a TextRange object on the document.selection (assuming the input field is focused).
- Insert a “~” character into that TextRange object (range.text = "~"). Thus, the tilde would be inserted at the caret position (which we actually want to determine).
- Search for the “~” character in the input field value and remember the index where it was found.
Restore the original input field value, saved at (1). - Return the index determined at (4) and claim it is the caret position.
The better method of doing it uses undocumented features of the Range object, and is
described here by Mishoo.
This uses the Range.getBookmark() function which returns a value that can be used to get to the caret position. It worked fine. And in IE7 it stopped working. Microsoft changed the way this function worked (It's undocumented and so they can do that) and broke things that rely on it.
The third method of working out the caret position, which I have not seen mentioned anywhere on the internet and so might very well not work properly, is to use the Range.offsetLeft value. This gives you a value which represents the distance from the start of the text field that the caret is located at. In standard mode, this value is (position * 7) + 1.
This has been tested in IE5, IE5.5, IE6 and IE7 and returns the same values across all of them. It also returns the same value regardless of the zoom of the page and the location of the textbox on the screen.
As such, below is my cross-browser function to get the caret position from a given text field. It is known to work in Firefox, Opera, Netscape and (now) all versions of IE from 5.5 and up.