gaurav gupta gaurav gupta - 3 months ago 10
Javascript Question

wheel event javascript give inconsistent values

I was working on zooming functionality with html / javascript / css

I attached a

wheel
event listener to my
div
tag
and
console.log(event.wheelDelta)


It works nicely with mouse. The
console.log
gives positive multiples of 120 for zoom in and negative otherwise

enter image description here


Problem is with touchpad

enter image description here

On zoom in gesture, it doesn't give consistent values. There are some
-120
's in between. Because of this the zoom is very rough.

How do i achieve smooth zooming or how do i get consistent
wheelDelta
values with touchpad

Answer

event.wheelDelta is not defined in every browser. You could use the values event.deltaX and event.deltaY. For further information, please refer to Mozilla wheel documentation.

I tested the following code in Google Chrome and Mozilla Firefox. The values are very different. Google Chrome always returns as event.deltaY the value 100 or -100. In Mozilla Firefox it always returns the values 3 or -3.

document.addEventListener('wheel', function(event) {
    console.log(event.deltaX, event.deltaY);
});

I would not rely onto the wheel value but rather listen to the scroll event like this is described on the Mozilla scroll documentation:

var lastKnownScrollPosition = 0;
var ticking = false;

function doSomething(scrollPosition) {
    console.log(scrollPosition);
}

window.addEventListener('scroll', function(e) {
    lastKnownScrollPosition = window.scrollY;
    if(!ticking) {
        window.requestAnimationFrame(function() {
            doSomething(lastKnownScrollPosition);
            ticking = false;
        });
    }
    ticking = true;
});