-
-
Save nathansearles/94a322fc605b481b823f6b4c4074f1f8 to your computer and use it in GitHub Desktop.
a native scrollTo function in javascript that uses requestAnimationFrame and easing for animation
This file contains hidden or 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
// easing functions http://goo.gl/5HLl8 | |
Math.easeInOutQuad = function (t, b, c, d) { | |
//t = current time | |
//b = start value | |
//c = change in value | |
//d = duration | |
t /= d/2; | |
if (t < 1) { | |
return c/2*t*t + b | |
} | |
t--; | |
return -c/2 * (t*(t-2) - 1) + b; | |
}; | |
function scrollTo(element, to, duration) { | |
var start = element.scrollTop, | |
change = to - start, | |
currentTime = 0, | |
increment = 20; | |
var animateScroll = function(){ | |
// increment the time | |
currentTime += increment; | |
// find the value with the quadratic in-out easing function | |
var val = Math.easeInOutQuad(currentTime, start, change, duration); | |
// move the element | |
element.scrollTop = val; | |
// do the animation unless its over | |
if(currentTime < duration) { | |
setTimeout(animateScroll, increment); | |
} | |
}; | |
animateScroll(); | |
} | |
// scrollTo(document.body, 0, 500); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment