Javascript : Getting and Setting Caret Position in Textarea
function doGetCaretPosition (ctrl) {
var CaretPos = 0; // IE Support
if (document.selection) {
ctrl.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;
return (CaretPos);
}
function setCaretPosition(ctrl, pos){
if(ctrl.setSelectionRange)
{
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
Here “ctrl” is the Textarea object. This script works well with Internet Explorer, Firefox and Opera.
You can check it at Get/Set Caret in Textarea Example
Categories: Javascript

Thanks a lot , it worked for me.
Thanks\
vijith
Thanks a lot. Very very helpful to me. You saved my huge time, thanks a lot again and again.
“me too”. I see tinyMce uses this kind of function and I was looking to replicate the behaviour in other input fields.