Change Dynamically Bar Percentage

3

I have this bar percentage and wanted to dynamically change the value of it just that I am not getting it.

Barcode

<script>$('.bar-percentage[data-percentage]').each(function(){varprogress=$(this);varpercentage=Math.ceil($(this).attr('data-percentage'));$({countNum:0}).animate({countNum:percentage},{duration:2000,easing:'linear',step:function(){//Whattodooneverycountvarpct=Math.floor(this.countNum)+'%';progress.text(pct)&&progress.siblings().children().css('width',pct);}});});</script><divid="bar-5" class="bar-main-container">
              <div class="bar-percentage" data-percentage="51"></div>
              <div class="bar-container">
                <div class="bar"></div>
            </div>
          </div>

Code that I used to try to change Dynamically

<script>
$('.bar-percentage').attr('data-percentage','60')//irá receber um valor diferente depois de efectuar cálculos
</script>
    
asked by anonymous 28.12.2015 / 13:35

1 answer

2

I've reformulated your function to give a load in progressBar, take a look:

I created the changePercentage() function, in it you inform the progress bar that you want load to happen. If you only report progressBar, it will capture the new value of the slash by the data-percentage attribute, if you want a new value other than that of that attribute just put it in the second argument of the function.

Example:

$(document).ready(function() {
  function changePercentage(progress) {
    var percentage = arguments.length > 1 ? arguments[1] : progress.attr('data-percentage')
    percentage = Math.floor(percentage);
    var bar = progress.siblings().children();
    bar.stop().animate({
      width: percentage * progress.width() / 100
    }, {
      duration: 2000,
      easing: 'linear',
      step: function() {
        var cdt = Math.round(100 * bar.width() / progress.width());
        progress.text(cdt + "%");
      }
    });
  }

  changePercentage($('.bar-percentage')); // Captura o novo valor do data-percentage

  $('button').click(function() {
    changePercentage($('.bar-percentage'), 10); // Captura o valor do segundo argumento (10)
  });
})
.bar-container {
  width: 100%;
  background: #c7c7c7;
  height: 30px;
}

.bar-container .bar {
  background: #333;
  height: 30px;
  width: 0
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><divid="bar-5" class="bar-main-container">
  <div class="bar-percentage" data-percentage="51"></div>
  <div class="bar-container">
    <div class="bar"></div>
  </div>
</div>

<br>

<button>Mudar porcentagem para 10%</button>
    
28.12.2015 / 15:12