Tuesday, May 22, 2007

Better alternating row colors

Occasionally you work something out to the point where it's good enough and you don't bother to go back and look at it again.

I thought I had done about all I could with alternating row colors by just doing a simple cfif before the rows started that picked a class for the row. It worked something like this:

--- in css file ---
.odd {background-color: #F7F7F7}
.even {background-color: #FFFFFF}

--- in code ---
<cfif myQuery.currentrow mod 2>
<cfset rowclass = "odd">
<cfelse>
<cfset rowclass = "even">
</cfif>
<tr class="#rowclass#">
STUFF
</tr>

That seems to work ok, but here is a shorter way that seems to be just a little more elegant.

--- in css file ---
.row1 {background-color:#F7F7F7;}
.row0 {background-color:#FFFFFF;}

--- in code ---
<tr class="row#CurrentRow mod 2#">
STUFF
</tr>

That seems much better to me.

3 comments:

  1. Some older versions of CF don't like the space between the pound/hash/octothorpe characters. Ift's not as elegant, but if you have an old version of CF and can't get it to work, you just need to throw in a function call: #Int(CurrentRow MOD 2)#.

    ReplyDelete
  2. octothorpe? Sounds like Spider-man's nemesis.

    ReplyDelete
  3. Hi Rick,

    Thanks for the tip - I'm maintaining an old CF5 site and your Int() trick was just what I needed :)

    ReplyDelete