End User
End User

Reputation: 109

Counter animation to a calculated value

I need my counter animation to animate a value dynamically calculated in a span by the checkboxes selected. The values are calculated fine, however they do not animate. http://jsfiddle.net/dbtj93kL/

 $('input[type="checkbox"]').change(function() {
   var total_span = 0;
   $('input[type="checkbox"]').each(function() {
     if ($(this).is(':checked')) {
       total_span += parseInt($(this).prop('value'));
     }
   });

   $("#usertotal").html(total_span);
 });

 jQuery({
   Counter: 0
 }).animate({
   Counter: $('.Single').text()
 }, {
   duration: 1000,
   step: function() {
     $('.Single').text(Math.ceil(this.Counter));
   }
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="checkbox" value="100" onclick="test(this);">1</input>
<input type="checkbox" value="200" onclick="test(this);">2</input>
<input type="checkbox" value="300" onclick="test(this);">3</input>
<input type="checkbox" value="400" onclick="test(this);">4</input>
<br />
<span id="usertotal" class="Single"> </span>

Upvotes: 0

Views: 379

Answers (1)

blex
blex

Reputation: 25634

You need to do the animation when a box is checked, not on page load like you did:

 $('input[type="checkbox"]').change(function () {
     var total_span = 0;
     $('input[type="checkbox"]').each(function () {
         total_span += this.checked && +this.value;
     });
     $({counter: +$('#usertotal').text()}).animate({counter: total_span},{
         duration: 500,
         step: function () {
             $('#usertotal').text(Math.round(this.counter));
         }
     });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input type="checkbox" value="1">1</input>
<input type="checkbox" value="2">2</input>
<input type="checkbox" value="3">3</input>
<input type="checkbox" value="4">4</input>
<br />
<span id="usertotal"></span>

Upvotes: 1

Related Questions