skip to Main Content

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;
}

2

Answers


  1. 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

    Login or Signup to reply.
  2. let mouseWheel = 0;
    
    addEventListener("wheel", (evt) => {
      mouseWheel += Math.sign(evt.deltaY);  // Add or subtract 1
      mouseWheel = Math.max(0, mouseWheel); // Prevent negative value
      console.log(mouseWheel);
    });
    Scroll down and up
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search