Home > Software design >  Scroll to the caret position of an html input
Scroll to the caret position of an html input

Time:03-27

function sel() {
  document.getElementById('testid').focus();
  document.getElementById('testid').setSelectionRange(10, 10);
}
<input style="width:50px" id="testid" value="abcdefghijklmnopqrst">
<button onclick="sel()">select 10,10</button>

input.setSelectionRange(10,10) not scrolling the value to the caret position for the first time. Is it feasible to scroll to the caret?

CodePudding user response:

Swap them

function sel() {
  document.getElementById('testid').setSelectionRange(10, 10);
  document.getElementById('testid').focus();
}
<input style="width:50px" id="testid" value="abcdefghijklmnopqrst">
<button onclick="sel()">select 10,10</button>

The above works in my Chrome. You many need a timeout if it does not work for you

function sel() {
  document.getElementById('testid').setSelectionRange(10, 10);
  setTimeout(() => document.getElementById('testid').focus(),10);
}
<input style="width:50px" id="testid" value="abcdefghijklmnopqrst">
<button onclick="sel()">select 10,10</button>

  • Related