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

Vishal Monpara is a full stack Solution Developer/Architect with 12 years of experience primarily using Microsoft stack. He is currently working in Retail industry and moving 1’s and 0’s from geographically dispersed hard disks to geographically dispersed user’s mind leveraging geographically dispersed team members.

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 *