Guide on setting a personalized color for progress bars in Bootstrap 4

I'm working on a progress bar:

<div class="progress"><div class="progress-bar" style="width:{{a.49}}%">{{a.49}} %</div> </div>

Is there a way to apply a custom color to the progress bar based on a condition in CSS? :

If a.49 < 50, color should be red
If a.49 > 50 but less than 70, color should be orange
If a.49 > 70, color should be green

Any assistance would be greatly appreciated.

I've attempted to implement suggestions but have not achieved the desired outcome:

a=50

 <div class="progress">
 <div class="progress-bar" style="width:{{a}} %; background:{% if a < 50 %}red{% elif a > 70 %} green{% else %}orange{% endif %};">{{a}} % </div></div>

Although the color inside the bar changes based on the value (in this case orange), the bar is only filled by 10-20% instead of 50% which it used to be with the value of {{a}}

Here's what I have tried:

<div class="progress"><div class="progress-bar" style="width:{{a}}% ;
       backkground:{% if a < 50 %} red {% elif a > 70 %} green {% else %} orange {% endif %}"> {{a}} %</div> </div>

Can this method be replicated for the progress bar?

Answer №1

Utilizing CSS variables in combination with multiple background images allows you to achieve this effect:

.progress .progress-bar {
  background: 
    linear-gradient(green  0 0) 0/ calc(var(--w)*1% - 70%) 1px, 
    linear-gradient(orange 0 0) 0/ calc(var(--w)*1% - 50%) 1px, 
    red;
  width: calc(var(--w)*1%);
}

.progress .progress-bar::before {
  content: attr(style) "%";
  font-family:monospace;
  text-indent:-4ch;
  margin:auto;
  overflow:hidden;
}

html {
  font-size:25px;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
<div class="progress">
  <div class="progress-bar" style="--w:20"></div>
</div>

<div class="progress">
  <div class="progress-bar" style="--w:80"></div>
</div>

<div class="progress">
  <div class="progress-bar" style="--w:60"></div>
</div>

Answer №2

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>

Answer №3

To achieve this effect without adding more CSS, consider utilizing the Django template language:

Here's a sample of the template logic:

{% if a<50 %}red{% elif a<70 %}green{% else %}blue{% endif %}

When incorporated into your code:

<div class="progress">
<div class="progress-bar" style="width:{{a}}%; color:{% if a<50 %}red{% elif a<70 %}green{% else %}blue{% endif %};">
    {{a}} %
</div> 
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjust the height of a division dynamically

I have the following HTML snippet: <div id="container"> <div id="feedbackBox"></div> </div> The #feedbackBox div is initially not visible. To center the div, the CSS code is used: #container { position: absolute; widt ...

JavaScript - Attempting to insert a value into a text field by clicking a button

I am struggling to get my function to properly add the value of the button to the text field when clicked by the user. HTML <form name="testing" action="test.php" method="get">Chords: <textarea name="field"& ...

Optimal ffmpeg configurations for encoding videos into mp4 and ogg formats for seamless playback on HTML5 platforms

Despite the buzz surrounding it, the HTML5 video tag is facing a minor issue. To ensure cross-browser compatibility, multiple video formats - like mp4 and ogg - need to be included for its use. Unfortunately, I couldn't find optimal settings for each ...

Troubleshooting: Issues with jQuery JavaScript Modal Popup functionality within MVC framework

When I click on the "Comments" link, a modal popup opens up and displays the content as expected. Now onto my issue: In the first scenario, the desired outcome is achieved but some other code does not execute. In this case, when I place the "@section" ins ...

PHP MySQL outputting data in a dropdown menu format

Struggling to extract data from a database and display it as a dropdown list. I am fetching the foreign key, its unique code, and its name/title to be displayed in a dropdown list for input into a new table. $sql = "SELECT quali_code, title FROM ...

Tips for securely storing visitor-entered form data on our computer from our webpage

Is there a way to store the information filled out by visitors on our website? <ul class="form"> <li class="short"> <label>First Name<span class="required"></span></ ...

ERROR : The value was modified after it had already been checked for changes

Encountering an issue with [height] on the main component and seeking a solution Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '753'. Current value: '731'. I have th ...

Extract the text content from an HTML file while ignoring the tags to get the substring

Hello, I am a newcomer to the world of Web Development. I have an HTML document that serves as my resume, formatted in HTML. For example: html <p>Mobile: 12345678891 E-mail: <a href="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Determine the exact scroll position needed to reveal the element when scrolling in reverse

I'm looking for a way to make my div disappear when I scroll down and reappear immediately when I start scrolling back up. Currently, it only works when I reach a certain position instead of taking effect right away. I need assistance in calculating t ...

Modify a CSS style with JavaScript or jQuery

Can CSS rules be overwritten using jQuery or JavaScript? Imagine a table with rows categorized by different classes - "names" for persons and "company" for companies. How can we efficiently hide or show specific rows based on these classes? If we have a ...

Moving from CSS to SCSS: Incorporating CSS files from npm packages - A Step-by-Step Guide

I am new to SASS and currently in the process of converting my existing project's CSS files to SCSS. I know that simply changing the extension to .scss will work for my custom files, but I'm not sure how to handle the dependency style files. I ty ...

What is the best way to access Sass variables in a different Sass file?

I'm currently working on a WordPress theme and running into an issue with utilizing SASS from another file using the @use method. For those of you who may not know, the @import rule method will soon be deprecated which is why I am trying to implement ...

What is the best method for modifying an XML document without altering its associated XSL stylesheet?

I am working with XML data retrieved from a URL: <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="/style.xsl"?> ....etc... To display the data in HTML format, I added the second line referencing the style.xsl file ...

What could be causing my dropdown menu to vanish unexpectedly after being clicked for the first time?

To view the live demonstration, simply click here. I have an issue with my drop down menu where it is hidden upon first click. Additionally, I would like the drop down menu to disappear when clicked anywhere outside of its current display. How can I accomp ...

Creating dynamic forms within a template

Creating a FormSet to generate Member objects is my current task. class MemberBuilder(forms.Form): first_name = forms.CharField(max_length=128) last_name = forms.CharField(max_length=128) role = forms.CharField(max_length=128) The FormSet def ...

Tips on correctly determining font size

I'm attempting to style a span element with a specific height (in this case, 23px). However, the browser is automatically adding some extra pixels to the element. There are no additional styles like padding or margin affecting it, just the size of th ...

Adjusting specific sections of a container in real-time

Fiddle: https://jsfiddle.net/1b81gv7q/ Sorry for the slightly cryptic title; I couldn't come up with a better way to phrase it. Imagine this scenario: there's a container with content that needs to be dynamically replaced. If I wanted to repla ...

Generating dynamic HTML content in React using a variable within a string

Currently, I am utilizing TypeScript in a React application. I am receiving the following data from an API: a) a list of variable names ["name", "surname"] b) several strings in simple HTML form with variables "<p>Hello, ho ...

What is the proper way to include 'rowspan' specific CSS within an HTML table?

I have an HTML table with rowspans in it: table tr, td { border: 1px solid black; } tr:nth-child(1) { background-color: red; } tr:nth-child(2) { background-color: blue; } <table> <tr> <td rowspan=2>Section 1</td> ...

How to disable CSS transition on Angular 4 component initialization

I am facing a major issue with css transitions and Angular 4. The problem arises when using an external library that includes an input counter feature. Despite knowing that no additional styling is being applied to the wrapped input, the application has a ...