2

I want to programmatically add words in input and always see the end of the text. But the problem is that when I'm adding word (like input.value += 'word') when length of text is almost the same as length of input, text inside input doesn't move, so I can see only begining of the text and ending is become hidden.
I think if I could put cursor to the end of input it will help, but none of tricks with cursor not working in Chrome, such as

input.value = input.value

or

input.setSelectionRange(input.value.length, input.value.length);
cooperok
  • 4,249
  • 3
  • 30
  • 48

2 Answers2

3

Seems to work well enough:

let input = document.getElementById('auto');
let sentence = 'Courage is the magic that turns dreams into reality.';
let index = 0;

setTimeout(function typing() {
  let letter = sentence.charAt(index++);

  input.blur();
  input.value += letter;
  input.focus();
  input.setSelectionRange(index, index);

  if (index < sentence.length) {
    let ms = Math.floor(75 + Math.random() * 150);

    setTimeout(typing, ms);
  }
}, 1000);
<input id="auto" type="text">
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
1

If the input does not have focus, then Chrome will show it "scrolled" all the way to the left, showing the beginning of your input value.

If the element has focus, then you can set the selection range to move the cursor:

window.onload = function(){
  
  var input = document.getElementById('foobar');
  input.value += ' bazbat';
  
  input.focus();
  input.setSelectionRange( input.value.length - 1 );
  
}
<input id="foobar" value="foobar" size="6">

But it would be a very confusing and frustrating UX if the cursor is moving around while the user is attempting to type a value.

Other options to consider:

  • Change the width of your input to match the value. make html text input field grow as I type?
  • Toggle between an input and a span (edit mode vs read mode). With a span, you'd have a lot more control over how text is displayed. Jquery: Toggle between input and text on click
  • Use an indicator of some sort to alert the user that one of their input values was modified. This would be useful even if they can see the entire value, as they might not notice that the value was updated.
Community
  • 1
  • 1
JDB
  • 25,172
  • 5
  • 72
  • 123