Search code examples
javascriptdomevent-handlinguser-inputevent-listener

How to enable an existing mousewheel-driven value-change on just focused number-type input-elements?


I have a working script but I don't know how to use addEventlistener instead of onfocus & onmousewheel. And how to apply it to many elements?

const input = document.getElementsByClassName("change-onscroll")[0];
input.value = input.min ? input.min : 0;
input.onfocus = () => {
    input.onmousewheel = (e) => {
        if (deltaY > 0 && +input.value <= +input.min) return;
        e.deltaY < 0 ? input.value++ : input.value--;
    };
};
<input type="number" name="num" class="change-onscroll" min="0" />


Solution

  • In case the OP wants to enable the scroll behavior for just focused input elements the OP needs to explicitly do both registering such a handling on any such element's 'focus' or 'focusin' event and deregistering the handling again on any such element's 'blur' or 'focusout' event

    function handleNumberTypeMouseScroll(evt) {
      const { currentTarget: input, deltaY } = evt;
      const minValue = parseInt(input.min, 10);
      
      if (deltaY > 0 && input.value <= minValue) return;
      deltaY < 0 ? input.value++ : input.value--;
    }
    
    function deregisterMousewheelHandling({ currentTarget }) {
      currentTarget
        .removeEventListener('mousewheel', handleNumberTypeMouseScroll);
    }
    function registerMousewheelHandling({ currentTarget }) {
      currentTarget
        .addEventListener('mousewheel', handleNumberTypeMouseScroll);
    }
    document
      .querySelectorAll('.change-on-focused-scroll')
      .forEach(elmNode => {
        elmNode.addEventListener('blur', deregisterMousewheelHandling);
        elmNode.addEventListener('focus', registerMousewheelHandling);
      });
    <input type="number" name="num" class="change-on-focused-scroll" min="0" value="0" />
    <input type="number" name="num" class="change-on-focused-scroll" min="5" value="5" />
    <input type="number" name="num" class="change-on-focused-scroll" min="20" value="20" />