tags:

views:

58

answers:

4

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

For example:

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

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

For the table cell containing the value of 40% I'd like the background color to be 40% of the range that is inbetween #ff0000 and #00ff00.

This way all the cells will have a custom background color based on the text value they contain.

Any clues?

+5  A: 

Sound like the Colorjizz library would help you.

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

Example of how to use from @Mikee (see the 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()
        });
    });​
});
Blair McMillan
As the author of ColorJizz I support this answer! :) Lets you do stuff like this too: new RGB(255,0,0).range(new Hex(0x00FF00), 10, true);
Mikee
Infact, I made you an example: http://www.jsfiddle.net/gCDn7/1/
Mikee
nice example, Mikee. +1
Clay Hinson
Thanks for the example Mikee, this worked like a charm for me!
Ilium
A: 

The RGB color space is not the bets choice when it comes to manipulating colors. Check out the following article: http://en.wikipedia.org/wiki/HSL_and_HSV. With the HSL color space you could just pick a Hue and Saturation, then adjust the luminance according to the cells content.

Lawrence Barsanti
+2  A: 

You would need to do a little math and use Ecma-/Javascripts toString() to convert hex 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 the complete answer to your question, but should send you on the right track.

jAndy
A: 

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}

Paniyar