PDA

View Full Version : Table repeat region and applying alternate background colors.


smitho
01-31-2008, 04:58 AM
When you create a dynamic table is there a way to apply alternate colors to the rows? Say header row blue then the dynamic rows odd light gray and the even rows white etc?

davidj
01-31-2008, 06:50 AM
how are your coding skills??

davidj
01-31-2008, 07:00 AM
wrap your chops round this

its my own monster

<table>

<?php

$no = 1; //<< set start counter

do { //<< start loop

$divide = $no / 2; //<< divide by 2 which will turn odd numbers into floats

//<< set boolean $detect using string search.
//Search for decimal in float.
//If found you have detected odd numeric.
$detect = strstr($divide,'.');


//check the IF statement in <tr> to echo the appropriate class
//if $detect is true then that is odd so echo color1 else echo color2
?>

<tr <?php if($detect){echo "class=\"color1\"";}else{echo "class=\"color2\"";} ?>>
<td><?php echo $row['field1_id'];?></td>

<td><?php echo $row['field2'];?></td>

<td><?php echo $row['field3'];?></td>

<td><?php echo $row['field4'];?></td>
</tr>

<?php

$no++; //<< increment count.

}while ($row = mysql_fetch_array($result))

?>

<table>

smitho
02-01-2008, 03:26 AM
Thanks davidj,

here's another option using JS.

in the <head> place:


<style>
.odd{background-color:white;}
.even{
background-color:#CCCCCC;
}
</style>
<script>
function alternate(id){
if(document.getElementsByTagName){
var table = document.getElementById(id);
var rows = table.getElementsByTagName("tr");
for(i = 0; i < rows.length; i++){
//manipulate rows
if(i % 2 == 0){
rows[i].className = "even";
}else{
rows[i].className = "odd";
}
}
}
}
</script>

Then at the first<body> and <table> type:


<body onload="alternate('thetable')">
<table id="thetable">
Now if you use dreamweaver like me to make your dynamic tables (getting better at coding one day I'll do it myself) change the first row <td> to <th> this will allow you to apply a css style to the table header making different from the white and gray.

dellis87
08-23-2010, 05:22 AM
Thanks a bunch davidj

I modified your code a bit to fit my foreach needs.

Here's how I did it:

<table>
<?php

$no = 1; //<< set start counter

?>
<?php foreach($news as $new): ?>
<?php $divide = $no / 2; $detect = strstr($divide,'.'); ?>
<tr <?php if($detect){echo 'class="rowcolor1"';}else{echo 'class="rowcolor2"';} ?>>
<td>
<div id="text">
<?php echo($new['text']); ?>
</div>
</td>
</tr>
<?php
$no++;
endforeach;
?>
</table>


I simply set .rowcolor2 to a light gray and .rowcolor1 to "background: none"

Works beautifully!

davidj
08-23-2010, 10:40 AM
Woah

That was an old post

Pleased its still helping!