Code-Lover
Code-Lover

Reputation: 309

Animating width to a specified percent and showing the percent from 0 to that specified percent while animating

I want bar to get animated from width:0 to width:95%.

Also I want the percentage to be shown from 0% to 95% inside .barPercent element while width is animated.

But with what i tried, the width animation ends whereas percentages in .barPercent element have not reached to 95% and stills is increased.

I can not find a way for them to match together and width animation and percentage increment done in the same time.

 var bar = $('.bar'),
 percent = bar.find('.barPercent'),
 i=1, interval;
 percent.text(i + '%');
 i++;
 interval = setInterval(function(){
 percent.text(i + '%');
 if(i == 95){
  clearInterval(interval);
 }
 i++;
 },2000/95);
 bar.animate({
 width: 95 + '%'
  },2000,'linear');
   
 .bar{
      height: 30px;
      background: red;
      position: relative;
      width: 0px;
      overflow: visible !important;
  }
  .barPercent {
     width: 50px;
     height: 40px;
     position: absolute;
     top: -5px;
     right: 0;
     background: #81858a;
     line-height: 40px;
     text-align: center;
     color: #fff;
     font-size: 0.88em;
  }
<html>
<head>
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/magnific-popup.min.css">
  <meta name = "viewport" content = "width=device-width,initial-scale=1,shrink-to-fit=no" />
</head>
<body>
<div class="barContainer">
  <div>HTML</div>
   <div class="bar" data-width="95">
    <span class="barPercent">0</span>
   </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/jquery.magnific-popup.min.js"></script>
</body>
</html>

How to make width and percentages increment to be done in the same time?

Is there a better solution?

Why don't their duration match?

Thanks

Upvotes: 0

Views: 395

Answers (1)

Alwaysa Learner
Alwaysa Learner

Reputation: 496

$('.bar').each(function () {

    duration = 2000; //in ms
    step = 0.5; //increase in width in px

    var bar = $(this),
        percent = bar.find('.barPercent'),
        barWidth = Number(bar.data('width')),
        i = 1,
        interval;
/*
    percent.text(i + '%');
    i++;*/

    interval = setInterval(function () {
        widthNumb = Math.floor(i);
        percent.text(widthNumb + '%');
        if (i >= barWidth) {
            clearInterval(interval);
        }

        bar.css({
            "width": i + '%'
        });

        i = i + step;
    }, Math.floor(duration / barWidth / 10));

    /*
    bar.animate({
        width: barWidth + '%'
    }, duration/step, 'linear'); //
    */
});

I used a step variable = 0.5 to increase the width in px, however the % text shown will be in whole numbers using Math.floor. You can play arund by changing the values of duration and step

Upvotes: 1

Related Questions