Home > Javascript > Javascript : Getting and Setting Caret Position in Textarea

Javascript : Getting and Setting Caret Position in Textarea

December 27th, 2005 Leave a comment Go to comments
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 Tags:
  1. April 9th, 2011 at 20:27 | #1

    How could I insert text, tabs and line breaks at the caret position using an on website keyboard?

  2. Steve
    May 21st, 2011 at 02:36 | #2

    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

  3. Peter
    May 24th, 2011 at 18:30 | #3

    thank“s a lot

  4. David
    July 5th, 2011 at 04:57 | #4

    That’s great.

  5. July 8th, 2011 at 01:15 | #5

    Wonderfull, Thanks

  6. Dan
    September 2nd, 2011 at 04:35 | #6

    Great script, just what I need. Any thought on how to return the start and end position if a series of characters is selected?

  7. Ben
    December 5th, 2011 at 10:25 | #7

    This is one of the most useful scripts I’ve ever found. Thanks a million for keeping this hosted. It was a life saver!

Comment pages
1 ... 4 5 6 10
  1. July 8th, 2010 at 03:24 | #1