My goal is to start a number counter from 0 to 100 as soon as the number enters the viewport.
With my current solution I have two issues:
- The number jumps back to 0 once it finished counting to 100
- The counting doesn’t “start” when the element enters the viewport but rather depends on the scroll state. It counts the further the user scrolls.
Here my code:
css:
.number {
animation-name: counter;
animation-duration: 5s;
animation-timing-function: ease-in-out;
animation-delay: 0s;
animation-direction: normal;
animation-iteration-count: 1;
animation-fill-mode: none;
animation-timeline: view();
counter-reset: num var(--num);
font: 800 40px system-ui;
padding: 2rem;
}
.number::after {
content: counter(num);
}
@keyframes counter {
from {
--num: 0;
}
to {
--num: 100;
}
}
html:
<span class="number"></span>