1
1
import React , { useState , useEffect , useRef } from "react" ;
2
- import { Box , Input , VStack } from "@chakra-ui/react" ;
3
-
2
+ import { Box , Input , VStack , Text } from "@chakra-ui/react" ;
4
3
import { motion } from "framer-motion" ;
5
4
6
5
const MotionBox = motion ( Box as any ) ;
@@ -11,6 +10,7 @@ const indentations = Array.from({ length: numBoxes }, (_, i) => i * 100);
11
10
const ChakraBoxes = ( ) => {
12
11
const [ highlightedIndex , setHighlightedIndex ] = useState ( null ) ; // Index of the box in the center
13
12
const [ offset , setOffset ] = useState ( 0 ) ;
13
+ const [ scrollPercentage , setScrollPercentage ] = useState ( 0 ) ; // State for scroll percentage
14
14
const boxRefs = useRef ( [ ] ) ; // Ref array to hold references to each box
15
15
const canvasRef = useRef ( ) ;
16
16
@@ -41,34 +41,48 @@ const ChakraBoxes = () => {
41
41
setOffset ( indentations [ closestIndex ] ) ;
42
42
} ;
43
43
44
+ const calculateScrollPercentage = ( ) => {
45
+ const scrollTop = window . scrollY ; // Distance from the top
46
+ const docHeight = document . documentElement . scrollHeight ; // Full document height
47
+ const winHeight = window . innerHeight ; // Visible window height
48
+
49
+ const totalScrollable = docHeight - winHeight ;
50
+ const scrolled = ( scrollTop / totalScrollable ) * 100 ;
51
+
52
+ setScrollPercentage ( scrolled ) ;
53
+ } ;
54
+
44
55
useEffect ( ( ) => {
45
56
// Call the function initially and on scroll
46
57
calculateClosestBoxToCenter ( ) ;
58
+ calculateScrollPercentage ( ) ;
59
+
47
60
window . addEventListener ( 'scroll' , calculateClosestBoxToCenter ) ;
61
+ window . addEventListener ( 'scroll' , calculateScrollPercentage ) ;
48
62
49
63
// Cleanup the scroll event listener on component unmount
50
64
return ( ) => {
51
65
window . removeEventListener ( 'scroll' , calculateClosestBoxToCenter ) ;
66
+ window . removeEventListener ( 'scroll' , calculateScrollPercentage ) ;
52
67
} ;
53
68
} , [ numBoxes ] ) ;
54
69
55
70
return (
56
71
< Box overflowX = { 'hidden' } >
72
+ < Text position = "fixed" top = { 0 } left = { 0 } p = { 4 } fontSize = "lg" bg = "white" zIndex = { 1 } >
73
+ Scroll Percentage: { scrollPercentage . toFixed ( 2 ) } %
74
+ </ Text >
57
75
< MotionBox
58
76
ref = { canvasRef }
59
77
animate = { { marginLeft : `${ - offset } px` } } // Animation on margin change
60
78
transition = { {
61
79
duration : 0.4 ,
62
- // ease: "easeIn", // Built-in easing function
63
80
ease : "easeOut" , // Built-in easing function
64
- // ease: "linear", // Built-in easing function
65
81
} } // Adjust the transition duration
66
82
paddingTop = { `50vh` }
67
83
paddingBottom = { `50vh` }
68
84
>
69
- < VStack
70
- spacing = { 4 }
71
- >
85
+ < VStack spacing = { 4 } >
72
86
{ Array . from ( { length : numBoxes } ) . map ( ( _ , index ) => (
73
87
< Box
74
88
key = { index }
0 commit comments