In the following example, I will create some basic functions to allow you to set where the cursor goes inside of a textarea or <input type=”text”>. Let’s dive right into the core JavaScript code that will leverage similar functions to a JavaScript array:
Using setSelectionRange and createTextRange
[code]
function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd(‘character’, selectionEnd);
range.moveStart(‘character’, selectionStart);
range.select();
}
}
function setCaretToPos (input, pos) {
setSelectionRange(input, pos, pos);
}
[/code]
To execute the code, it would be done as follows:
setCaretToPos(document.getElementById(“testinput”), 8);
So, assuming you have a textarea with the id of testinput created on your page, the cursor position will be set after the 8th character in the textarea. On occasion you may get errors like How to check for undefined in JavaScript so hopefully this will help.
Explaining moveEnd and moveStart
The above code could then be updated to use the equivalent getSelectionRange of the textarea when a user clicks a button, insert your code, then move the cursor to the end of the newly inserted code.
By using the setSelectionRange or the createTextRange, it will allow you to set the mouse cursor position of a form element item such as a textarea, input box, etc…