zenwaichi
zenwaichi

Reputation: 197

Prevent blur behaviour on input element

document.body.querySelector("input").addEventListener("blur",
  function(e) {
    e.preventDefault()
  });
<input type="text">

Upon the blur event,if the string typed in the input would overflow, the shown area is scrolled back to the start. My snippet does not seem to prevent that behaviour. Is there any way to pull this trick off?

input.value =   "aaaaaaaaaaabbb"
input.sketch = "|___________|"   
inpur.ideal  =    "|___________|"  //just an aligned visual aid 

When input lose focus bbb is no longer shown,I would like to prevent the scroll back to start automagically.

Upvotes: 4

Views: 2609

Answers (1)

skyline3000
skyline3000

Reputation: 7913

preventDefault() on an input's blur event does not prevent the scrolling. What you'll actually need to do is capture the input's scrollLeft position when the blur happens and then force the browser to reset it after it tries to do the scroll. See the code snippet below.

On blur, we capture the input's current scrollLeft. Next, we reset the scrollLeft position wrapped in a window.setTimeout() to ensure the browser waits to render the queued change.

document.body.querySelector("input").addEventListener('blur', function(event) {
  var scrollLeft = event.target.scrollLeft;
  window.setTimeout(function () {
    event.target.scrollLeft = scrollLeft;
  }, 0);
}, false);
<input>

Upvotes: 4

Related Questions