Skip to content

Instantly share code, notes, and snippets.

@pierrenel
Created July 11, 2019 19:15
Show Gist options
  • Save pierrenel/b7c362a7273b379f2f95ad66b8ff4a87 to your computer and use it in GitHub Desktop.
Save pierrenel/b7c362a7273b379f2f95ad66b8ff4a87 to your computer and use it in GitHub Desktop.
useScrollProgress.js
import { useEffect, useState } from "react";
export default function useScrollProgress() {
const [width, setWidth] = useState(0);
useEffect(() => {
const onScroll = () => {
const {
scrollHeight,
clientHeight,
scrollTop
} = document.documentElement;
const winScroll = document.body.scrollTop || scrollTop;
const height = scrollHeight - clientHeight;
const scrolled = (winScroll / height) * 100;
return setWidth(scrolled);
};
window.addEventListener("scroll", onScroll);
return () => window.removeEventListener("scroll", onScroll);
}, []);
return width;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment