Skip to content

Commit 025a274

Browse files
committed
Use scrollRatio as a basis
1 parent 502fc5b commit 025a274

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

example/components/chakra-boxes.tsx

+12-12
Original file line numberDiff line numberDiff line change
@@ -7,35 +7,35 @@ const indentations = Array.from({ length: numBoxes }, (_, i) => i * 100);
77
const ChakraBoxes = () => {
88
const [highlightedIndex, setHighlightedIndex] = useState(0);
99
const [offset, setOffset] = useState(0);
10-
const [scrollPercentage, setScrollPercentage] = useState(0);
10+
const [scrollRatio, setScrollRatio] = useState(0); // Save ratio instead of percentage
1111

12-
const calculateScrollPercentage = () => {
12+
const calculateScrollRatio = () => {
1313
const scrollTop = window.scrollY;
14-
const docHeight = document.documentElement.scrollHeight;
15-
const winHeight = window.innerHeight;
14+
const documentHeight = document.documentElement.scrollHeight;
15+
const windowHeight = window.innerHeight;
1616

17-
const totalScrollable = docHeight - winHeight;
18-
const scrolled = (scrollTop / totalScrollable) * 100;
17+
const totalScrollable = documentHeight - windowHeight;
18+
const ratio = scrollTop / totalScrollable;
1919

20-
setScrollPercentage(scrolled);
20+
setScrollRatio(ratio);
2121

22-
const calculatedIndex = Math.round((scrolled / 100) * (numBoxes - 1));
22+
const calculatedIndex = Math.round(ratio * (numBoxes - 1));
2323
setHighlightedIndex(calculatedIndex);
2424
setOffset(indentations[calculatedIndex]);
2525
};
2626

2727
useEffect(() => {
28-
calculateScrollPercentage();
29-
window.addEventListener('scroll', calculateScrollPercentage);
28+
calculateScrollRatio();
29+
window.addEventListener('scroll', calculateScrollRatio);
3030
return () => {
31-
window.removeEventListener('scroll', calculateScrollPercentage);
31+
window.removeEventListener('scroll', calculateScrollRatio);
3232
};
3333
}, [numBoxes]);
3434

3535
return (
3636
<Box overflowX={'hidden'}>
3737
<Text fontFamily="monospace" position="fixed" top={0} right={0} p={4} fontSize="lg" zIndex={1}>
38-
Scroll Percentage: {scrollPercentage.toFixed(2).padStart(5, '0')}%
38+
Scroll Percentage: {(scrollRatio*100).toFixed(2).padStart(5, '0')}%
3939
</Text>
4040
<Box
4141
marginLeft={`${-offset}px`}

0 commit comments

Comments
 (0)