Home > database >  Animate numbers from 0 to Value with Comma - Value is pulled from var
Animate numbers from 0 to Value with Comma - Value is pulled from var

Time:10-23

Struggling with this one so any ideas or suggestions are really appreciated.

I have a calculation (working) that counts how many days have passed since 01/01/2021 and * by a value. I would like to animate from 0 to the value over a period of 3 seconds, however, I don't know how to get around commas - can get it working without.

Any suggestions?

var startDate = new Date('01-01-2021');
var today = new Date();
var diff = Math.floor((today - startDate)/(1000*60*60*24))
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth()   1).padStart(2, '0');
var yyyy = today.getFullYear();
today = mm   '/'   dd   '/'   yyyy;
var answer = diff * 134256;
 
function commaSeparateNumber(val){
    while (/(\d )(\d{3})/.test(val.toString())){
      val = val.toString().replace(/(\d)(?=(\d\d\d) (?!\d))/g, "$1,");
    }
    return val;
}
document.getElementById("CCalc").innerHTML = (commaSeparateNumber(answer));
<p id="CCalc" class="fig-number"></p>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Here is the code with jQuery:

var startDate = new Date('01-01-2021');
var today = new Date();
var diff = Math.floor((today - startDate)/(1000*60*60*24))
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth()   1).padStart(2, '0');
var yyyy = today.getFullYear();
today = mm   '/'   dd   '/'   yyyy;
var answer = diff * 134256;
 
function commaSeparateNumber(val){
    while (/(\d )(\d{3})/.test(val.toString())){
      val = val.toString().replace(/(\d)(?=(\d\d\d) (?!\d))/g, "$1,");
    }
    return val;
}
document.getElementById("CCalc").innerHTML = parseFloat(commaSeparateNumber(answer).replace(/,/g, ''));


$(".fig-number").each(function () {
    $(this)
      .prop("Counter", 0)
      .animate(
        {
          Counter: $(this).text()
        },
        {
          duration: 3000,
          easing: "swing",
          step: function (now, tween) {
            // Check added for decimal number
            if(parseInt(tween.end) == parseFloat(tween.end)){
                var number = Math.ceil(now);
              $(this).text(number.toLocaleString());
            }
          },
        }
      );
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p id="CCalc" class="fig-number">39471264</p>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related