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

How could I insert text, tabs and line breaks at the caret position using an on website keyboard?
Thanks for this. I’m struggling with it a bit. I’ve got the added complexity that I need to setCaretPosition in a different frame. The application is that by clicking on a text box in Frame A causes a page to load in Frame B but then I need the caret to stay in the same place in Frame A. Firefox seems to be smart enough to do this without any code but I can’t get it to work in IE. What I’ve tried is getting the position in Frame A and passing both it and the ID name of the field that I need the caret positioned in. Then in FRAME B’s script I tried onLoad=setCaretPosition(ID,pos) setting the ctrl name as: var ctrl = parent.frames['frame_A_name'].document.getElementById(ID); in setCaretPos(). I’ve verified that the ID and pos is passing correctly but doesn’t seem to be generating the right element id or something as the caret never appears. Frames always mess me up. Thanks for any help
thank“s a lot
That’s great.
Wonderfull, Thanks
Great script, just what I need. Any thought on how to return the start and end position if a series of characters is selected?
This is one of the most useful scripts I’ve ever found. Thanks a million for keeping this hosted. It was a life saver!