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');
};
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With