jquery animate scrolltop callback

callum.bennett picture callum.bennett · Jun 1, 2011 · Viewed 10.1k times · Source

I have the following jquery that scrolls the page to the top, then performs a callback function.

The problem is that even if the page is already at the top, it still waits for the '1000' to elapse before performing the callback, which i dont want it to.

$('html').animate({scrollTop:0}, 1000, 'swing', function(){

//do something

});

Answer

Robert Koritnik picture Robert Koritnik · Jun 1, 2011

It doesn't wait

It animates your document from top to the top... Funny but that's how it is. You have other alternatives. Either:

  • check your page position before scrolling (as others suggested by providing some code) or
  • use some jQuery plugin that works differently

My .scrollintoview() jQuery plugin works that way. It scrolls only if it has to and runs a complete handler after scrolling is complete (if there was scrolling in the first place) or immediately if scrolling is not needed.

But it needs some element that needs to be scrolled. You're actually not scrolling any element into view but rather just HTML. This is of course not the safest way. It's better to use either:

$("html,body")

or

$(window)

It's more cross browser supported. So your $("html") may not work in all of them.