Contact Form    |   Email    |    Site Map
RSS

Coldfusion: Alternating row colors

Some people feel that using tables has gone the way of the Dodo. In some respects that may be true (slicing up an image into a tabular layout for instance), yet tables still have their place. Have you ever tried to recreate a complex table using CSS and DIV tags? It isn't for the faint of heart.

Although Exam Professor has gone beyond using tables in presenting tablular data (we use <cfgrid>), we developed this little bit of code from an earlier build.

First we start with the CSS to define the odd, even and mouse-over color of the table rows.

<style>
tr.rowOdd {background-color: #FFFFFF;}
tr.rowEven {background-color: #E7E7E7;}
tr.rowHighlight {background-color: #FFFF99;}
</style>

If you already have a CSS based website simply copy and paste the code between the style tags into your .css file.

The next step is to query your data, create the table, and loop over the table row as follows:

<table summary="">
<th>First name</th>
<th>Last name</th>
<cfoutput>
<cfloop query="qGetYourData">
<tr class="#IIf(CurrentRow Mod 2, DE('rowOdd'), DE('rowEven'))#" onmouseover="this.className='rowHighlight'" <cfif CurrentRow Mod 2>onmouseout="this.className='rowOdd'"<cfelse>onmouseout="this.className='rowEven'"</cfif>>
<td>#firstname#</td>
<td>#lastname#</td>
</tr>
</cfloop>
</cfoutput>
</table>

As long as your query returns a few records you'll see alternating row colors in your table. This same technique could be applied to other HTML tags as well, such as <li> or <div> with very few modifications.