Skip to content

Instantly share code, notes, and snippets.

@heartcode
Created February 11, 2012 23:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heartcode/1804993 to your computer and use it in GitHub Desktop.
Save heartcode/1804993 to your computer and use it in GitHub Desktop.
Scrolls the window to the required position (Please note that this snippet works best with top scrolling just for now)
/*
* Scrolls the window to the required position using animation with custom easing.
* The required position can be set with the 1st argument ('position');
* The fineness of the animation can be customized by using the 'speed' (2nd) argument, which ranges between 0.1 (very fine) and 1 (instant jump).
* Usage #1:
* scrollWindowTo(0, 0.2); // -> Scrolls the page to the top with a fine animation
* Usage #2:
* scrollWindowTo(100, 1); // -> Makes the page jump to 100px
*/
var scrollWindowTo = (function(){
var timer = 0, posTo = 0, scrollingSpeed = 0.1;
// Returns the current scroll position
function scrollPosition() {
if (typeof pageYOffset != "undefined") {
return pageYOffset;
} else {
var body = document.body, doc = document.documentElement;
doc = doc.clientHeight ? doc: body;
return doc.scrollTop;
}
};
// Calculates the next scroll position with a custom easing equation
function easeScrolling() {
if(Math.round(Math.abs(currentPos - posTo)) > 0) {
currentPos += (posTo - currentPos) * scrollingSpeed;
} else {
currentPos = posTo;
window.clearInterval(timer);
}
window.scrollTo(0, currentPos);
};
/*
* Starts the scrolling to the 'position' which can be anything between 0 and the page height
* @param position The required position to scroll the window to
* @param speed The speed can range from 0 to 1 and sets the speed of the animation
*/
return function (position, speed) {
if (timer > 0) {
window.clearInterval(timer);
}
posTo = typeof position === "number" ? Math.abs(position) : 0;
scrollingSpeed = typeof speed === "number" && speed >= 0.1 ? speed : scrollingSpeed;
currentPos = scrollPosition();
timer = window.setInterval(easeScrolling, 16.7);
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment