Created
October 12, 2017 13:51
-
-
Save AudyOdi/e78a7a20ed0466d729bc26ee4d31efa4 to your computer and use it in GitHub Desktop.
updated scrollTo from marketwurks
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
| // @flow | |
| let scrollAnimationTimeout: ?mixed; | |
| function easeInOutQuad(t: number, b: number, c: number, d: number) { | |
| t /= d / 2; | |
| if (t < 1) { | |
| return c / 2 * t * t + b; | |
| } | |
| t--; | |
| return -c / 2 * (t * (t - 2) - 1) + b; | |
| } | |
| export default function scrollTo( | |
| scrollNode: Element, | |
| to: number, | |
| duration: number, | |
| ) { | |
| let scrollTop = scrollNode.scrollTop; | |
| let scrollLeft = scrollNode.scrollLeft; | |
| let change = to - scrollTop; | |
| let startTime = Date.now(); | |
| // if currently doing an animation, cancel it | |
| clearTimeout(scrollAnimationTimeout); | |
| let animateScroll = () => { | |
| let currentTime = Date.now() - startTime; | |
| let newScrollTop; | |
| if (currentTime > duration) { | |
| newScrollTop = to; | |
| } else { | |
| newScrollTop = easeInOutQuad(currentTime, scrollTop, change, duration); | |
| } | |
| // $FlowFixMe | |
| scrollNode.scrollTo(scrollLeft, newScrollTop); | |
| if (currentTime < duration) { | |
| scrollAnimationTimeout = requestAnimationFrame(animateScroll); | |
| } | |
| }; | |
| scrollAnimationTimeout = requestAnimationFrame(animateScroll); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment