Dynamic background color on td based on text value

I am trying to create a dynamic background color in a specific range on td. This color should be based on the value that is inside td.

For instance:

<tr> <td>40%</td> <td>70%</td> <td>30%</td> </tr> 

Let's say 0% color: # ff0000, and color 100%: # 00ff00

For a table cell containing a value of 40%, I would like the background color to be 40% of the range that is between # ff0000 and # 00ff00.

Thus, all cells will have their own background color based on the text value that they contain.

Any clues?

+4
source share
5 answers

Sounds like Colorjizz library will help you.

http://code.google.com/p/colorjizz/

An example of using @Mikee (see comments):

 $(function (){ var colors = new Hex(0xFF0000).range(new Hex(0x00FF00), 100, true); $("table tr td:first-child").each(function (){ $(this).parent().css({ 'background-color' : '#'+colors[parseInt($(this).text())].toString() }); });​ }); 
+6
source

You will need to do a little math and use Ecma- / Javascripts toString() to convert the hexadecimal values.

 var rgb = [255,0,0]; $(function(){ $('td').each(function(i, elem){ var $self = $(elem), percent = parseInt($self.text()), csscolor = ['#']; rgb.forEach(function(value, index){ this.temp = (~~((percent/100) * value)).toString(16); csscolor.push(temp.length < 2 ? '0' + temp : temp); }); $self.css('background-color', csscolor.join('')); }); });​ 

Example: http://www.jsfiddle.net/YjC6y/11/

This is not a complete answer to your question, but should send you on the right path.

+3
source

RGB color space is not a betting choice when it comes to color management. Check out the following article: http://en.wikipedia.org/wiki/HSL_and_HSV . In the HSL color space, you can simply select the hue and saturation, and then adjust the brightness according to the contents of the cells.

0
source

I have a javascript solution

  ele=document.getElementById('tabid').getElementsByTagName('td'); var cont; for(var i=0;i<ele.length;i++) { cont=ele[i].innerHTML.split('%'); switch(cont[0]) { case 10: ele[i].className='blue-color'; break; ... } } 

set table id as tabid and css blue-color{background:blue}

0
source

I had a very similar need, so I went ahead and wrapped a couple of the logical snippets that I found on the Internet in one jquery extension.

Using can be as simple as $ ('# myTable td'). color () or you can provide an array of colors if you are trying to follow a predefined color scheme.

The following is an example of a gradient between two specified colors based on a <td> text value.

 $(document).ready(function(){ var myColors = [ { rng: 0, to: 99, color: { r: 0xff, g: 0x00, b: 0x00 } }, { rng: 100, to: 100, color: { r: 0x00, g: 0xff, b: 0x00 } } ]; $('#myTable td').color({thresh: 110, colors: myColors}); }); 

JSFiddle: http://jsfiddle.net/danno2000/Yxm4G/

GitHub: https://github.com/danno2000/jquery-color

0
source

All Articles