In mozilla, one can use "textarea.selectionStart" to retrieve the caret position by Javascript.
But what is the case of IE? I've seen
a method that sets end point of a
dummy range to document.selection.createRange() object, but it is not working for me.
Another method
uses for-loop repeatedly to test the end point of these two range objects, which seems to be naive.
Here I propose a simple but a-little-dirty method to retrieve caret position in textarea for IE.
Following is the code:
function caret(node) {
//node.focus();
/* without node.focus() IE will returns -1 when focus is not on node */
if(node.selectionStart) return node.selectionStart;
else if(!document.selection) return 0;
var c = "\001";
var sel = document.selection.createRange();
var dul = sel.duplicate();
var len = 0;
dul.moveToElementText(node);
sel.text = c;
len = (dul.text.indexOf(c));
sel.moveStart('character',-1);
sel.text = "";
return len;
}
It simply inserts a dummy character in caret position and removes it after obtaining its position in textarea. Isn't it simple?