baao
baao

Reputation: 73231

Mousewheel event firing too often / many scrolls break animation

I wrote a little function in order to have my page scroll nicely to the next div.

The scrolling appears to be working, but only as long as the user only scrolls one step with the mousewheel, as soon as the wheel is "rolled" more often than on step, it won't work for the next div any more / breaks it all. I've set up a fiddle to demonstrate the behavior:

DEMO

The javascript code looks like this:

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" ;

     $('#start').bind(mousewheelevt, function(e){

     var evt = window.event || e ;
     evt = evt.originalEvent ? evt.originalEvent : evt;
     var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta;

     if(delta < 0)
     {


     $('html, body').animate({
     scrollTop: $('#hotels').offset().top
     }, 2000);

     }
     });

     var mousewheelevt1 = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" ;

     $('#hotels').bind(mousewheelevt1, function(e){

     var evt = window.event || e ;
     evt = evt.originalEvent ? evt.originalEvent : evt;
     var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta;

     if(delta < 0)
     {
     $('html, body').animate({
     scrollTop: $('#training').offset().top
     }, 2000);

     }
     else {
     $('html, body').animate({
     scrollTop: $('#start').offset().top
     }, 2000);

     }
     });
   var mousewheelevt2 = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" ;

     $('#training').bind(mousewheelevt2, function(e){

     var evt = window.event || e ;
     evt = evt.originalEvent ? evt.originalEvent : evt;
     var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta;

     if(delta < 0)
     {


     }
     else {
     $('html, body').animate({
     scrollTop: $('#hotels').offset().top
     }, 2000);

     }
     });

Is there a way to disable mousewheel after the first event fired or do you have other ideas on how to solve this?

Upvotes: 2

Views: 1531

Answers (2)

santi6291
santi6291

Reputation: 164

You should use a flag before you call the scroll event have a variable with the value of true, when the scroll event is called set the variable to false and of course make sure the scroll event only executes when when the variable is set to true, once the animation is complete set the variable back to true. hope that helps.

Upvotes: 1

Anubhav
Anubhav

Reputation: 7208

.stop().animate() did the trick.

FIDDLE

You should also use e.preventDefault() to disable the default mousewheel event if you want to get rid of the flickering.

Upvotes: 1

Related Questions