Skip to content

Instantly share code, notes, and snippets.

@PanagiotisGeorgiadis
Created June 27, 2019 08:33
Show Gist options
  • Save PanagiotisGeorgiadis/28c4e4544683e3d5d05ce5bf38e95aca to your computer and use it in GitHub Desktop.
Save PanagiotisGeorgiadis/28c4e4544683e3d5d05ce5bf38e95aca to your computer and use it in GitHub Desktop.
Smooth scroll animation using the Ease In Quint function.
const scrollToElement = (id) => {
let duration = 1000;
let element = document.getElementById(id);
if (!element)
return;
let targetPosition = element.offsetTop;
let startPosition = window.pageYOffset;
let distance = targetPosition - startPosition;
let startTime = null;
const animate = (currentTime) => {
if (startTime === null) {
startTime = currentTime;
}
let timeElapsed = currentTime - startTime;
let run = easeInOutQuint(timeElapsed, startPosition, distance, duration);
window.scrollTo(0, run);
if (timeElapsed < duration) {
requestAnimationFrame(animate);
}
}
const easeInOutQuint = (t, b, c, d) => {
t /= d/2;
if (t < 1 ) {
return c/2*t*t*t*t*t + b;
}
t -= 2;
return c/2*(t*t*t*t*t + 2) + b;
}
requestAnimationFrame(animate);
}
// Example scrollToElement("elementId");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment