Created
June 27, 2019 08:33
-
-
Save PanagiotisGeorgiadis/28c4e4544683e3d5d05ce5bf38e95aca to your computer and use it in GitHub Desktop.
Smooth scroll animation using the Ease In Quint function.
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
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