Positioning Keyboard Caret in HTML Textboxes
To move the keyboard caret within a textbox, a specific position can be targeted using JavaScript.
Generic Function:
function setCaretPosition(elemId, caretPos) { var elem = document.getElementById(elemId); if (elem) { if (elem.createTextRange) { // IE specific var range = elem.createTextRange(); range.move('character', caretPos); range.select(); } else if (elem.selectionStart) { elem.focus(); elem.setSelectionRange(caretPos, caretPos); } else { elem.focus(); // Fallback for browsers not supporting setSelectionRange } } }
Usage:
Example:
To set the caret before character 20 in a textbox with 50 characters:
setCaretPosition('myTextbox', 20);
Compatibility:
Additional Notes:
You can also force the caret to jump to the end of all textareas on page focus using this code (within the addLoadEvent function):
for (var i = 0; i < textAreas.length; i++) { textAreas[i].onfocus = function() { setCaretPosition(this.id, this.value.length); } }
The above is the detailed content of How Can I Programmatically Position the Cursor in an HTML Textbox?. For more information, please follow other related articles on the PHP Chinese website!