Reputation: 281
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?
Upvotes: 10
Views: 17884
Reputation: 281
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);
Upvotes: 16
Reputation: 165
I posted an Answer on firing a wheel event now, as initEvent
is deprecated:
https://stackoverflow.com/a/72525302/16054918
You could adapt it to your needs or make the function more general.
Upvotes: 0
Reputation: 804
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.
Upvotes: -1