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
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.Here’s an example with JSFiddle
deltaY
from the WheelEvent-1
or1
value0