4

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?

1 Answers1

5

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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Hi @mplungjan, this technique is not working in my file. Is it possible to scroll to the caret? Thanks in advance – user3103982 Mar 26 '22 at 07:13
  • 1
    Your code did not work for me, my code does work for me in Chrome at least. So perhaps there is something else going on. I first tried your code with a timeout on the select - perhaps your browser needs a timeout on the focus with my code – mplungjan Mar 26 '22 at 07:20
  • 1
    HI @mplungjan I'm back. Since my input text was inside an ag-grid, I turned on suppressKeyboardEvent in my gridoptions. Yet there is a way to identify current cursor position and change scrollLeft property of input element ( https://stackoverflow.com/a/7948715/2820150 ). Thanks for spending time for my question – user3103982 Mar 26 '22 at 09:53