Skip to content

Instantly share code, notes, and snippets.

@RShergold
Last active December 1, 2015 18:02
Show Gist options
  • Save RShergold/fd31881b906c67ec7186 to your computer and use it in GitHub Desktop.
Save RShergold/fd31881b906c67ec7186 to your computer and use it in GitHub Desktop.
function scroll_to(element, duration = 500, easing = 'easeInOutQuart') {
var start_pos = document.body.scrollTop,
end_pos = element.offsetTop,
distance = end_pos - start_pos,
start_time = Date.now(),
end_time = start_time + duration;
var easingFunctions = {
// https://gist.github.com/gre/1650294
// no easing, no acceleration
linear: function (t) { return t },
// accelerating from zero velocity
easeInQuad: function (t) { return t*t },
// decelerating to zero velocity
easeOutQuad: function (t) { return t*(2-t) },
// acceleration until halfway, then deceleration
easeInOutQuad: function (t) { return t<.5 ? 2*t*t : -1+(4-2*t)*t },
// accelerating from zero velocity
easeInCubic: function (t) { return t*t*t },
// decelerating to zero velocity
easeOutCubic: function (t) { return (--t)*t*t+1 },
// acceleration until halfway, then deceleration
easeInOutCubic: function (t) { return t<.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1 },
// accelerating from zero velocity
easeInQuart: function (t) { return t*t*t*t },
// decelerating to zero velocity
easeOutQuart: function (t) { return 1-(--t)*t*t*t },
// acceleration until halfway, then deceleration
easeInOutQuart: function (t) { return t<.5 ? 8*t*t*t*t : 1-8*(--t)*t*t*t },
// accelerating from zero velocity
easeInQuint: function (t) { return t*t*t*t*t },
// decelerating to zero velocity
easeOutQuint: function (t) { return 1+(--t)*t*t*t*t },
// acceleration until halfway, then deceleration
easeInOutQuint: function (t) { return t<.5 ? 16*t*t*t*t*t : 1+16*(--t)*t*t*t*t }
}
var requestAnimFrame = (function(){
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); };
})();
var animate_frame = function() {
var now = Date.now(),
percent = easingFunctions[easing]( (now - start_time) / duration ),
new_top = start_pos + (distance * percent);
document.body.scrollTop = new_top;
if (now >= end_time) {
document.body.scrollTop = end_pos;
} else {
requestAnimFrame(animate_frame);
}
};
animate_frame();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment