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?
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?
Share Improve this question asked Oct 3, 2017 at 5:26 VyacheslavVyacheslav 991 gold badge3 silver badges8 bronze badges 1-
Beware: if your goal is to create a synthetic event to trigger the UI to scroll, that isn't possible because any event you create programmatically will have the
isTrusted: false
property which is equivalent topreventDefault()
being called on your event, see: w3/TR/uievents/#trusted-events Instead, look into developer.mozilla/en-US/docs/Web/API/Element/scrollTo as an (inferior) replacement. – Keavon Commented Dec 5, 2021 at 8:15
2 Answers
Reset to default 5First 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/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>