> I'm trying to find out where the user has placed the cursor within a
> textfield. Position means the number of characters of the text in the
> textfield. Must only work in ie5. Please help!
The inner working of the textfield and textarea objects are hidden from us
mere mortals. All text selection, insertion and deletion is handled by a
TextRange object on the assumption that a single document can only have a
single selection active at any one time.
To my knowledge there is NO simple elegant method for getting the caretPOS
through any object or object method.
this is however a dirty workaround that i built to solve this exact
problem that gets the same result, (and results are all we are worried
about).
Solution Theory
We can insert text at the caretPOS using a TextRange object
so insert a charactor/substring of our chosing.
then search the object.value for the index of the charactor/substring to
get the position.
Solution Code
function ReturnCaretPOS() {
// copy current value
var txt = myobject.value;
// create textrange
myobject.caretPos = document.selection.createRange().duplicate();
// insert my char
myobject.caretPos.text = "|";
// find index of my char
var i = myobject.value.indexOf("|");
// return old value string
myobject.value = txt;
// return i as the caretPOS
return i;
}
Solution Notes
- this works for both textfield and textarea objects.
- does not return x,y position in textarea objects (thats a different
problem altogether).
- on slower machines you may actually see the | be inserted then deleted
which may be confusing, so be careful (i did say it was a dirty method)
- choose your marking charactor with care, look at the application and use
something which is unlikely to be typed by the user (try an untypeable
charactor with String.charcodeFrom();
If anyone has a better solution, I'm all ears.
Trevor