Note: In year 2024, this solution still works for textarea/input.
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, Edge, Chrome, Safari, Firefox and Opera.
Interactive Example
How to set caret position
Type the number where you want to set the caret position and click on “Set Position” button.
How to set selection
Type the starting character number and end character number. Then click on “Set Selection” button to set selection.
How to get caret position or selection
Click on “Get Position/Selection”. If there is no selection (i.e. selection is collapsed), you will see only single value. This value represents current caret position. If there is a selection, you will see start and end position for selection.
Browser Caveats
Some browser considers new line character as single character whereas some browser handles new line character as two separate characters.
Fun Fact
This code is used by Twitter.
JavaScript Source Code
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. Other than that, the source code is self explanatory.
Leave a Reply