Skip to content

Instantly share code, notes, and snippets.

@clemlatz
Created September 6, 2017 08:56
Show Gist options
  • Save clemlatz/4c8819420ce5237aeaf338339df25c32 to your computer and use it in GitHub Desktop.
Save clemlatz/4c8819420ce5237aeaf338339df25c32 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