jQuery .scrollTop(); + animation

I set the page to scroll to top when a button is clicked. But first I used an if statement to see if the top of the page was not set to 0. Then if it's not 0 I animate the page to scroll to the top.

var body = $("body");
var top = body.scrollTop() // Get position of the body

if(top!=0)
{
  body.animate({scrollTop:0}, '500');
}

The tricky part now is animating something AFTER the page has scrolled to the top. So my next thought is, find out what the page position is. So I used console log to find out.

console.log(top);  // the result was 365

This gave me a result of 365, I'm guessing that is the position number I was at just before scrolling to the top.

My question is how do I set the position to be 0, so that I can add another animation that runs once the page is at 0?

Thanks!


Solution 1:

To do this, you can set a callback function for the animate command which will execute after the scroll animation has finished.

For example:

var body = $("html, body");
body.stop().animate({scrollTop:0}, 500, 'swing', function() { 
   alert("Finished animating");
});

Where that alert code is, you can execute more javascript to add in further animation.

Also, the 'swing' is there to set the easing. Check out http://api.jquery.com/animate/ for more info.

Solution 2:

Try this code:

$('.Classname').click(function(){
    $("html, body").animate({ scrollTop: 0 }, 600);
    return false;
});

Solution 3:

Use this:

$('a[href^="#"]').on('click', function(event) {

    var target = $( $(this).attr('href') );

    if( target.length ) {
        event.preventDefault();
        $('html, body').animate({
            scrollTop: target.offset().top
        }, 500);
    }

});

Solution 4:

for this you can use callback method

body.animate({
      scrollTop:0
    }, 500, 
    function(){} // callback method use this space how you like
);