Cross browser Javascript code to get/set caret position in textarea/input

By | December 27, 2005

Here is a working snippet of code to get and set the caret position in HTML textarea and textbox. This code works for IE 6, 7, 8, >=9, Firefox, Chrome, Safari and Opera. If you are looking for code snippet that works for content editable div or iframe with design mode = on, please contact me.

Fun Fact: This code is used by Twitter (as per their developer)

function getCaretPosition (ctrl) {
	// IE < 9 Support
	if (document.selection) {
		ctrl.focus();
		var range = document.selection.createRange();
		var rangelen = range.text.length;
		range.moveStart ('character', -ctrl.value.length);
		var start = range.text.length - rangelen;
		return {'start': start, 'end': start + rangelen };
	}
	// IE >=9 and other browsers
	else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
		return {'start': ctrl.selectionStart, 'end': ctrl.selectionEnd };
	} else {
		return {'start': 0, 'end': 0};
	}
}


function setCaretPosition(ctrl, start, end) {
	// IE >= 9 and other browsers
	if(ctrl.setSelectionRange)
	{
		ctrl.focus();
		ctrl.setSelectionRange(start, end);
	}
	// IE < 9
	else if (ctrl.createTextRange) {
		var range = ctrl.createTextRange();
		range.collapse(true);
		range.moveEnd('character', end);
		range.moveStart('character', start);
		range.select();
	}
}

Here “ctrl” is the Textarea object.

You can check it at Get/Set Caret in Textarea Example

83 thoughts on “Cross browser Javascript code to get/set caret position in textarea/input

  1. Susil Kumar Sethi

    Thanks a lot.
    Its worked for me Fine.

    Thanks
    Susil

  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 *