To implement this feature, you can utilize basic JavaScript. However, it is crucial to avoid adding any additional spaces within the "style" attribute to ensure the functionality works correctly.
Initially, modify your progress bar code slightly by including a new ID attribute, for instance, "progress" will be used as the ID in this example.
<div class="progress">
<div id="progress" class="progress-bar" style="width:{{a}}%">{{a}}%</div>
</div>
Subsequently, insert the following JavaScript code snippet. This script will automatically calculate the percentage and update the color accordingly based on the value. A designated function is defined for this purpose.
Function:
function formatbar(id) {
div1 = document.getElementById(id);
style = div1.getAttribute('style');
percent = style.substring(6);
a = percent.substring(0, percent.length - 1);
if (a < 50) {
// color red
document.getElementById(id).style.backgroundColor = "red";
} else if (a < 70) {
// color orange
document.getElementById(id).style.backgroundColor = "orange";
} else if (a > 70) {
// color green
document.getElementById(id).style.backgroundColor = "green";
}
}
Lastly, you simply need to invoke the function with the provided ID.
formatbar(id);
By following this approach, you can create multiple progress bars using this method. Just ensure that each progress bar has a unique ID assigned to it, or else the functionality may not work as expected.
To utilize the function on different progress bars:
formatbar("progress")
formatbar("progress1")
formatbar("progress12")
function formatbar(id) {
div1 = document.getElementById(id);
style = div1.getAttribute('style');
percent = style.substring(6);
a= percent.substring(0, percent.length - 1);
if (a < 50) {
// color red
document.getElementById(id).style.backgroundColor = "red";
} else if (a < 70) {
// color orange
document.getElementById(id).style.backgroundColor = "orange";
} else if (a > 70) {
// color green
document.getElementById(id).style.backgroundColor = "green";
}
}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="progress"><div id="progress" class="progress-bar" style="width:20%">20%</div> </div>
<div class="progress"><div id="progress1" class="progress-bar" style="width:60%">60%</div> </div>
<div class="progress"><div id="progress12" class="progress-bar" style="width:90%">90%</div> </div>