Skip to content

Instantly share code, notes, and snippets.

@ardeshireshghi
Created December 11, 2016 15:52
Show Gist options
  • Save ardeshireshghi/aa58b772e539b4efb6f8d8a25633d580 to your computer and use it in GitHub Desktop.
Save ardeshireshghi/aa58b772e539b4efb6f8d8a25633d580 to your computer and use it in GitHub Desktop.
function animateScrollToEl(targetEl, duration, easing) {
var easings = {
easeInOutExpo: function (t, b, c, d) {
t /= d/2;
if (t < 1) return c/2 * Math.pow( 2, 10 * (t - 1) ) + b;
t--;
return c/2 * ( -Math.pow( 2, -10 * t) + 2 ) + b;
}
};
var pageScrollYOffset= function() {
return Math.max(
window.pageYOffset,
document.documentElement.scrollTop,
document.body.scrollTop);
};
var requestAnimFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
setTimeout(callback, 1000 / 60);
};
duration = duration || 300;
easing = easing || 'easeInOutExpo';
var initialScrollTop = pageScrollYOffset();
var targetElOffsetTop = initialScrollTop + targetEl.getBoundingClientRect().top;
var offsetDiff = targetElOffsetTop - initialScrollTop;
var timeElapsed = 0;
var startTime = Date.now();
var animate = function() {
timeElapsed = Date.now() - startTime;
var currentScrollTop = easings[easing](timeElapsed, initialScrollTop, offsetDiff, duration);
if (timeElapsed <= duration) {
window.scrollTo(0, currentScrollTop);
requestAnimFrame(animate);
}
};
requestAnimFrame(animate);
}
if (exports) {
module.exports = animateScrollToEl;
} else {
window.animateScrollToEl = animateScrollToEl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment