Created
March 19, 2013 22:21
-
-
Save bjrn/5200670 to your computer and use it in GitHub Desktop.
scrollToPos ( yPos, opts, after );
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
/* | |
Props to emilejs for nice handling of easing and callbacks. | |
TODO: | |
opts.el - calculate positions | |
(in our case, we do that outside of this function already) | |
IE8+ ... el = (typeof el === 'string') ? document.querySelector(el) : el | |
use window.requestAnimationFrame instead of setInterval | |
- with polyfill of course | |
*/ | |
function scrollToPos(yPos, opts, after){ | |
var opts = opts || {}, | |
duration = opts.duration || 600, | |
threshold = opts.threshold || 100, | |
easing = opts.easing || function(pos){return(-Math.cos(pos*Math.PI)/2)+0.5;}, | |
startTime = +new Date, | |
finish = startTime + duration, | |
startY = isNaN(window.pageYOffset) ? document.documentElement.scrollTop : window.pageYOffset, | |
distance = yPos - startY; | |
if (Math.abs(distance) < threshold) { | |
window.scrollTo(0, yPos); | |
return; | |
} | |
var interval = setInterval(function(){ | |
var time = +new Date, | |
pos = time > finish ? 1 : (time-startTime) / duration; | |
window.scrollTo(0, startY + distance * easing(pos)); | |
if(time > finish) { | |
clearInterval(interval); | |
opts.after && opts.after(); | |
after && setTimeout(after,1); | |
} | |
}, 15); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment