Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to the caret position of an html input

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?

like image 901
user3103982 Avatar asked Oct 26 '25 07:10

user3103982


1 Answers

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>
like image 119
mplungjan Avatar answered Oct 28 '25 22:10

mplungjan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!