Animate the digits into the separate span using CSS and jQuery

Viewed 101

I am using this code to animate the digits. Is there any way to animate each digit into separate span. I need to give padding with background for each digit and need space between each digit.

Number is starting from 0 which is expected functionality.

Achieve this:

$('.count').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $(this).text()
    }, {
        duration: 4000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">
  <span class="count">200</span>
</div>

1 Answers

Please try this.

var total_digit = $('#test').attr('data-count').toString().length;
var countobj=$('.count').get(0);
for (var i=1;i<total_digit;i++){
  $("#test").append(' <span class="count"> 0 </span>')
}
$('.count').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $('#test').attr('data-count')
    }, {
        duration: 5000,
        easing: 'swing',
        step: function (now) {
        var num =Math.ceil(now).toString()
        num = num.padStart(total_digit, '0')
        for (var i=1;i<=total_digit;i++){
            $('#test span:nth-child('+i+')').text(num.charAt(i-1))
            }
        }
    });
});
span{
margin:15px;
background:red;
padding:15px;
color:white;
direction: rtl;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test" data-count="200">
  <span class="count"> 0 </span>
</div>

Related