Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery change speed depending on distance

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

So, if you have scrolled down the page 500px or 5000px I would like to create a function that calculates how long it should take to animate back to the top keeping 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');
};
like image 351
Benjamin Avatar asked Apr 14 '16 06:04

Benjamin


1 Answers

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

Like if you want to cover distance of 500 and 1500 in 1000ms and 3000ms respectively then the formula will be

var speed = distance * 2

Ex:

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>
like image 127
Arun P Johny Avatar answered Oct 09 '22 17:10

Arun P Johny