Created
May 24, 2016 22:44
-
-
Save carlosascari/ccb49597bf6a4ba41325060711a8e22d to your computer and use it in GitHub Desktop.
Basic automatic scroller with requestAnimationFrame
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
// @todo https://miketaylr.com/posts/2014/11/document-body-scrolltop.html | |
let animReference = null; | |
function _start(loop) | |
{ | |
animReference = requestAnimationFrame(loop); | |
} | |
function _stop() | |
{ | |
if (animReference) | |
{ | |
cancelAnimationFrame(animReference); | |
animReference = null; | |
} | |
} | |
export default function EZScroller(scrollableElement, targetElement, duration=600) { | |
let _from = scrollableElement.scrollTop; | |
let _to = targetElement.offsetTop; | |
let _started_at = Date.now(); | |
function loop() | |
{ | |
let _step = Math.min(1, (Date.now() - _started_at) / duration); | |
scrollableElement.scrollTop = (_from + _step * (_to - _from)); | |
if (_step === 1) | |
{ | |
return _stop(); | |
} | |
_start(loop); | |
} | |
_stop(); | |
_start(loop); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment