Skip to content

Instantly share code, notes, and snippets.

@julkue
Created March 3, 2023 15:28
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 julkue/80dc53f4ec7bde507f5262d3e7bcbba7 to your computer and use it in GitHub Desktop.
Save julkue/80dc53f4ec7bde507f5262d3e7bcbba7 to your computer and use it in GitHub Desktop.
Scroll to target with configurable duration
// Source: https://htmldom.dev/scroll-to-an-element-smoothly/
const scrollToTarget = function (target, duration) {
const top = target.getBoundingClientRect().top;
const startPos = window.pageYOffset;
const diff = top;
let startTime = null;
let requestId;
const loop = function (currentTime) {
if (!startTime) {
startTime = currentTime;
}
// Elapsed time in miliseconds
const time = currentTime - startTime;
const percent = Math.min(time / duration, 1);
window.scrollTo(0, startPos + diff * percent);
if (time < duration) {
// Continue moving
requestId = window.requestAnimationFrame(loop);
} else {
window.cancelAnimationFrame(requestId);
}
};
requestId = window.requestAnimationFrame(loop);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment