john Smith
john Smith

Reputation: 17906

animated count with zeros

I´m having this function to make a text-number count up animated. it counts up in this pattern :

[1,2,3,4,5,6,7,8,9,10,11,12,...]

function:

   var pointnum = 28;   
   function countStuffUp(points,selector,duration) {//Animate count
        $({countNum: $(selector).text()}).animate({countNum: points}, {
            duration: duration,
            easing:'linear',
            step: function() {
                $(selector).text(parseInt(this.countNum) );
            },
            complete: function() {
                    $(selector).text(points)
            }
        });     
    }

    countStuffUp(pointnum,'.pointWrap',1000);

but what i want to achieve to count it up like

[01,02,03,04,05,06,07,08,09,10,11,12,...]

i tryed some sensless but i have no idea

for any hints thanks in advance

here´s a fiddle : http://jsfiddle.net/Q37Q6/

Upvotes: 1

Views: 467

Answers (2)

Alnitak
Alnitak

Reputation: 339856

You just need a padding function:

function pad(n) {
    return n < 10 ? '0' + n : n;
}

and then call that:

$(selector).text(pad(Math.floor(this.countNumber)));

NB: don't use parseInt for truncating numbers - strictly speaking that function exists to convert strings to numbers, not for rounding.

See http://jsfiddle.net/alnitak/6BUug/1/

Upvotes: 2

NG.
NG.

Reputation: 22904

Tweaked fiddle here - just add your own padding.

function padNum(num) {
    if (num < 10) {
        return "0" + num;   
    }
    return num;
}

// step becomes:
step: function() {
    $(selector).text(padNum(parseInt(this.countNumber)));
},

Upvotes: 1

Related Questions