Skip to content

Instantly share code, notes, and snippets.

@bloodyowl
Created June 29, 2012 09:52
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bloodyowl/3016988 to your computer and use it in GitHub Desktop.
Save bloodyowl/3016988 to your computer and use it in GitHub Desktop.
smoothScroll explained
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