gaurav gupta gaurav gupta - 1 year ago 54
Javascript Question

wheel event javascript give inconsistent values

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

I attached a

event listener to my

It works nicely with mouse. The
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
's in between. Because of this the zoom is very rough.

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

Answer Source

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) {

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