Skip to content

codegem-insta/react_scroll

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

React scroll progress made easy

ProgressBar component

function ProgressBar() {
  const percentScroll = useScroll();

  return (
    <div
      style={{
        width: percentScroll + "%",
        position: "fixed",
        backgroundColor: "red",
        height: "16px",
        zIndex: 10,
      }}
    />
  );
}

Custom scroll hook

This hook adds an event listener that is triggered any time we scroll and calls a scroll function

function useScroll() {
    const [percentageScrolled, setPercentageScrolled] = useState(0);

    useEffect(() => {
        const scroll = () => setPercentageScrolled(calculateScrollPercentage());

        document.addEventListener('scroll', scroll);

        return () => document.removeEventListener('scroll', scroll);
    }, []);

    return percentageScrolled;
}

Calculate percentage scrolled

This function returns the percentage scrolled down

function calculateScrollPercentage() {
    const scrollOffset = window.pageYOffset;
    const scrollPercentage = Math.floor(scrollOffset / totalPageHeight() * 100);

    return scrollPercentage;
}

function totalPageHeight() {
    const windowHeight = window.innerHeight;
    const docHeight = document.documentElement.scrollHeight;

    return docHeight - windowHeight;
}

About

A demo on how to build a progress bar that grows as the user scrolls across the page

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published