javascriptmousewheel

How to create mouse wheel scroll counter


How can I count mouse scroll using pure JS?
Example:

default value: 0
scroll down: ++1
scroll up: --1

I tried to do this using deltaY and a switch case

let mouseWheel = 0;
switch (deltaY) {
  case 100:
    if (mouseWheel > 0) {
      mouseWheel += 1;
    } else if (mouseWheel < 0) {
      mouseWheel = 0;
    }
    break;
  case -100:
    if (mouseWheel > 0) {
      mouseWheel -= 1;
    } else if (mouseWheel < 0) {
      mouseWheel = 0;
    }
    break;
  default:
    break;
}

Solution

  • You can use the wheel event to detect for mouse wheel changes and add/deduct the counter accordingly.

    My example assumes you are only checking vertical scrolling (i.e. change in deltaY). Feel free to amend the code if you need to check horizontal scroll too.

    I think you don't want to hard code the deltaY change (e.g. 100 or -100) because different people may have configured a different scroll amount and this would break your switch statement.

    const containerEle = document.querySelector("#container")
    
    let mouseWheelCounter = 0;
    
    containerEle.addEventListener("wheel", (wheel) => {
      if(wheel.deltaY > 0) {
        mouseWheelCounter++;
      }else{
        mouseWheelCounter--;
      }
      console.log(mouseWheelCounter) 
    })
    

    Here's an example with JSFiddle