Jquery animate scrolltop callback

I have the following jquery that scrolls the page at the top and then performs a callback function.

The problem is that even if the page is already at the top of the page, it is still waiting for the completion of "1000" before making the callback, which I do not want.

$('html').animate({scrollTop:0}, 1000, 'swing', function(){ //do something }); 
+2
source share
3 answers

He does not wait

It animates your document from top to top ... Funny, but true. You have other alternatives. Or:

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

My .scrollintoview() The jQuery plugin works just like that. It scrolls only if necessary, and starts the full handler after the scroll is completed (if there was a scroll in the first place) or immediately if the scroll is not needed.

But for this you need an element that needs to be scrolled. You are not actually scrolling any element, but just HTML. This, of course, is not the safest way. Better to use either:

 $("html,body") 

or

 $(window) 

More cross browser supported. Thus, your $("html") may not work in all of them.

+3
source
 var html=$('html'); if(html.scrollTop()>0){ html.animate({scrollTop:0}, 1000, 'swing', function(){ //do something }); }else{ //do something } 
+1
source
 if( $(window).scrollTop() > 0 ) { $('html').animate({scrollTop:0}, 1000, 'swing', function(){ //callback after animate }); } else { // callback right now (no wait) } 
+1
source

Source: https://habr.com/ru/post/915508/


All Articles