Skip to content

Instantly share code, notes, and snippets.

@blackChef
Created September 3, 2019 14:53
Show Gist options
  • Save blackChef/f0d21255427b2dae6a3f644a3e02ba69 to your computer and use it in GitHub Desktop.
Save blackChef/f0d21255427b2dae6a3f644a3e02ba69 to your computer and use it in GitHub Desktop.
AnimateScrollTo
const nativeScrollTo = function(to) {
window.scrollTo({
top: to,
left: 0,
behavior: 'smooth',
});
};
const customScrollTo = function(to, duration = 1000) {
const element = document.scrollingElement || document.documentElement,
start = element.scrollTop,
change = to - start,
startDate = +new Date(),
// t = current time
// b = start value
// c = change in value
// d = duration
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;
},
animateScroll = function() {
const currentDate = +new Date();
const currentTime = currentDate - startDate;
element.scrollTop = parseInt(easeInOutQuad(currentTime, start, change, duration));
if(currentTime < duration) {
requestAnimationFrame(animateScroll);
}
else {
element.scrollTop = to;
}
};
animateScroll();
};
const animateScrollTo = function(to) {
// iOS doesn't support `behavior: smooth`
if (window.__isIOS__) {
return customScrollTo(to);
}
nativeScrollTo(to);
};
export default animateScrollTo;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment