CSS Animation to Increment Counter
Asked Answered
T

1

9

I've been playing around with CSS counters lately and I wondered if it was possible to put them in a CSS animation loop and increment them. My code is fairly simple:

div {
    animation-name: anim;
    animation-duration: 0.5s;
    animation-iteration-count: 10;
    animation-fill-mode: forwards;
}

div:before {
    counter-increment: variable;
    content: counter(variable);
}

@keyframes anim {
    100% { counter-increment: variable; }
}
<div></div>

You can see the number goes up, but then it snaps back to 1. I assumed the animation-fill-mode: forwards would prevent that from happening, but I guess not.

Am I doing something wrong, or is this not possible with CSS counters?

Taut answered 6/11, 2017 at 15:21 Comment(3)
Just as an aside: CSS variables can be used us pseudo content. jsfiddle.net/Skateside/n153kuswGuayule
@JamesLong That's interesting! I was trying to increment an integer variable and it wouldn't show, but strings work instead. jsfiddle.net/d25j9vL3/16Taut
here is a solution for it though it's not very browser friendly yet. here is its codepenBaptiste
U
-4

It can be easily achieved using a simple script code, try this

<div><span class="count">200</span></div>
<div><span class="count">177</span></div>

$('.count').each(function () {
    $(this).prop('Counter',0).animate({
       Counter: $(this).text()
    }, {
       duration: 4000,
       easing: 'swing',
       step: function (now) {
          $(this).text(Math.ceil(now));
       }
   });
});

Refer This

Unschooled answered 7/4, 2021 at 7:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.