Hidden jQuery snippet works at different speeds

I got this pretty 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> 

Go to

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

But on one page of the site, when divs are at different heights, i.e. the scroll should go in different lengths - scrolling is sometimes much faster, and sometimes very slow. What code will make te scroll always be time = speed * distance , not time = lentgh in ms or in other words, how can I always achieve the same speed?

+6
source share
1 answer

Associate your duration with the pixels you need to move.

The duration of your code is locked at 500 . If I get the number of pixels that need to be moved in any direction and multiplied by a few milliseconds, you can get the set speed at which the page scrolls.

Replace this:

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

Wherein:

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

Change 10 above to increase or decrease the duration.

+7
source

All Articles