@@ -7,35 +7,35 @@ const indentations = Array.from({ length: numBoxes }, (_, i) => i * 100);
7
7
const ChakraBoxes = ( ) => {
8
8
const [ highlightedIndex , setHighlightedIndex ] = useState ( 0 ) ;
9
9
const [ offset , setOffset ] = useState ( 0 ) ;
10
- const [ scrollPercentage , setScrollPercentage ] = useState ( 0 ) ;
10
+ const [ scrollRatio , setScrollRatio ] = useState ( 0 ) ; // Save ratio instead of percentage
11
11
12
- const calculateScrollPercentage = ( ) => {
12
+ const calculateScrollRatio = ( ) => {
13
13
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 ;
16
16
17
- const totalScrollable = docHeight - winHeight ;
18
- const scrolled = ( scrollTop / totalScrollable ) * 100 ;
17
+ const totalScrollable = documentHeight - windowHeight ;
18
+ const ratio = scrollTop / totalScrollable ;
19
19
20
- setScrollPercentage ( scrolled ) ;
20
+ setScrollRatio ( ratio ) ;
21
21
22
- const calculatedIndex = Math . round ( ( scrolled / 100 ) * ( numBoxes - 1 ) ) ;
22
+ const calculatedIndex = Math . round ( ratio * ( numBoxes - 1 ) ) ;
23
23
setHighlightedIndex ( calculatedIndex ) ;
24
24
setOffset ( indentations [ calculatedIndex ] ) ;
25
25
} ;
26
26
27
27
useEffect ( ( ) => {
28
- calculateScrollPercentage ( ) ;
29
- window . addEventListener ( 'scroll' , calculateScrollPercentage ) ;
28
+ calculateScrollRatio ( ) ;
29
+ window . addEventListener ( 'scroll' , calculateScrollRatio ) ;
30
30
return ( ) => {
31
- window . removeEventListener ( 'scroll' , calculateScrollPercentage ) ;
31
+ window . removeEventListener ( 'scroll' , calculateScrollRatio ) ;
32
32
} ;
33
33
} , [ numBoxes ] ) ;
34
34
35
35
return (
36
36
< Box overflowX = { 'hidden' } >
37
37
< 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' ) } %
39
39
</ Text >
40
40
< Box
41
41
marginLeft = { `${ - offset } px` }
0 commit comments