1

I'd like to have input value in my input element change when a user hovers their mouse over the input and scrolls up and down. I've tried adding an onscroll listener to the input but it doesn't seem to do anything. I'd like to use plain JS but am willing to use jQuery. Thanks for the help.

Clarification: I don't want to use the up and down buttons. I want to use be able to hover over the input and then scroll which in change increase or decreases the input value. Perhaps using a container div is needed?

Heres a codepen.

HTML

<input id="my-input" type="number" min="0" max="100" />

CSS

#my-input {
  width: 50px;
  height: 50px;
}

JS

var myInput = document.getElementById('my-input');
myInput.value = 0;
myInput.onscroll = function(e) {
  // this is never printed
  console.log('scrolling');
}
Daniel Kobe
  • 9,376
  • 15
  • 62
  • 109
  • 1
    attach to the onchange event. input does not support onscroll. – joelnet Mar 14 '16 at 23:40
  • @joelnet Do you want it to scroll up when the value increases and scroll down on the page when the value decreases? – Larry Lane Mar 14 '16 at 23:54
  • @LarryLane No I'd want to prevent the default behavior of actually scrolling. – Daniel Kobe Mar 14 '16 at 23:55
  • change the input type from number to text. the scroll bars you are seeing is how the browser displays a number field. You can also try this: http://stackoverflow.com/questions/9712295/disable-scrolling-on-input-type-number – joelnet Mar 14 '16 at 23:58

2 Answers2

0

This line

console.log('scrolling');

doesn't execute because there isn't any scrolling. In the inputs, up-arrow and down-arrow act as an increaser and reducer. So onscroll event never work on inputs.


oninput event would be a good alternative in this case:

var myInput = document.getElementById('my-input');
myInput.value = 0;
myInput.oninput = function(e) {
  console.log('scrolling');
}
#my-input {
  width: 50px;
  height: 50px;
}
<input id="my-input" type="number" min="0" max="100" />
Shafizadeh
  • 9,960
  • 12
  • 52
  • 89
  • The `onchange` event won't allow me to change input by scrolling. What if I attached the `onscroll` to a container div? – Daniel Kobe Mar 14 '16 at 23:51
0

You have to use the onmousewheel event. See this. Warning: seems that there isn't reliable x-browser support.

PS Codepen updated as well.

JS

var myInput = document.getElementById('my-input');
var myInputCntnr = document.getElementById('my-input-cntnr');
myInput.value = 0;
myInputCntnr.onmousewheel = function(e) {
  console.log(e.deltaY);
  if(e.deltaY > 1) {
    myInput.value++;
  } else if (e.deltaY < -1) {
    myInput.value--;
  }
}
Community
  • 1
  • 1
Daniel Kobe
  • 9,376
  • 15
  • 62
  • 109