can i simulate mousewheel up or down with javascript

Viewed 12098

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 javascript function and simulate the mouse wheel actions. I tried with :

window.scrollTo(0,300);

but scrolling in my case doesn't zoom (seems like only mouse wheel action work).

Do you have any idea, how can i simulate the mouse wheel up or down within the javascript ?

thank you

3 Answers

So i solve my problem after some research.

Here is what i did :

I create a mouse event and pass it 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 so :

element.dispatchEvent(evt);

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.

Related