Home > OS >  Moving caret to end of input not working in Chrome/Opera but works fine on Firefox
Moving caret to end of input not working in Chrome/Opera but works fine on Firefox

Time:01-20

The code looks like:

var input = document.getElementById("Search");
input.onclick = function(){
  setTimeout(function () {

    if (input.setSelectionRange) {
      let len = input.value.length * 2;
      input.setSelectionRange(len, len);
    } else {
      input.value = input.value;

      if (input.scrollTop) {
        input.scrollTop = Number.MAX_SAFE_INTEGER;
      }
    }
  }, 0);
}
<input type="text" id="Search" value="Hello World to everyone that have luck in their life" />

The fiddle:

http://jsfiddle.net/zeoc0xuj/

Seems that works fine on Firefox 109, the caret is moved to right as I expected. On Chrome 109/Opera 94 is not working and caret is moved to end but the end text is not visible until I press LEFT/RIGHT arrow.

How to solve the issue ?

CodePudding user response:

So to move cursor to the end of the input and make sure text is also scrolled:

const input = document.getElementById("Search");
input.onclick = function(){
    this.selectionStart = this.selectionEnd = this.value.length;
    this.scrollLeft = 99999;
}
<input type="text" id="Search" value="Hello World to everyone that have luck in their life" style="width:100px" />

  • Related