Issue with javascript code
Posted: 19 Jan 2025, 05:48
Hi. I made some adjustments on my website and added some animation numbers. However everything works fine when first time the site is visited, but when clicking on any page on the website and coming back again on home page, the numbers are shown 0 for some reason. Any ideas what adjustments should I make?
Link:
https://happyfeelings.co.uk
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