Home > Software engineering >  How can change a number on focus && on scroll by addEventlistener?
How can change a number on focus && on scroll by addEventlistener?

Time:11-19

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 (e.deltaY > input.min && input.value <= input.min) return;
        e.deltaY < 0 ? input.value   : input.value--;
    };
};
<input type="number" name="num"  min="0" />

CodePudding user response:

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;
  
  if (deltaY > input.min && input.value <= input.min) return;
  deltaY < 0 ? input.value   : input.value--;
}

function deregisterMousewheelHandling({ currentTarget }) {
  currentTarget
    .removeEventListener('mousewheel', handleNumberTypeMouseScroll);
}
function registerMousewheelHandling({ currentTarget }) {
  currentTarget
    .addEventListener('mousewheel', handleNumberTypeMouseScroll);
}

const nodeList = document
  .querySelectorAll('.change-on-focused-scroll');

nodeList
  .forEach(elmNode =>
    //elmNode.addEventListener('focusout', deregisterMousewheelHandling)
    elmNode.addEventListener('blur', deregisterMousewheelHandling)
  );
nodeList
  .forEach(elmNode =>
    //elmNode.addEventListener('focusin', registerMousewheelHandling)
    elmNode.addEventListener('focus', registerMousewheelHandling)
  );
<input type="number" name="num"  min="0" value="0" />
<input type="number" name="num"  min="5" value="5" />
<input type="number" name="num"  min="20" value="20" />

CodePudding user response:

Thank you @ManirajMurugan for the help.

// const inputs = document.querySelectorAll(".change-onscroll");
const inputs = document.querySelectorAll('input[type="number"]');
inputs.forEach((input) => {
    input.value = input.min ? input.min : 0;
    input.addEventListener("focus", () => {
        input.addEventListener("mousewheel", (e) => {
            if (e.deltaY > input.min && input.value <= input.min) return;
            e.deltaY < 0 ? input.value   : input.value--;
        });
    });
});
<input type="number" name="num"  min="0" />
<input type="number" name="num"  min="1" />
<input type="number" name="num"  min="2" />
<input type="number" name="num"  min="3" />

  • Related