Skip to content

Instantly share code, notes, and snippets.

@avitorio
Created August 17, 2023 00:15
Show Gist options
  • Save avitorio/1a35ae25ac7a433289db9aae6115803d to your computer and use it in GitHub Desktop.
Save avitorio/1a35ae25ac7a433289db9aae6115803d to your computer and use it in GitHub Desktop.
Smooth site scroll
function smoothScrollByViewports(herodelay, viewports, duration) {
// Hide scrollbar
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = `html::-webkit-scrollbar { width: 0px; }`;
document.getElementsByTagName('head')[0].appendChild(style);
var start = null;
var initialScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
var distanceToScroll = window.innerHeight * viewports;
setTimeout(() => {
function step(timestamp) {
if (start === null) {
start = timestamp;
}
var elapsed = timestamp - start;
var progress = Math.min(elapsed / duration, 1);
var scrollAmount = initialScrollTop + distanceToScroll * progress;
window.scrollTo(0, scrollAmount);
if (progress < 1) {
window.requestAnimationFrame(step);
}
}
window.requestAnimationFrame(step);}, herodelay * 1000);
}
// Stay on hero for 3 seconds, scroll down by 5 viewports smoothly over 10 seconds (adjust accordingly)
smoothScrollByViewports(3, 5, 10000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment