-
-
Save jadark/c90d5ba617d77c330c522cf7fdbccbf2 to your computer and use it in GitHub Desktop.
Simple smooth-scroll animation in pure/vanilla 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 | |
*/ | |
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