I am developing a polling website in which the poll option progress changes color depending on the percentage of votes. Currently, the color changes using an if statement that checks on the progress percentage. Is there a better way to do this without relying on this many if statements? Like a gradient of some sort? I would be okay with both vanilla and jQuery solutions.
function progressColor(progress) {
if (progress >= 0 && progress <= 24) return '#FFE169';
else if (progress >= 25 && progress <= 49) return '#FFDE59';
else if (progress >= 50 && progress <= 74) return '#FF914D';
else if (progress >= 75 && progress <= 89) return '#FF7A7A';
else if (progress >= 90 && progress <= 100) return '#FF5757';
}
4
Answers
well, you could use the slightly unusual switch syntax
you dont need the else if since the conditions are mutually exclusive, just seperate if statements will do
I quite like the if syntax though, it is robust and shows exactly what you are doing
Here’s an approximate parametrization of your color scale.
You can use the slider to change the background color too.
Same function, use math.
Base color:
0xFFE169
final color 0xFF5757
and between them…0xFFE169 – 0xFF5757 = 8a12
so:
every percentage is in hex ~ 162 = (DEC)354
To a computer, colour is just a bunch of numbers. That means, in theory, you could do some maths to get the number that’s a certain percentage point difference between a lower and higher number. With your scale, I don’t think it’s as simple as that however we’ll keep the essence of the idea and get some help with a library which does all the complex maths: chroma.js.
chroma.js has a function called
scale
which can take an array of colours that appear on the scale. Using the colours in your question, you would build a scale like this:scale
returns a function which you can call with a percentage to get the colour at that percentage on the scale.Below is a demo, constructing a scale from the colours in your question and using inputs to change the percentage and get a specific colour on the scale.