Code
document.addEventListener('DOMContentLoaded', () => {
const counters = document.querySelectorAll('.stat-item h2');
const duration = 2000; // Total animation duration in milliseconds
const updateCount = (counter) => {
const target = +counter.getAttribute('data-target');
const count = +counter.innerText;
console.log(`Updating counter from ${count} to ${target}`); // Debugging message
// Calculate increment with a minimum step for small numbers
const increment = target / (duration / 50);
const step = target < 20 ? 0.1 : increment; // Use smaller step for small numbers
if (count < target) {
counter.innerText = Math.min(target, Math.ceil(count + step));
setTimeout(() => updateCount(counter), 50);
} else {
counter.innerText = target;
console.log(`Counter reached target ${target}`); // Debugging message
localStorage.setItem(counter.getAttribute('data-target'), target); // Store the final value
}
};
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const counter = entry.target;
const storedValue = localStorage.getItem(counter.getAttribute('data-target'));
if (storedValue) {
counter.innerText = storedValue; // Set the stored value
} else {
console.log(`Starting animation for counter with target ${counter.getAttribute('data-target')}`); // Debugging message
counter.innerText = '0'; // Ensure the counter starts from 0
updateCount(counter);
}
observer.unobserve(counter); // Stop observing once the animation starts or value is set
}
});
}, { threshold: 1 });
counters.forEach(counter => {
observer.observe(counter);
});
});
https://happyfeelings.co.uk