Javascript : Getting and Setting Caret Position in Textarea

By | December 27, 2005
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){
	else if (ctrl.createTextRange) {
		var range = ctrl.createTextRange();
		range.moveEnd('character', pos);
		range.moveStart('character', pos);;

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

83 thoughts on “Javascript : Getting and Setting Caret Position in Textarea

  1. Susil Kumar Sethi

    Thanks a lot.
    Its worked for me Fine.


  2. Abhay Mishra

    how do i get cursor position when i am using text-angular directive.Any help would be highly obliged.

Leave a Reply

Your email address will not be published. Required fields are marked *