Skip to content

Commit 5d4908c

Browse files
committed
made scroll progress bar (on top of page)
1 parent 6c026f4 commit 5d4908c

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/app/components/navbar.tsx

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import useReadingProgress from '../hooks/useReadingProgress'
2+
3+
const Navbar = () => {
4+
const completion = useReadingProgress();
5+
6+
return (
7+
<nav className="py-0.5 sticky top-0">
8+
{/* <div className="flex items-center justify-between container mx-auto text-xl"></div> */}
9+
<div className="h-0.5 overflow-hidden">
10+
<span
11+
className="absolute bg-midnight-blue-600 dark:bg-midnight-blue-400 h-full w-full top-0 bottom-0"
12+
style={{ transform: `translateX(${completion - 100}%)` }}
13+
/>
14+
</div>
15+
</nav>
16+
)
17+
}
18+
19+
export default Navbar

src/app/hooks/useReadingProgress.tsx

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { useEffect, useState } from 'react'
2+
3+
const useReadingProgress = () => {
4+
const [completion, setCompletion] = useState(0);
5+
6+
useEffect(() => {
7+
const updateScrollCompletion = () => {
8+
const currentProgress = window.scrollY;
9+
const scrollHeight = document.body.scrollHeight - window.innerHeight;
10+
if (scrollHeight) {
11+
setCompletion(
12+
Number((currentProgress / scrollHeight).toFixed(2)) * 100
13+
);
14+
}
15+
}
16+
window.addEventListener('scroll', updateScrollCompletion);
17+
return () => {
18+
window.removeEventListener('scroll', updateScrollCompletion);
19+
}
20+
}, []);
21+
22+
return completion;
23+
}
24+
25+
export default useReadingProgress

0 commit comments

Comments
 (0)