Set an input's cursor position with Javascript
If you need to hijack an input's cursor position, you can use .setSelectionRange()
. This function takes two zero-based index arguments: a starting position and end position and makes makes a text-selection based on those start and end points. With this understanding, we can pass in the same index for both the start and end point to manually move the cursors position without making a selection. For example:
// move the cursor to the end of an input
inputElement.setSelectionRange(inputElement.value.length, inputElement.value.length)
//or move the cursor to a specific index
inputElement.setSelectionRange(3, 3)
//or make a selection with a different start/end
inputElement.setSelectionRange(3, 6)
Tweet