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. March 21st, 2013 at 00:25 | #1

    Thanks a lot , it worked for me.

    Thanks\
    vijith

  2. Lekhnath Rijal
    March 21st, 2013 at 22:40 | #2

    Thanks a lot. Very very helpful to me. You saved my huge time, thanks a lot again and again.

  3. March 24th, 2013 at 23:28 | #3

    “me too”. I see tinyMce uses this kind of function and I was looking to replicate the behaviour in other input fields.

Comment pages
1 ... 6 7 8 10
  1. July 8th, 2010 at 03:24 | #1
  2. May 28th, 2012 at 18:31 | #2