-
Notifications
You must be signed in to change notification settings - Fork 0
/
CustomScrollbar.tsx
58 lines (47 loc) · 1.61 KB
/
CustomScrollbar.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"use client";
import { useEffect, useRef, useState } from "react";
export default function CustomScrollbar() {
const [scrollbarHeight, setScrollbarHeight] = useState(0);
const [scrollbarTop, setScrollbarTop] = useState(0);
const [isVisible, setIsVisible] = useState(false);
const timeoutRef = useRef<NodeJS.Timeout>();
useEffect(() => {
const updateScrollbar = () => {
const windowHeight = window.innerHeight;
const documentHeight = document.documentElement.scrollHeight;
const scrollTop = window.scrollY;
const scrollbarHeight = (windowHeight / documentHeight) * windowHeight;
const scrollbarTop = (scrollTop / documentHeight) * windowHeight;
setScrollbarHeight(scrollbarHeight);
setScrollbarTop(scrollbarTop);
setIsVisible(true);
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(() => {
setIsVisible(false);
}, 1000);
};
window.addEventListener("scroll", updateScrollbar);
window.addEventListener("resize", updateScrollbar);
updateScrollbar();
return () => {
window.removeEventListener("scroll", updateScrollbar);
window.removeEventListener("resize", updateScrollbar);
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, []);
return (
<div className={`custom-scrollbar ${isVisible ? "visible" : ""}`}>
<div
className="custom-scrollbar-thumb"
style={{
height: `${scrollbarHeight}px`,
transform: `translateY(${scrollbarTop}px)`,
}}
/>
</div>
);
}