javascriptjquery

Animate scrolling when user scrolls


I want to animate page scrolling incrementally to different sections of the page when the user scrolls. So I wrote this code:

var $window = $(window);    
var sectionHeight = $window.height();
var animating = false;
var dir;
// initialize page position (0)
var pagePos = $(window).scrollTop();

$(window).scroll(function() {
    // current page position    
    var st = $(this).scrollTop();

    // whether to animate up or down        
    dir = ((st > pagePos) ? '+=' : '-=');

    // animate 
    if (animating == false) {
        animating = true;
        $('html, body').stop().animate({scrollTop: dir+sectionHeight},500, function() {

            pagePos = $(window).scrollTop();    
            animating = false;
        }); 
    }
});

The problem is, I get a chained animation after my initial animation down, that animates the page back to the top. I'm not sure why, because it shouldn't animate unless 'animating' is set to false. It only gets set back to false when the animation is complete... right?


Solution

  • I was able to get it to work, I still don't know why it wouldn't work as it was coded, but here is the solution that worked for me- I was inspired by @sachleen's answer. Thanks sachleen.

    I moved the scroll animation into a separate function, then on the callback to the animation function I used a setTimeout with the same duration as the animation to call another function that simply changed the 'animating' boolean back to false.