0

For example say there is a bunch of values range from [80.8, 92.1] I would like to let the lowest value 80.8 have the color pure red #FF0000 and 92.1 have the color pure green #00FF00. For the values in the middle, I would like to have their color in proportion to their values from red to green like the following picture.

Is there any function that given the value it could spit out the CSS color value? Or anything else to get the job down?

enter image description here

user3692521
  • 2,563
  • 5
  • 27
  • 33
  • This question has been asked 3 years ago—possible duplicate of [Generate colors between red and green for an input range](http://stackoverflow.com/questions/11849308/generate-colors-between-red-and-green-for-an-input-range) – Terry Mar 02 '15 at 05:01
  • Wrong. This is about between red and green. OP is asking for red-yellow-green – Stephen Rodriguez Mar 02 '15 at 05:04

1 Answers1

0

Here is a solution that I came up with on JSFiddle:

To explain what is going on:

var red    = "#FF0000";
var yellow = "#FFFF00";
var green  = "#00FF00";

These are our minimum, middle, and maximum values to choose from. In short, Red-Yellow-Green. In order to provide these values as a range of colors from red and green, we need to use some math:

First we store the possible hex values in a string:

var hex = '0123456789ABCDEF';

Then (in a function) we capture the min-middle-max range values directly. As for other cases, we use some math to select some hex value between 0-F based on the existing value from the range. Below is that as a function:

function update(val) {
    if(val == 0) {
        $('#color').css('background', red);        
    } else if(val == 50) {
        $('#color').css('background', yellow);
    } else if(val == 100) {
        $('#color').css('background', green);
    } else {
        if(val < 50) {
            // val < 50 is between red and yellow
            var perc = val/50;
            var hexVal = hex[Math.round(16*perc)];
            $('#color').css('background', "#FF"+hexVal+hexVal+"00");
        } else if(val > 50) {
            // val > 50 is between yellow and green
            var perc = val/100/0.5-1;
            var hexVal = hex[hex.length - Math.round(16*perc)];
            $('#color').css('background', "#"+hexVal+hexVal+"FF00");
        }
    }
}

#color is a div container to show the active color.

See the JSFiddle here: http://jsfiddle.net/rhyx81u4/4/

Stephen Rodriguez
  • 1,037
  • 1
  • 12
  • 22