Created
June 29, 2012 09:52
-
-
Save bloodyowl/3016988 to your computer and use it in GitHub Desktop.
smoothScroll explained
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
function (destination, duration) { | |
// destination (relative to window top) in px | |
// duration in ms | |
/* Variables */ | |
var startPosition = "pageYOffset" in window ? window.pageYOffset : document.documentElement.scrollTop, | |
startTime = +new Date(), | |
endTime = startTime + duration, | |
// if top of element is outside the document, then define end point to document limit | |
// elsewhere, go the the top of the element | |
destinationSafe = document.height < (destination + window.innerHeight) ? document.height - window.innerHeight : destination, | |
// check if scroll direction is up or down | |
direction = destinationSafe - startPosition < 0 ? true : false, | |
// animate | |
interval = setInterval(function () { | |
// get current time every 10ms | |
var currentTime = +new Date(); | |
// if time is still before end (var e) | |
if (currentTime <= endTime) { | |
// then scroll every 10ms to the logical position | |
scrollTo(0, direction ? startPosition - (currentTime - startTime) / (endTime - startTime) * startPosition + destinationSafe : startPosition + (currentTime - startTime) / (endTime - startTime) * (destinationSafe - startPosition)) | |
} else { | |
// if time is over, scroll to the destination (10ms can't be always precise) | |
scrollTo(0, destinationSafe); | |
// stop setInverval mechanism | |
clearInterval(interval) | |
} | |
}, 10); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment