Created
September 27, 2018 09:50
-
-
Save reecelucas/3f7cd4919008650ad035dc3a873ec30e to your computer and use it in GitHub Desktop.
Scroll progress indicator in native JS
This file contains 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
import debounce from "lodash/debounce"; | |
const getPageHeight = () => | |
Math.max( | |
document.body.scrollHeight, | |
document.body.offsetHeight, | |
document.documentElement.clientHeight, | |
document.documentElement.scrollHeight, | |
document.documentElement.offsetHeight | |
); | |
const progressBar = document.querySelector("[data-progress-bar]"); | |
let pageHeight = getPageHeight(); | |
let scrollY = window.pageYOffset; | |
let ticking = false; | |
const updateProgress = () => { | |
const width = scrollY / (pageHeight - window.innerHeight); | |
progressBar.style.width = `${width * 100}%`; | |
ticking = false; | |
}; | |
const onScroll = () => { | |
if (!ticking) { | |
ticking = true; | |
window.requestAnimationFrame(updateProgress); | |
scrollY = window.pageYOffset; | |
} | |
}; | |
const onResize = () => { | |
pageHeight = getPageHeight(); | |
}; | |
export default () => { | |
if (!progressBar) return; | |
window.addEventListener("scroll", onScroll); | |
window.addEventListener("resize", debounce(onResize, 200)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment