Created
July 26, 2019 22:39
-
-
Save devxom/53bd13ab66f6dcd4450324a1feca2ab6 to your computer and use it in GitHub Desktop.
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 = (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 = (t, b, c, d) => { | |
const tc = (t/=d)*t*t; | |
return b+c*(tc); | |
}; | |
Math.inOutQuintic = (t, b, c, d) => { | |
const ts = (t/=d)*t; | |
const tc = ts*t; | |
return b+c*(6*tc*ts + -15*ts*ts + 10*tc); | |
}; | |
// requestAnimationFrame for Smart Animating http://goo.gl/sx5sts | |
const requestAnimFrame = (() => window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || (callback => { window.setTimeout(callback, 1000 / 60); }))(); | |
function scrollTo(to, callback, duration) { | |
// because it's so fucking difficult to detect the scrolling element, just move them all | |
function move(amount) { | |
document.documentElement.scrollTop = amount; | |
document.body.parentNode.scrollTop = amount; | |
document.body.scrollTop = amount; | |
} | |
function position() { | |
return document.documentElement.scrollTop || document.body.scrollTop || document.body.scrollTop || window.pageYOffset; | |
} | |
const start = position(); | |
const change = to - start; | |
let currentTime = 0; | |
const increment = 20; | |
duration = (typeof(duration) === 'undefined') ? 500 : duration; | |
const animateScroll = () => { | |
// increment the time | |
currentTime += increment; | |
// find the value with the quadratic in-out easing function | |
const val = Math.easeInOutQuad(currentTime, start, change, duration); | |
// move the document.body | |
move(val); | |
// do the animation unless its over | |
if (currentTime < duration) { | |
requestAnimFrame(animateScroll); | |
} else { | |
if (callback && typeof(callback) === 'function') { | |
// the animation is done so lets callback | |
callback(); | |
} | |
} | |
}; | |
animateScroll(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment