react-scroll-progress-read
Version:
Progress Bar for show position of scroll page
2 lines (1 loc) • 1.19 kB
JavaScript
import{memo as e,useState as t,useEffect as n,createElement as o}from"react";const r=(e,t=5)=>Number(e.toFixed(t)),l=e=>window.requestAnimationFrame(e),c=({backgroundColor:e,height:c,barColor:d,target:u,refTarget:m})=>{let i;const[s,a]=t("0%");n(()=>(i=u?document.getElementById(u):null,g(),window.addEventListener("scroll",g),()=>window.removeEventListener("scroll",g)),[]);const g=()=>{const e=m?m.current:i||null;let t=0,n=0;const o=(()=>{let e=0;return document.documentElement&&null!==document.documentElement&&(e=document.documentElement.scrollTop),window.pageYOffset||e})();e?(t=(e=>{let t=e.offsetHeight;const n=window.getComputedStyle(e),{marginBottom:o,marginTop:r}=n;return o&&r&&(t+=parseInt(r,10)+parseInt(o,10)),t})(e)-document.documentElement.clientHeight,n=e.offsetTop):t=document.documentElement.scrollHeight-document.documentElement.clientHeight;const c=r(o-n);if(o<n)return l(()=>a("0%"));if(c>t)return l(()=>a("100%"));const d=r(c/t),u=`${r(100*d)}%`;l(()=>a(u))};return o("div",{style:{background:e,height:c,width:"100vw"}},o("div",{style:{height:c,background:d,width:s}}))};c.defaultProps={backgroundColor:"#CCC",height:"5px",barColor:"#e91e63"};export default e(c);