Skip to content

Instantly share code, notes, and snippets.

@ticky
Forked from james2doyle/scrollTo.js
Last active March 4, 2016 16:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ticky/e89fc81d88557628e332 to your computer and use it in GitHub Desktop.
Save ticky/e89fc81d88557628e332 to your computer and use it in GitHub Desktop.
// easing functions http://goo.gl/5HLl8
Math.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;
};
Math.easeInCubic = function(t, b, c, d) {
var tc = (t/=d)*t*t;
return b+c*(tc);
};
Math.inOutQuintic = function(t, b, c, d) {
var ts = (t/=d)*t,
tc = ts*t;
return b+c*(6*tc*ts + -15*ts*ts + 10*tc);
};
// requestAnimationFrame for Smart Animating http://goo.gl/sx5sts
var requestAnimFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); };
function scrollTo(element, to, duration, easing, callback) {
// figure out if this is moz || IE because they use documentElement
element = (typeof(element) === 'undefined' ? ((navigator.userAgent.indexOf('Firefox') != -1 || navigator.userAgent.indexOf('MSIE') != -1) ? document.documentElement : document.body): element);
easing = (typeof(easing) !== 'function' ? Math.easeInOutQuad: easing);
duration = (typeof(duration) === 'undefined' ? 500: duration);
var start = element.scrollTop,
change = to - start,
currentTime = 0,
frames = 0,
lastTime = Date.now();
var animateScroll = function(){
// increment the time
currentTime = Date.now() - lastTime;
// find the value with the quadratic in-out easing function
var val = easing(currentTime, start, change, duration);
// move the document.body
element.scrollTop = val;
// do the animation unless its over
if(currentTime < duration) {
frames++;
requestAnimFrame(animateScroll);
} else {
if (callback && typeof(callback) === 'function') {
// the animation is done so lets callback
callback();
}
console.debug("[scrollTo] drew " + frames.toString(10) + " frames in " + (Date.now() - startTime).toString(10) + "ms");
}
};
animateScroll();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment