Created
November 17, 2015 11:53
-
-
Save mrtnbroder/7e640165bc6d8d89372b to your computer and use it in GitHub Desktop.
smoothScroll
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
| /** | |
| Smoothly scroll element to the given target (element.scrollTop) | |
| for the given duration | |
| Returns a promise that's fulfilled when done, or rejected if | |
| interrupted | |
| */ | |
| var smoothScroll = function(element, target, duration) { | |
| target = Math.round(target); | |
| duration = Math.round(duration); | |
| if (duration < 0) { | |
| return Promise.reject("bad duration"); | |
| } | |
| if (duration === 0) { | |
| element.scrollTop = target; | |
| return Promise.resolve(); | |
| } | |
| var start_time = Date.now(); | |
| var end_time = start_time + duration; | |
| var start_top = element.scrollTop; | |
| var distance = target - start_top; | |
| // based on http://en.wikipedia.org/wiki/Smoothstep | |
| var smooth_step = function(start, end, point) { | |
| if(point <= start) { return 0; } | |
| if(point >= end) { return 1; } | |
| var x = (point - start) / (end - start); // interpolation | |
| return x*x*(3 - 2*x); | |
| } | |
| return new Promise(function(resolve, reject) { | |
| // This is to keep track of where the element's scrollTop is | |
| // supposed to be, based on what we're doing | |
| var previous_top = element.scrollTop; | |
| // This is like a think function from a game loop | |
| var scroll_frame = function() { | |
| if(element.scrollTop != previous_top) { | |
| reject("interrupted"); | |
| return; | |
| } | |
| // set the scrollTop for this frame | |
| var now = Date.now(); | |
| var point = smooth_step(start_time, end_time, now); | |
| var frameTop = Math.round(start_top + (distance * point)); | |
| element.scrollTop = frameTop; | |
| // check if we're done! | |
| if(now >= end_time) { | |
| resolve(); | |
| return; | |
| } | |
| // If we were supposed to scroll but didn't, then we | |
| // probably hit the limit, so consider it done; not | |
| // interrupted. | |
| if(element.scrollTop === previous_top | |
| && element.scrollTop !== frameTop) { | |
| resolve(); | |
| return; | |
| } | |
| previous_top = element.scrollTop; | |
| // schedule next frame for execution | |
| requestAnimationFrame(scroll_frame); | |
| } | |
| // boostrap the animation process | |
| requestAnimationFrame(scroll_frame); | |
| }); | |
| } | |
| module.exports = smoothScroll |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment