Skip to content

Instantly share code, notes, and snippets.

@matdave
Created September 30, 2025 20:58
Show Gist options
  • Save matdave/f5f322fb2498d197354f596b13696560 to your computer and use it in GitHub Desktop.
Save matdave/f5f322fb2498d197354f596b13696560 to your computer and use it in GitHub Desktop.
Stats Counter
const statfigures = document.querySelectorAll('[data-stats]');
if (statfigures.length) {
statfigures.forEach((el) => {
const initialValue = el.innerText;
let statNumber = parseFloat(initialValue.replace(/[^0-9.]/g, ""));
console.info(statNumber);
el.innerText = "0";
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
updateStats(el, statNumber, initialValue);
}
});
}
);
observer.observe(el);
});
}
const updateStats = (el, stat, initialValue) => {
let initial = 1;
let adjust = Math.ceil(stat / 12) || 1;
let decimal = 0;
// test decimal place for stats
if (stat % 1 !== 0) {
initial = 0.1;
adjust = stat / 12;
decimal = 1;
}
const interval = setInterval(() => {
if (initial < stat) {
if (initial + adjust < stat) {
initial += adjust;
} else {
initial = stat;
}
const formatted = initial.toFixed(decimal);
// replace the initialValue with the formatted number
el.innerText = initialValue.replace(
stat.toString(),
formatted.toString(),
);
} else {
clearInterval(interval);
el.innerText = initialValue;
}
}, 100);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment