Created
March 9, 2014 15:46
-
-
Save marekhrabe/9449737 to your computer and use it in GitHub Desktop.
Animated scrolling without any dependency on libraries. If user scrolls when animation is running, scroll animation would be immediately canceled.
This file contains hidden or 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
window.requestAnimFrame = (function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(callback){window.setTimeout(callback,1000/60);};})(); | |
var easeInOutQuad = function (t, b, c, d) { | |
t /= d/2; | |
if (t < 1) return c/2*t*t + b; | |
t--; | |
return -c/2 * (t*(t-2) - 1) + b; | |
}; | |
var animatedScrollTo = function (element, to, duration) { | |
var start = element.scrollTop, | |
change = to - start, | |
animationStart = +new Date(); | |
var animating = true; | |
var lastpos = null; | |
var animateScroll = function() { | |
if (!animating) { | |
return; | |
} | |
requestAnimFrame(animateScroll); | |
var now = +new Date(); | |
var val = Math.floor(easeInOutQuad(now - animationStart, start, change, duration)); | |
if (lastpos) { | |
if (lastpos === element.scrollTop) { | |
lastpos = val; | |
element.scrollTop = val; | |
} else { | |
animating = false; | |
} | |
} else { | |
lastpos = val; | |
element.scrollTop = val; | |
} | |
if (now > animationStart + duration) { | |
element.scrollTop = to; | |
animating = false; | |
} | |
}; | |
requestAnimFrame(animateScroll); | |
}; |
This file contains hidden or 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
// scroll to top in 10 seconds | |
button.addEventListener('click', function () { | |
animatedScrollTo(document.body, 0, 10000); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment