The problem:
My site reads a xml file that contains information (values) for a data-table.
I use CSS to style the table and everything works fine.
To get a better user-experience I wondered if it is possible to change the background color of each cell dynamically depending on its value? For example: Each cell that contains a number less then “5” has a red background color; each cell >= “5” has a green background color.
Can this be solved in CSS only or do I have to use JavaScript?
Sure it’s possible. I put together a demo which basically makes the cell color red if less than 1/3 of the max, yellow if less than 1/2 of max and green otherwise (demo):
$('table td').each(function(){
var c = 'high',
t = $(this),
val = parseInt( t.text(), 10 );
if (val <= max/3 ) { c = 'low'; }
if (val > max/3 && val <= max/2) { c = 'medium'; }
t.addClass(c);
});
This is assuming you’re using integers, if not, change the parseInt( t.text(), 10); to parseFloat( t.text() );
Author
Posts
Viewing 2 posts - 1 through 2 (of 2 total)
The forum ‘CSS’ is closed to new topics and replies.