Skip to content

Instantly share code, notes, and snippets.

@jazlalli
Created January 23, 2015 11:23
Show Gist options
  • Save jazlalli/e030c3830e82af965aca to your computer and use it in GitHub Desktop.
Save jazlalli/e030c3830e82af965aca to your computer and use it in GitHub Desktop.
Function to scroll to specified X coord with a map of easing functions to choose from.
function scrollTo(X, duration, easingFunction, callback) {
callback = callback || function () {};
var start = Date.now(),
elem = document.scrollLeft ? document : document.body,
from = elem.scrollLeft;
if (from === X) {
callback();
return; /* Prevent scrolling to the X point if already there */
}
function min(a,b) {
return a < b ? a : b;
}
function scroll(timestamp) {
var currentTime = Date.now(),
time = min(1, ((currentTime - start) / duration)),
easedT = easingFunction(time);
elem.scrollLeft = (easedT * (X - from)) + from;
if (time < 1) requestAnimationFrame(scroll);
else
if (callback) callback();
}
requestAnimationFrame(scroll)
}
var easing = {
// 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 }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment