input[type=number] continuously increasing when clicking on arrows in Chrome and Edge

Viewed 1156

I am experiencing the following issue: After a particular jQuery library loads, if you click on a number input arrow, the input value keeps increasing (or decreasing) until the focus is shifted outside the input element.

Binding an input event to the element showed it keeps triggering, which led me to believe some piece of code kept setting element.value in a loop. But that did not happen.

I've tracked the issue down to calling event.preventDefault() on a mouseup event.

See:

document.body.addEventListener('mouseup', (e) => {
    e.preventDefault();
});
<input type="number">

Why does this happen?

2 Answers

I had trouble finding information by searching what causes these infinitely increasing inputs.

Only after finding the cause myself, I've found out about a similar bug that happened with preventing the default of mousemove (https://stackoverflow.com/a/37521764/6849064). Although, this one does not seem to happen anymore.

Looks like this is a Chrome (and Edge) bug. But as https://stackoverflow.com/a/65253876/6849064 said, it is actually default behavior which makes sense in the way he said it. I myself failed to find this standard behavior documented anywhere. One way to fix the problem is to stop bubbling of the event up to the document,

document.querySelector('input').addEventListener('mouseup', (e) => {
    e.stopPropagation();
});

And the other is, well, not preventing default behavior.

The following issue has nothing to do with jQuery. The issue is the code is doing exactly what you wanted it to do. In the code <input type="number" /> has got 2 events. One is 'mousedown' and second is 'mouseup'.

Consider following example: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_event_preventdefault2

The same is represented in the example above.

What you are doing is cancelling the 2nd part, ie mouseup so if you do mousedown and cancel mouseup, then the number will:

  1. Go on increasing if you push uparrow
  2. Go on decreaseing if you push downarrow

The only, surprise is this would have perfect sense if you would have written the code adding event to input rather than body, but anyways seems browser by default is increasing or decreasing number -- based on event-bubbling to body.

Note: The issue is replicated below, while no jQuery has been added!

document.body.addEventListener('mouseup', (e) => {
  e.preventDefault();
});
<input type="number">

Related