Skip to content

Instantly share code, notes, and snippets.

@dmitryfry
Created September 28, 2017 07:55
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 dmitryfry/66e652fdc249d621c53721434e0fe618 to your computer and use it in GitHub Desktop.
Save dmitryfry/66e652fdc249d621c53721434e0fe618 to your computer and use it in GitHub Desktop.
function scrollToTop(scrollDuration) {
var cosParameter = window.scrollY / 2,
scrollCount = 0,
oldTimestamp = performance.now();
function step (newTimestamp) {
scrollCount += Math.PI / (scrollDuration / (newTimestamp - oldTimestamp));
if (scrollCount >= Math.PI) window.scrollTo(0, 0);
if (window.scrollY === 0) return;
window.scrollTo(0, Math.round(cosParameter + cosParameter * Math.cos(scrollCount)));
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
@dmitryfry
Copy link
Author

Explanations:
- pi is the length/end point of the cosinus intervall (see above)
- newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
(for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
- newTimestamp - oldTimestamp equals the duration

  a * cos (bx + c) + d                      | c translates along the x axis = 0
= a * cos (bx) + d                          | d translates along the y axis = 1 -> only positive y values
= a * cos (bx) + 1                          | a stretches along the y axis = cosParameter = window.scrollY / 2
= cosParameter + cosParameter * (cos bx)    | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
= cosParameter + cosParameter * (cos scrollCount * x)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment