-2

I want that when i click a button, the percentage of the div go very fast from 0 to the number of the div. How can I implement the animation to my code?

JSFiddle: https://jsfiddle.net/252jxsjq/5/

jQuery:

var counter = localStorage.getItem('rans') || 0;
var counter = Number(localStorage.getItem('rans')) || 0;
var counter1 = Number(localStorage.getItem('bans')) || 0;

$('.redanswer').click(function(){
     localStorage.setItem('rans', ++counter);
     $( '.bpercent' ).html( counter1 * 100 / (counter1+counter) + "%" );
     $( '.rpercent' ).html( counter * 100 / (counter1+counter) + "%" );
     $('.rpercent').animateNumber({ number: 'rans' });


});

var counter1 = localStorage.getItem('bans') || 0;
var counter = Number(localStorage.getItem('rans')) || 0;
var counter1 = Number(localStorage.getItem('bans')) || 0;

$('.blueanswer').click(function(){
     localStorage.setItem('bans', ++counter1);
     $( '.rpercent' ).text( counter * 100 / (counter1+counter) + "%" );
     $( '.bpercent' ).text( counter1 * 100 / (counter1+counter) + "%" );
});
bob
  • 4,282
  • 2
  • 22
  • 30
Niccolò Guidi
  • 195
  • 2
  • 14

2 Answers2

2

Check out a working example in CODEPEN, looking in to the link provided by Enkode. Here I created a self-calling loop which can go as much as you specify, 100 in this case.

$(".clickButton").click(function() {
   var counter = 0;
   var timeDelay = 10; // in millisecond
   var endCount= 100;  // end of loop

   (function loopFunc (counter) {
      setTimeout(function () {
         $("p").html(counter + "%");                

         if (counter++ < endCount) loopFunc(counter);   
      }, timeDelay)
    })(1); 
});

The loop will be invoked by clicking .clickButton. Then a setTimeout function create a pause inside of the loop iteration.

zero point
  • 1,290
  • 3
  • 10
  • 15
0

You code is not dry and can be condensed and broken in to functions. For your animation you can use a simple while loop with a timer. Here is an example of a while loop with a time. Depending how slow you want your animation you will want to sleep for a shorter / longer time

How do I add a delay in a JavaScript loop?

Community
  • 1
  • 1
Enkode
  • 4,515
  • 4
  • 35
  • 50