2

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

Gaurav Gupta
  • 1,929
  • 4
  • 21
  • 40

3 Answers3

9

event.wheelDelta is not defined in every browser, deprecated and should not been used anymore according to its Mozilla documention. 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;
});
ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87
2
var Scale = 1;

document.addEventListener("wheel",function(e){

  if(e.wheelDelta>0) Scale+=0.01; 
  else Scale-=0.01;

  // use Scale variable ....

  e.preventDefault();
});

user3684669
  • 117
  • 1
  • 3
1

Use event.wheelDeltaY or event.deltaY
console.log(event.wheelDeltaY) for mouse:
enter image description here
for touchpad:
enter image description here
Instead of -120 it gives 0. -120 which appears in the wheelDelta is actually the result of horizontal scroll(wheelDeltaX).(When you try to zoom in using touch pad, there may be slight horizontal motion too)
Do not zoom when its 0 and you will get consistent smooth zooming!

Gaurav Gupta
  • 1,929
  • 4
  • 21
  • 40