Using setSelectionRange and createTextRange
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);
}
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…
Published on Feb 14, 2019
Tags: JavaScript
| setSelectionRange
| createTextRange