Skip to content

Instantly share code, notes, and snippets.

@jadark
Forked from clemlatz/smooth-scroll.js
Created October 8, 2018 04:57
Show Gist options
  • Save jadark/c90d5ba617d77c330c522cf7fdbccbf2 to your computer and use it in GitHub Desktop.
Save jadark/c90d5ba617d77c330c522cf7fdbccbf2 to your computer and use it in GitHub Desktop.
Simple smooth-scroll animation in pure/vanilla javascript
/**
* Smooth scroll animation
* @param {int} endX: destination x coordinate
* @param {int) endY: destination y coordinate
* @param {int} duration: animation duration in ms
*/
window.smoothScrollTo = function(endX, endY, duration) {
var startX = window.scrollX || window.pageXOffset,
startY = window.scrollY || window.pageYOffset,
distanceX = endX - startX,
distanceY = endY - startY,
startTime = new Date().getTime();
duration = typeof duration !== 'undefined' ? duration : 400;
// Easing function
var easeInOutQuart = function(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;
};
var timer = window.setInterval(function() {
var time = new Date().getTime() - startTime,
newX = easeInOutQuart(time, startX, distanceX, duration),
newY = easeInOutQuart(time, startY, distanceY, duration);
if (time >= duration) {
window.clearInterval(timer);
}
window.scrollTo(newX, newY);
}, 1000 / 60); // 60 fps
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment