Skip to content

Instantly share code, notes, and snippets.

@jbasoo
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbasoo/6219f3ad4d8091137bf4 to your computer and use it in GitHub Desktop.
Save jbasoo/6219f3ad4d8091137bf4 to your computer and use it in GitHub Desktop.
Variable time smooth scroll
/**
*
* In real life your time taken to complete a journey = distance/speed.
* This emulates that, longer journeys actually take more time, shorter journeys take less time.
*
* Forked from http://css-tricks.com/snippets/jquery/smooth-scrolling/
* Demo http://codepen.io/jbasoo/pen/LEovc
*
* Requires jQuery and jQuery Easing
*
*/
$(function() {
$('a[href^=#]:not([href=#])').click(function() { // This targets all internal page links (which may break some other js plugins like tabs/accordions etc. Be more specific with your selector if you have issues.)
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
var currentLocation = $(window).scrollTop();
var targetLocation = target.offset().top;
var distance = Math.abs(currentLocation - targetLocation);
var speed = 2; // X px per ms
var time = distance / speed;
$('html,body').animate({
scrollTop: targetLocation
}, time, 'easeOutCubic');
return false;
}
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment