How to simulate mousewheel up or down with JavaScript?
Asked Answered
G

3

10

I have a web app where with an immersive view. In this view I can zoom in or zoom out with the mouse wheel action.

What I would like to do is to create 2 buttons which call a JavaScript function and simulate the mouse wheel actions.

I tried with:

window.scrollTo(0,300);

But scrolling in my case doesn't zoom (it seems like only the mouse wheel action works).

How can I simulate the mouse wheel up or down?

Gentilism answered 28/9, 2017 at 16:38 Comment(0)
G
16

So I solved my problem after some research.

Here is what I did:

I create a mouse event and pass it a wheel event:

var evt = document.createEvent('MouseEvents');
evt.initEvent('wheel', true, true); 

Then I can set deltaY depending on if you want a wheel up or a wheel down.

evt.deltaY = +120;
// evt.deltaY = -120

And you can pass this event to your element by doing:

element.dispatchEvent(evt);
Gentilism answered 2/10, 2017 at 7:45 Comment(3)
This used to work in Chrome up to version 49 (April 2016). Now it's just an anecdote.Washerwoman
Hello. I tried using your solution but i got error undefined on CHromeIdaline
Thanks. Working for me on Firefox 101 and Chrome 102.Eyot
S
0

I posted an Answer on firing a wheel event now, as initEvent is deprecated:

https://mcmap.net/q/1163725/-three-js-orbitcontrols-js-invoking-zoom-in-out-with-button-controls-dollyout-is-not-a-function

You could adapt it to your needs or make the function more general.

Sergiosergipe answered 7/6, 2022 at 2:31 Comment(0)
K
-1

You can use the $.animate() from JQuery. Here's an example:

$('html, body').animate({
  scrollTop: target.offset().top
}, 1000, function() {
   // Do something when animation is complete
});

Where target can be any DOM element you may want to scroll to or a number that determines the length to scroll.

You should check out http://api.jquery.com/animate for more information on this method.

Kreisler answered 28/9, 2017 at 16:51 Comment(4)
That's doesn't work, scroll animation doesn't zoom on my view. I think i should create a mousewheelevent and set wheelDeltaY or something like thatGentilism
@Gentilism Ok, I've just seen you want to actually -zoom in- with mouse scroll, yet in your question you show code for scrolling; which is why it was confusing.Kreisler
Thanks, i just found a solution to my problem. So i create a mouseevent var evt = document.createEvent('MouseEvents'); evt.initEvent('wheel', true, true); if (direction === 'in') { evt.deltaY = -120; } else { evt.deltaY = 120; } and then pass it to my element with element.dispatchEvent(evt);Gentilism
Sweet! Answer your own question so this gets stored for future questions about this.Kreisler

© 2022 - 2024 — McMap. All rights reserved.