The jQuery rate of change as a function of distance

I am trying to maintain a relatively constant speed when scrolling back to the top of the browser window, depending on how far you are from the top of the page.

So, if you have scrolled through a 500px or 5000px page, I would like to create a function that calculates how long it takes to animate back, while maintaining a constant speed.

var scrollTo = function() { var top = $(window).scrollTop(); var dist = $('.article').offset().top; var speed = // not sure what goes here depending on distance $('html, body').animate( {scrollTop: dist}, speed, 'linear'); }; 
+6
source share
1 answer

You can use something like distance * <millisecond per unit distance> ,

As if you would like to cover a distance of 500 and 1500 in 1000 ms and 3000 ms respectively, then the formula will be

 var speed = distance * 2 

Example:

 var scrollTo = function() { var dist = jQuery(window).scrollTop(); var speed = dist * 2; $('html, body').animate({ scrollTop: 0 }, speed); } 
 body { height: 5000px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a style="position:fixed; top: 10px" onclick="scrollTo()">top</a> 
+4
source

All Articles