Skip to content

Commit 8b88467

Browse files
committed
Add scroll percentage calculation
1 parent cfa56ed commit 8b88467

File tree

1 file changed

+21
-7
lines changed

1 file changed

+21
-7
lines changed

example/components/chakra-boxes.tsx

+21-7
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
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";
43
import { motion } from "framer-motion";
54

65
const MotionBox = motion(Box as any);
@@ -11,6 +10,7 @@ const indentations = Array.from({ length: numBoxes }, (_, i) => i * 100);
1110
const ChakraBoxes = () => {
1211
const [highlightedIndex, setHighlightedIndex] = useState(null); // Index of the box in the center
1312
const [offset, setOffset] = useState(0);
13+
const [scrollPercentage, setScrollPercentage] = useState(0); // State for scroll percentage
1414
const boxRefs = useRef([]); // Ref array to hold references to each box
1515
const canvasRef = useRef();
1616

@@ -41,34 +41,48 @@ const ChakraBoxes = () => {
4141
setOffset(indentations[closestIndex]);
4242
};
4343

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+
4455
useEffect(() => {
4556
// Call the function initially and on scroll
4657
calculateClosestBoxToCenter();
58+
calculateScrollPercentage();
59+
4760
window.addEventListener('scroll', calculateClosestBoxToCenter);
61+
window.addEventListener('scroll', calculateScrollPercentage);
4862

4963
// Cleanup the scroll event listener on component unmount
5064
return () => {
5165
window.removeEventListener('scroll', calculateClosestBoxToCenter);
66+
window.removeEventListener('scroll', calculateScrollPercentage);
5267
};
5368
}, [numBoxes]);
5469

5570
return (
5671
<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>
5775
<MotionBox
5876
ref={canvasRef}
5977
animate={{ marginLeft: `${-offset}px` }} // Animation on margin change
6078
transition={{
6179
duration: 0.4,
62-
// ease: "easeIn", // Built-in easing function
6380
ease: "easeOut", // Built-in easing function
64-
// ease: "linear", // Built-in easing function
6581
}} // Adjust the transition duration
6682
paddingTop={`50vh`}
6783
paddingBottom={`50vh`}
6884
>
69-
<VStack
70-
spacing={4}
71-
>
85+
<VStack spacing={4}>
7286
{Array.from({ length: numBoxes }).map((_, index) => (
7387
<Box
7488
key={index}

0 commit comments

Comments
 (0)