< Back

useScrollbarPercentage React Hook


Solution:

Returns the percentage of the scrollbar.

Copy ✂️
/** * useScrollbarPercentage hook * @description Returns the percentage of the scrollbar * @returns {number} scrollbarPercentage * * @example * const {scrollbarPercentage} = useScrollbarPercentage(); * console.log(scrollbarPercentage); */ import {useEffect, useState} from "react"; function useScrollbarPercentage() { const [scrollbarPercentage, setScrollbarPercentage] = useState(0); useEffect(() => { const handleScroll = () => { const scrollHeight = document.documentElement.scrollHeight; const scrollPosition = document.documentElement.scrollTop || document.body.scrollTop; setScrollbarPercentage((scrollPosition / scrollHeight) * 100); }; window.addEventListener('scroll', handleScroll); return () => { window.removeEventListener('scroll', handleScroll); }; }, []); return {scrollbarPercentage}; } export default useScrollbarPercentage;
🚀 Enjoy!