6

Ive got this rather popular code:

jQuery(document).ready(function($) {
    $(".scroll").click(function(event){     
        event.preventDefault();
        $('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
    });
});

And in html:

<a href="#scrollThere">Click</a>

Goes to

<div class="scroll" id="scrollThere"></div>

But on one page website when the divs are on different height, i.e. The scroll has to go on different lenghths - the scrolling is sometimes much faster and sometimes very slow. What kind of code would make te scroll always be time = speed * distance, not time = lentgh in ms or in other words how can I achieve always the same speed?

hkk
  • 2,069
  • 1
  • 23
  • 48
Piotr Uchman
  • 119
  • 1
  • 7

1 Answers1

9

Link your duration to the pixels you are having to move.

The duration in your code is locked at 500. If I get the amount of pixels that have to be moved in either direction and multiply it by some milliseconds you can get a set speed at which the page will scroll.

Replace this:

$('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);

With this:

$('html,body').animate({scrollTop:$(this.hash).offset().top}, 
    Math.abs(window.scrollY - $(this.hash).offset().top) * 10);

Edit the 10 above to increase or decrease the duration.

iambriansreed
  • 21,935
  • 6
  • 63
  • 79
  • Thank You very much! This answer is perfect for a noob like me and works great. – Piotr Uchman Jan 03 '14 at 14:10
  • `Math.pow(Math.abs(window.scrollY - $(this.hash).offset().top),2/3)*5)` gives you much better scroll on large scale of height, in my case more than 60k pixels ... – Sijav Aug 10 '16 at 02:21