Use JQuery to Change Progress Bar Color based on Value

Date: 2016-03-30 |

**Problem: **I’ve got a Twitter Bootstrap progress bar that I want to change colors based on a variable value in Javascript. I’ve got the value in my JS and I’ve also got the progress bar to appear, however I haven’t been able to figure out how to dynamically set the bar’s color based on that value.

**Solution: **The solution here is to utilize JQuery’s ability to alter the CSS of an HTML element. Check out my Pen to see it in action. Or simply check out the code below:

[[https://gist.github.com/SIRHAMY/d15aafeb1a788d2f071f](https://gist.github.com/SIRHAMY/d15aafeb1a788d2f071f)]

In a progress bar, the property that determines the color is ‘background-color’. As you can see in ‘progressbar.js’, we’re using JQuery to select the HTML element with ID == ‘progressbar’ and then altering its CSS.

When only altering one property, we pass in the property we’re trying to change (‘background-color’) as well as the value we’re trying to set it to, here a variable we’ve set to a hexadecimal color value based on the value of ‘someValueToCheck’.

Of course, you could use a similar tactic to change other things on the progress bar as well, such as

  • Completion: ‘aria-valuenow’ and ‘width’
  • Stripe size: ‘background-size’
  • Stripe color (a little more complicated)
  • Bar’s max and min value: ‘aria-valuemax’ and ‘aria-valuemin’ respectively

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.