Friday, 31 March, 2023 UTC


Summary

Tip of the day: for any HTML Input Element, we have access to a setSelectionRange() method that controls where the cursor is placed in that element, and also what text is selected.
The setSelectionRange() takes a starting position parameter and the ending position. Both are zero indexed.
For example:
input.focus()
// select the first 6 chars from the input
input.setSelectionRange(0, 6)
Note that in order to see the setSelectionRange() working, you first need to focus the input element!
If these 2 parameters are equal then it will just place the cursor/caret at that position:
//move the cursor to a specific index 
input.setSelectionRange(2, 2)

// move the cursor at the end of an input
const {length} = inputElement.value
inputElement.setSelectionRange(length, length)
So, it's very easy to select and change just some parts of the text from a html input:
The below Javascript code does this:
const input = document.getElementById("my-input")

function renameFile() {
  input.focus()
  const dotIndex = input.value.lastIndexOf('.')
  input.setSelectionRange(0, dotIndex)
}

function changeFileExtension() {
  input.focus()
  const {value} = input
  const dotIndex = value.lastIndexOf('.')
  input.setSelectionRange(dotIndex + 1, value.length)
}
You can see here the full working codepen here.
By the way, speaking of cursor/caret in an HTML input you can also set its color with the CSS caret-color property.
The post Select text or set the cursor in a HTML input with Javascript appeared first on Js Craft.