Search code examples
javascriptjquerycyclecounterjcycle

Percentage countdown


I'm doing a countdown from 100% to 0% using jQuery or JavaScript. I'm trying work out how to do this and have control over what percentage it stops at. So far I've put together this using a plugin called jCycle because I can apply fx none, set speed and timeout and also use autostop and autostopCount. I need it to count down quickly but not sure of a better way.

Although I know it's clunky my code is below to hopefully help give you a better idea of what I'm trying to achieve. For example purposes I have just shown from 10% - 0%:

<div id="counter">
   <p>1%</p>
   <p>2%</p>
   <p>3%</p>
   <p>4%</p>
   <p>5%</p>
   <p>6%</p>
   <p>7%</p>
   <p>8%</p>
   <p>9%</p>
   <p>10%</p>
</div>
$('#counter').cycle({
    delay: 600,
    fx:     'none',
    backwards: true,
    speed: 1,
    timeout:  60, 
        autostop: 1,
    autostopCount: 0,
});

How can I consolidate my HTML? There are too many p tags I have to type manually.


Solution

  • You can set autostopCount to how many items you want to count down. So if you're starting at 100 and want to stop at 5, set autostopCount: 96. The formula is thus: stop = start - (difference - 1).

    You can pass in any var to your .cycle() function and change it programmatically.

    To avoid typing out 100 p tags, just use a for loop!

    for(i=1; i <= 100; i++) {
        $('#counter').append('<p>' + i + '%');
    }
    

    DEMO