Skip to content

Instantly share code, notes, and snippets.

@jasonwarta
Created January 12, 2018 00:30
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 jasonwarta/defcf41739ea6da1f8015ac596a0acfe to your computer and use it in GitHub Desktop.
Save jasonwarta/defcf41739ea6da1f8015ac596a0acfe to your computer and use it in GitHub Desktop.
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function smoothScrollToTop(elemId) {
const speed = 1000; //ms
let targetY = document.querySelector(`#${elemId}`).offsetTop;
let curPos = window.scrollY;
let steps = 100;
let calcPixelStep = (targetY - curPos)/steps;
let timeDelay = speed/steps;
let actualPixelStep = Math.floor(calcPixelStep);
let remainder = (targetY - curPos) - (actualPixelStep * steps)
console.log(actualPixelStep, remainder);
for(let i = 0; i <= steps; i++) {
window.scrollBy(0,actualPixelStep);
await sleep(timeDelay);
}
window.scrollBy(0,remainder);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment