Created
July 11, 2019 19:15
-
-
Save pierrenel/b7c362a7273b379f2f95ad66b8ff4a87 to your computer and use it in GitHub Desktop.
useScrollProgress.js
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
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