Skip to content

Instantly share code, notes, and snippets.

@marekhrabe
Created March 9, 2014 15:46
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marekhrabe/9449737 to your computer and use it in GitHub Desktop.
Save marekhrabe/9449737 to your computer and use it in GitHub Desktop.
Animated scrolling without any dependency on libraries. If user scrolls when animation is running, scroll animation would be immediately canceled.
window.requestAnimFrame = (function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(callback){window.setTimeout(callback,1000/60);};})();
var easeInOutQuad = function (t, b, c, d) {
t /= d/2;
if (t < 1) return c/2*t*t + b;
t--;
return -c/2 * (t*(t-2) - 1) + b;
};
var animatedScrollTo = function (element, to, duration) {
var start = element.scrollTop,
change = to - start,
animationStart = +new Date();
var animating = true;
var lastpos = null;
var animateScroll = function() {
if (!animating) {
return;
}
requestAnimFrame(animateScroll);
var now = +new Date();
var val = Math.floor(easeInOutQuad(now - animationStart, start, change, duration));
if (lastpos) {
if (lastpos === element.scrollTop) {
lastpos = val;
element.scrollTop = val;
} else {
animating = false;
}
} else {
lastpos = val;
element.scrollTop = val;
}
if (now > animationStart + duration) {
element.scrollTop = to;
animating = false;
}
};
requestAnimFrame(animateScroll);
};
// scroll to top in 10 seconds
button.addEventListener('click', function () {
animatedScrollTo(document.body, 0, 10000);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment