Does anybody know how to move the keyboard caret in a textbox to a particular position?
For example, if a text-box (e.g. input element, not text-area) has 50 characters in it and I want to position the caret before character 20, how would I go about it?
This is in differentiation from this question: jQuery Set Cursor Position in Text Area , which requires jQuery.
Excerpted from Josh Stodola's Setting keyboard caret Position in a Textbox or TextArea with Javascript
A generic function that will allow you to insert the caret at any position of a textbox or textarea that you wish:
function setCaretPosition(elemId, caretPos) {
var elem = document.getElementById(elemId);
if(elem != null) {
if(elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
}
else {
if(elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
}
else
elem.focus();
}
}
}
The first expected parameter is the ID of the element you wish to insert the keyboard caret on. If the element is unable to be found, nothing will happen (obviously). The second parameter is the caret positon index. Zero will put the keyboard caret at the beginning. If you pass a number larger than the number of characters in the elements value, it will put the keyboard caret at the end.
Tested on IE6 and up, Firefox 2, Opera 8, Netscape 9, SeaMonkey, and Safari. Unfortunately on Safari it does not work in combination with the onfocus event).
An example of using the above function to force the keyboard caret to jump to the end of all textareas on the page when they receive focus:
function addLoadEvent(func) {
if(typeof window.onload != 'function') {
window.onload = func;
}
else {
if(func) {
var oldLoad = window.onload;
window.onload = function() {
if(oldLoad)
oldLoad();
func();
}
}
}
}
// The setCaretPosition function belongs right here!
function setTextAreasOnFocus() {
/***
* This function will force the keyboard caret to be positioned
* at the end of all textareas when they receive focus.
*/
var textAreas = document.getElementsByTagName('textarea');
for(var i = 0; i < textAreas.length; i++) {
textAreas[i].onfocus = function() {
setCaretPosition(this.id, this.value.length);
}
}
textAreas = null;
}
addLoadEvent(setTextAreasOnFocus);