Skip to content

Instantly share code, notes, and snippets.

@reecelucas
Created September 27, 2018 09:50
Show Gist options
  • Save reecelucas/3f7cd4919008650ad035dc3a873ec30e to your computer and use it in GitHub Desktop.
Save reecelucas/3f7cd4919008650ad035dc3a873ec30e to your computer and use it in GitHub Desktop.
Scroll progress indicator in native JS
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