Search code examples
javascripthtmlfocuscaretonblur

Set input caret position on blur in Safari without refocusing input


⏯ Playground Link (before the answer)
⏯ Playground Link (after the answer https://stackoverflow.com/a/67071637/112882)

<style>input[type=text] { width: 3em; text-overflow: ellipsis; }</style>
<input id=a type=text value=123456789><br>
<input id=b type=text value=123456789>

<script>
  a.addEventListener('blur', function(event) {
    if (event.target.selectionStart > 0)
      event.target.setSelectionRange(0, 0);
  });
</script>

event.target.setSelectionRange(0, 0); is something

Now,

  1. Firefox is the only browser that requires setSelectionRange for 12359
  2. Safari is the only browser where setSelectionRange interferes with blur (focus loss/change)
    setSelectionRange traps the user into #a in Safari with no way out!
    selectionStart > 0 that I have added helps one escape on second attempt.

does anyone see an ultimate fix that satisfies the quirks of all browsers including Safari and Firefox?


Following up with Safari: https://bugs.webkit.org/show_bug.cgi?id=224425


Solution

  • There's no need to setSelectionRange() to update the scroll position. input.scrollLeft = 0; would have the same effect without the side effects in Safari.