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

By | December 27, 2005 | 84 Comments
Category: Javascript

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
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);; } }[/code] Here "ctrl" is the Textarea object. You can check it at Get/Set Caret in Textarea Example

About Vishal Monpara

Vishal Monpara is a full stack Solution Developer/Architect with 13 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 leveraging geographically dispersed team members.

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

  1. Abhay Mishra

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

  2. Susil Kumar Sethi

    Thanks a lot.
    Its worked for me Fine.


Leave a Reply

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