Created
December 11, 2016 15:52
-
-
Save ardeshireshghi/aa58b772e539b4efb6f8d8a25633d580 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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