Code Example in HTML:
<button onclick="scrollToTop(1000);"></button>
1# JavaScript Function (linear scrolling):
function scrollToTopLinear(duration) {
if (document.scrollingElement.scrollTop === 0) return;
const totalScrollDistance = document.scrollingElement.scrollTop;
let scrollY = totalScrollDistance, oldTimestamp = null;
function step(newTimestamp) {
if (oldTimestamp !== null) {
scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = scrollY;
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
2# JavaScript Function (ease in and out scrolling):
function scrollToTopEase(duration) {
if (document.scrollingElement.scrollTop === 0) return;
const cosParameter = document.scrollingElement.scrollTop / 2;
let scrollCount = 0, oldTimestamp = null;
function step(newTimestamp) {
if (oldTimestamp !== null) {
scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
/*
Explanation:
- pi is the length/end point of the cosinus intervall
- newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
For more information see the link provided above.
*/
Note:
- Duration is in milliseconds (1000ms = 1s)
- The second script utilizes the cosine function for smooth scrolling.
3# Explore a scrolling library on Github