user3187675 user3187675 - 1 month ago 20
HTML Question

Animate bootstrap progressbar

I have some trouble using the animation with jquery on the progress bar. I retrieve some percentage from the database and put it as text inside the progress bar div, but I can't find a way to change the base width in the animated properties. Is it possible to change the color of the progress according to the current value of the progress bar (i.e. : < 33% -> red, < 66% -> yellow, else green)



console.log($(".progress-bar").text())

$(".progress-bar").animate({
width: $(this).text() //I want to get the value inside the progressbar div but doesn't seems like to work
}, {
duration: 2000,
step: function(now, fx) {}
});

<link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="col-xs-12 col-sm-12 progress-container">
<div class="progress progress-striped active">
<!-- Part retrieved from the database -->
<div class="progress-bar progress-bar-success" style="width:0%">60%</div>
</div>
</div>





JSfiddle: http://jsfiddle.net/WEYKL/968/

Answer

There is a mistake with context. this in options refers to window object, not $(".progress-bar")

$( ".progress-bar" ).animate({
   width: $( ".progress-bar" ).text()
}, {
   duration: 2000,
   step: function( now, fx ) {
  	      $(this).removeClass (function (index, css) {
	     return (css.match (/(^|\s)progress-bar-\S+/g) || []).join(' ');
      });
  	      if (now < 33) {
  		     $(this).addClass('progress-bar-danger');
      } else if (now < 66) {
	     $(this).addClass('progress-bar-warning');
      } else {
	     $(this).addClass('progress-bar-success');
      }
   }
});
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="col-xs-12 col-sm-12 progress-container">
  <div class="progress progress-striped active">
    <!-- Part retrieved from the database -->
    <div class="progress-bar progress-bar-success" style="width:0%">60%</div>
  </div>
</div>

Here is your working example

Comments