<div class="animated-counter text-center">
<p class="headline mb-3" data-animated-counter="{"from":0,"to":2000,"duration":2000,"suffix":"+","locale":"de","decimals":2,"unit":"ms"}">0</p>
</div>
<div class="animated-counter text-center">
<p class="headline mb-3" data-animated-counter="{{ json }}">{{ from }}</p>
</div>
{
"from": 0,
"to": 2000,
"duration": 2000,
"json": "{\"from\":0,\"to\":2000,\"duration\":2000,\"suffix\":\"+\",\"locale\":\"de\",\"decimals\":2,\"unit\":\"ms\"}",
"suffix": "+"
}
export const AnimatedCounter = (() => {
function easeOutCirc(x) {
return Math.sqrt(1 - Math.pow(x - 1, 2));
}
function observe(element) {
return new Promise(resolve => {
const observer = new window.IntersectionObserver(([entry]) => {
if (entry.isIntersecting) {
resolve(element);
return
}
},
{ threshold: 1 }
);
const observable = observer.observe(element);
});
}
function count(counter) {
return new Promise((resolve) => {
const options = counter.dataset.animatedCounter && JSON.parse(counter.dataset.animatedCounter);
if (options) {
let duration = options.duration || 200;
let start = 0;
let end = 0;
let value = 0;
let begin = options.from;
let target = options.to;
let formatted = '';
function animate(timestamp) {
start = timestamp;
end = start + duration;
draw(timestamp);
}
function draw(now) {
if (now >= start + duration) {
formatted = options.locale
? new Intl.NumberFormat(options.locale, {
minimumFractionDigits: options.decimals || 0,
maximumFractionDigits: options.decimals || 0
}).format(options.to)
: options.to;
counter.innerText = `${formatted}${options.unit || ''}`;
resolve('done');
return;
}
let progress = (now - start) / duration;
let val = easeOutCirc(progress);
let value = begin + (target - begin) * val;
formatted = options.locale
? new Intl.NumberFormat(options.locale, {
minimumFractionDigits: options.decimals || 0,
maximumFractionDigits: options.decimals || 0
}).format(value)
: value;
counter.innerText = `${formatted}${options.unit || ''}`;
requestAnimationFrame(draw);
}
requestAnimationFrame(animate);
}
});
}
return (() => {
const counters = document.querySelectorAll('[data-animated-counter');
counters.forEach(async counter => {
const counting = await observe(counter);
const done = await count(counter);
if (done) {
const options = counter.dataset.animatedCounter && JSON.parse(counter.dataset.animatedCounter);
if (options.suffix) {
const suffix = document.createElement('i');
suffix.innerHTML = options.suffix;
counter.appendChild(suffix);
}
}
});
})()
})();
export default AnimatedCounter;
.animated-counter {
}
No notes defined.