Last active
August 29, 2015 14:02
-
-
Save jbasoo/6219f3ad4d8091137bf4 to your computer and use it in GitHub Desktop.
Variable time smooth scroll
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* 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