Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic background-color on td, based on text value

Tags:

jquery

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?

like image 342
Ilium Avatar asked Jan 21 '23 07:01

Ilium


2 Answers

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()
        });
    });​
});
like image 200
Blair McMillan Avatar answered Feb 06 '23 19:02

Blair McMillan


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.

like image 35
jAndy Avatar answered Feb 06 '23 19:02

jAndy