I have table of data that has a column called percent. I would like the background color of the cells in that column to depend on the value in that cell. So if <= -8, the color would be red. If -4 the color would be yellow. If >=0 then green. But should be a gradient so that the numbers in between like 2.2 would be between yellow and green. Can anyone help me with an example that I could use for my specific task? I appreciate the help.
Asked
Active
Viewed 2,345 times
1 Answers
3
My answer is inspired from the accepted answer to this question,
function GreenYellowRed(value) {
value--;
var r,g,b;
if (value < 4) {
// green to yellow
r = Math.floor(255 * (value / 4));
g = 255;
} else {
// yellow to red
r = 255;
g = Math.floor(255 * ((4-value%4) / 4));
}
b = 0;
return r + "," + g + "," + b;
}
Working JS Fiddle: https://jsfiddle.net/vu1b1m57/
Update Please see the new JSFiddle https://jsfiddle.net/vu1b1m57/1/

Kishor
- 2,659
- 4
- 16
- 34
-
Thank you so much. That is awesome. Can I bother you with a follow-up question, since I am not very learned in JavaScript? Using your example, how would I apply the background color to the cells within the one column of my table that have the different values? – singular Feb 04 '16 at 15:40
-
Please check the update. Is it what you are looking for? – Kishor Feb 05 '16 at 01:34
-
Fantastic. Exactly what I was looking for. I can't thank you enough. I am trying to play with the color values though and am getting close to what I need but not quite there. The scale currently goes from green to red as the numbers get higher. I am looking for it to go from red to green with red starting at -8. Yellow starting at -4 and green starting at 1. Is that doable with this example? Since I am not familiar with the math.floor logic, I am not quite sure how to do it correctly. Thank you again! – singular Feb 05 '16 at 13:15
-
1I am not as good with this relations between the numbers and colors but I have updated the fiddle after some trail and errors. https://jsfiddle.net/vu1b1m57/3/. Hope it helps. :) – Kishor Feb 05 '16 at 16:53
-
1I honestly do not know what to say. I wish there was a way I could repay you for this. Thank you so much! – singular Feb 05 '16 at 18:17