Skip to content

Commit 64e1d5a

Browse files
authored
Merge pull request #93 from MichiganDataScienceTeam/feat/dynamic_fact
(bug) fix incremental only in view
2 parents 8e862c7 + 2010c03 commit 64e1d5a

File tree

1 file changed

+30
-13
lines changed

1 file changed

+30
-13
lines changed

pages/index.jsx

Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -169,23 +169,40 @@ import React, { useEffect } from "react";
169169
function Factbox({ fact, closer }) {
170170
useEffect(() => {
171171
const elements = document.querySelectorAll(".number");
172-
elements.forEach((element) => {
173-
const target = +element.getAttribute("data-target");
174-
const increment = target / 250; // Adjust this value to control the speed
175-
let count = 0;
176172

177-
const updateCount = () => {
178-
count += increment;
179-
if (count < target) {
180-
element.textContent = Math.ceil(count);
181-
requestAnimationFrame(updateCount);
182-
} else {
183-
element.textContent = target;
173+
const observer = new IntersectionObserver((entries) => {
174+
entries.forEach((entry) => {
175+
if (entry.isIntersecting) {
176+
const element = entry.target;
177+
const target = +element.getAttribute("data-target");
178+
const increment = target / 250; // Adjust this value to control the speed
179+
let count = 0;
180+
181+
const updateCount = () => {
182+
count += increment;
183+
if (count < target) {
184+
element.textContent = Math.ceil(count);
185+
requestAnimationFrame(updateCount);
186+
} else {
187+
element.textContent = target;
188+
}
189+
};
190+
191+
updateCount();
192+
observer.unobserve(element); // Stop observing once the animation starts
184193
}
185-
};
194+
});
195+
});
186196

187-
updateCount();
197+
elements.forEach((element) => {
198+
observer.observe(element);
188199
});
200+
201+
return () => {
202+
elements.forEach((element) => {
203+
observer.unobserve(element);
204+
});
205+
};
189206
}, []);
190207

191208
return (

0 commit comments

Comments
 (0)