简体   繁体   中英

How to fire scroll (mousewheel) event with specific delta in JavaScript?

I'm trying to fire scroll event in chrome with creating custom event by document.createEvent and I want to trigger all functions binded to scroll or mousewheel listeners (I'm not sure if it scrolls browser itself?). I catch event by onmousewheel listener but event object have deltaX == 0 && deltaY == 0 when I used to specify their values:

document.documentElement.onmousewheel = function(e) {
  console.log(e.deltaX, e.deltaY, e.wheelDeltaX, e.wheelDeltaY)  // 0, 0, 0, 0
}

var e = document.createEvent('WheelEvent');
e.initMouseEvent('mousewheel', true, true, window, 120, 0, 0, 0, 0, 0, 0, 0, 0, 
0, null);
e.wheelDeltaY = 120;
e.deltaY = 120;
document.documentElement.dispatchEvent(e);

I'm not sure that I must use this type of event and this initaliztion type. So how can I specify event's delta values?

First of all, this is deprecated and you shouldn't use initMouseEvent at all.

What you should do is to create WheelEvent with delta params https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/WheelEvent and then dispatch it if you want to proceed with custom delta values or stuff like that.

 window.addEventListener('wheel', function(e) { console.log(e.deltaY) if (e.deltaY < 0) { console.log('scrolling up'); document.getElementById('status').innerHTML = "scroll up"; } if (e.deltaY > 0) { console.log('scrolling down'); document.getElementById('status').innerHTML = "scroll down"; } });
 <div id="status"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM