Skip to content

Instantly share code, notes, and snippets.

@origamid
Forked from clemlatz/smooth-scroll.js
Last active July 21, 2022 15:23
Show Gist options
  • Save origamid/79ec81fa835e16ff754eb1e5fbb0c047 to your computer and use it in GitHub Desktop.
Save origamid/79ec81fa835e16ff754eb1e5fbb0c047 to your computer and use it in GitHub Desktop.
Smooth Scroll Animation - JavaScript
/**
* 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