Skip to content

Instantly share code, notes, and snippets.

@carlosascari
Created May 24, 2016 22:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlosascari/ccb49597bf6a4ba41325060711a8e22d to your computer and use it in GitHub Desktop.
Save carlosascari/ccb49597bf6a4ba41325060711a8e22d to your computer and use it in GitHub Desktop.
Basic automatic scroller with requestAnimationFrame
// @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