Created
March 3, 2023 15:28
-
-
Save julkue/80dc53f4ec7bde507f5262d3e7bcbba7 to your computer and use it in GitHub Desktop.
Scroll to target with configurable duration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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