-
-
Save origamid/79ec81fa835e16ff754eb1e5fbb0c047 to your computer and use it in GitHub Desktop.
Smooth Scroll Animation - JavaScript
This file contains 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
/** | |
* Smooth scroll animation | |
* @param {int} endX: destination x coordinate | |
* @param {int} endY: destination y coordinate | |
* @param {int} duration: animation duration in ms | |
*/ | |
function smoothScrollTo(endX, endY, duration) { | |
const startX = window.scrollX || window.pageXOffset; | |
const startY = window.scrollY || window.pageYOffset; | |
const distanceX = endX - startX; | |
const distanceY = endY - startY; | |
const startTime = new Date().getTime(); | |
duration = typeof duration !== 'undefined' ? duration : 400; | |
// Easing function | |
const easeInOutQuart = (time, from, distance, duration) => { | |
if ((time /= duration / 2) < 1) return distance / 2 * time * time * time * time + from; | |
return -distance / 2 * ((time -= 2) * time * time * time - 2) + from; | |
}; | |
const timer = setInterval(() => { | |
const time = new Date().getTime() - startTime; | |
const newX = easeInOutQuart(time, startX, distanceX, duration); | |
const newY = easeInOutQuart(time, startY, distanceY, duration); | |
if (time >= duration) { | |
clearInterval(timer); | |
} | |
window.scroll(newX, newY); | |
}, 1000 / 60); // 60 fps | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment