Sometimes, we want to set the keyboard carte position of an HTML text box with JavaScript.
In this article, we’ll look at how to set the keyboard caret position of an HTML text box with JavaScript.
Use the HTML Element’s createTextRange, move and select Methods
We can use the createTextRange
method to create a selection, then we can move the cursor of the selection to the location we want.
For instance, if we have the following HTML:
<input>
Then we can write the following JavaScript code to move the cursor.
For instance, we can write:
const setCaretPosition = (elem, caretPos) => {
if (elem !== null) {
if (elem.createTextRange) {
const range = elem.createTextRange();
range.move('character', caretPos);
range.select();
} else {
if (elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
} else
elem.focus();
}
}
}
const input = document.querySelector('input')
input.value = 'hello world'
setCaretPosition(input, 10)
We create the setCaretPosition
function with the elem
and caretPos
parameters.
elem
is the input element that we want to move the cursor of.
caretPos
is the position of the cursor starting from 0 for the first position.
We check if elem
isn’t null
with the if
statement.
If it’s not null
, then we can check if the createTextRange
method exists.
If it does, then we call it to create the range
object.
Next, we call move
with 'character'
and caretPos
to move the cursor.
Then we call select
to apply the move.
Otherwise, we can also use focus
method to focus on the input.
Then we call setSelectionRange
to move to the position given by caretPos
.
Then if we set a value
of the input that’s longer than caretPos
, then we can call setCaretPosition
to move the cursor to where we want.
Conclusion
We can set the keyboard caret position of an input by creating a selection and setting the end position of the cursor with the selection range object.