Looping through values to assign width to div

I'm working on a function where the width of the element is added dynamically using js. This is my js

<script>
    $('.progress-fill span').each(function(){
    var percent = $(this).html();
    if(percent ==12){
      $(this).parent().css({
        'width' : "100%"
      });
    }
    if(percent ==11){
      $(this).parent().css({
        'width' : "92%"
      });
    }
    if(percent ==10){
      $(this).parent().css({
        'width' : "83%"
      });
    }
    if(percent == 9){
      $(this).parent().css({
        'width' : "75%"
      });
    }
    });
    </script>

the html looks something like this:

<div class="results-block">
 <div class="progress-bar">
  <div class="progress-fill">
    <span>12</span>
  </div>
 </div>
</div>

so I'm checking the value from the .progress-fill span and depending on this value the width of the parent div is set. This has to go from a possible value of 12 down to 1. The way I'm currently doing it with separate if statements works but I'm sure it's not the most efficient way to do this. Has anybody got any other ideas how to do this?

3 answers

  • answered 2018-01-17 11:28 Stormcloak

    If I understood your question, you have chance to calculate it. Min value is 1, so equilavent to width: 0% and max value is 12 so equilavent width: 100%

    <script>
        $('.progress-fill span').each(function(){
            var percent = $(this).html();
            $(this).parent().css({
            'width' : "" + ((percent - 1) * 100) / (12 - 1) + '%'
            });
        });
    </script>
    

  • answered 2018-01-17 11:29 Ctznkane525

    How about this?

    Note this is pseudocode:

    if(percent >= 9 and percent <= 12){
          $(this).parent().css({
            'width' : "" + (percent/12).toString() + "%"
          });
        }
    

  • answered 2018-01-17 11:29 Rory McCrossan

    The simplest way to achieve this would be to calculate the width as a percentage based on the 12 possible values, like this:

    $('.progress-fill').css('width', function() {
      return 100 / 12 * $(this).find('span').text() + '%';
    });
    .progress-fill {
      background-color: #C00;
      color: #FFF;
      margin: 5px 0;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="results-block">
      <div class="progress-bar">
        <div class="progress-fill">
          <span>12</span>
        </div>
    
        <div class="progress-fill">
          <span>6</span>
        </div>
    
        <div class="progress-fill">
          <span>10</span>
        </div>
      </div>
    </div>