Change progress bar colour based on progress value

Changing a progress bar colour based on what value its progress is at. This is done using jQuery and the default Bootstrap colour classes.

Progress bar change color based on percent

CodePen example.

The jQuery:

$(document).ready(function () {
  const show_percent = true;
  var progressBars = $(".progress-bar");
  for (i = 0; i < progressBars.length; i++) {
    var progress = $(progressBars[i]).attr("aria-valuenow");
    $(progressBars[i]).width(progress + "%");
    if (show_percent) {
      $(progressBars[i]).text(progress + "%");
    }
    if (progress >= "90") {
      //90 and above
      $(progressBars[i]).addClass("bg-success");
    } else if (progress >= "30" && progress < "45") {
      $(progressBars[i]).addClass("bg-warning"); //From 30 to 44
    } else if (progress >= "45" && progress < "90") {
      $(progressBars[i]).addClass("bg-info"); //From 45 to 89
    } else {
      //29 and under
      $(progressBars[i]).addClass("bg-danger");
    }
  }
});

This will add the Bootstrap colour classes to the progress bar when its progress is at a certain conditional, you can however use custom CSS classes instead of the Bootstrap supplied packaged ones.

HTML:

<div class="container">
  <div class="row mt-3 text-center">
    <div class="col-12">

      <div class="progress">
        <div class="progress-bar" role="progressbar" style="width: 15%" aria-valuenow="15" aria-valuemin="0" aria-valuemax="100"></div>
      </div>

      <div class="progress">
        <div class="progress-bar" role="progressbar" style="width: 32%" aria-valuenow="32" aria-valuemin="0" aria-valuemax="100"></div>
      </div>

      <div class="progress">
        <div class="progress-bar" role="progressbar" style="width: 53%" aria-valuenow="53" aria-valuemin="0" aria-valuemax="100"></div>
      </div>

      <div class="progress">
        <div class="progress-bar" role="progressbar" style="width: 91%" aria-valuenow="91" aria-valuemin="0" aria-valuemax="100"></div>
      </div>

    </div>
  </div>
</div>

jQuery and Bootstrap:

<head>
    <title>Progress change colour</title>
    <link rel="stylesheet" href="https://write.corbpie.com/wp-content/litespeed/localres/aHR0cHM6Ly9jZG5qcy5jbG91ZGZsYXJlLmNvbS8=ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css"/>
    <script src="https://write.corbpie.com/wp-content/litespeed/localres/aHR0cHM6Ly9jZG5qcy5jbG91ZGZsYXJlLmNvbS8=ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>