Пример 1
function digitsCounter() {
// Обнуление
if (document.querySelectorAll("[data-digits-counter]").length) {
document.querySelectorAll("[data-digits-counter]").forEach((element) => {
element.dataset.digitsCounter = element.innerHTML;
element.innerHTML = `0`;
});
}
// Функция инициализации
function digitsCountersInit(digitsCountersItems) {
let digitsCounters = digitsCountersItems
? digitsCountersItems
: document.querySelectorAll("[data-digits-counter]");
if (digitsCounters.length) {
digitsCounters.forEach((digitsCounter) => {
digitsCountersAnimate(digitsCounter);
});
}
}
// Анимация
function digitsCountersAnimate(digitsCounter) {
let startTimestamp = null;
const duration = parseInt(digitsCounter.dataset.digitsCounterSpeed)
? parseInt(digitsCounter.dataset.digitsCounterSpeed)
: 1000;
const startValue = parseInt(digitsCounter.dataset.digitsCounter);
const startPosition = 0;
const step = (timestamp) => {
if (!startTimestamp) startTimestamp = timestamp;
const progress = Math.min((timestamp - startTimestamp) / duration, 1);
digitsCounter.innerHTML = Math.floor(progress * (startPosition + startValue));
if (progress < 1) {
window.requestAnimationFrame(step);
}
};
window.requestAnimationFrame(step);
}
//Вызов инициализации без действия
digitsCountersInit();
}
digitsCounter();
Пример 2
function animateCounter(element, attributeName) {
const value = parseInt(element.textContent);
const time = parseInt(element.getAttribute(attributeName)) || 1000;
let current = 0;
let start;
function updateCounter(timestamp) {
// !start ? start = timestamp : null
if (!start) start = timestamp;
const progress = timestamp - start;
const increment = value / time;
if (current < value) {
current += increment * (progress / 1000);
element.textContent = Math.floor(current);
requestAnimationFrame(updateCounter);
} else {
element.textContent = value;
}
}
requestAnimationFrame(updateCounter);
}
function setWidth(element) {
const width = element.offsetWidth;
element.style.minWidth = width + 4 + "px";
console.log(width);
return width;
}
window.onload = () => {
const counters = document.querySelectorAll("[data-counter]");
if (counters.length) {
counters.forEach(setWidth);
counters.forEach((element) => animateCounter(element, "data-counter"));
}
// document.querySelectorAll("[data-counter]").forEach(animateCounter)
};