Create alternating table row colors or classes with JavaScript
Well this is sort of the other way around, I adapted a
table sorting javascript and added in row
coloring. After that, I got some emails asking if I had a script that did just the row coloring.
That wasn't that hard anymore, so here it is. An inobtrusive alternating row class script. It simply
gives your table rows CSS classes odd and even.
It's MIT licensed, so feel free to use it.
Download the alternating row classes script
- The script + example CSS and HTML (~ 3 kb)
- The script (~ 2.5 kb)
- Example page (~ 1 kb)
- Example stylesheet (~ 0.5 kb)
Example table with alternate row classes
| Numbers | Alphabet | Dates | Currency | Unsortable |
|---|---|---|---|---|
| 1 | Z | 01-01-2006 | € 5.00 | Unsortable |
| 2 | y | 04-13-2005 | € 6.70 | Unsortable |
| 3 | X | 08-17-2006 | € 6.50 | Unsortable |
| 4 | w | 01-01-2005 | € 4.20 | Unsortable |
| 5 | V | 05-12-2006 | € 7.15 | Unsortable |
How to implement the script to create alternating row colors
In the head, include the following:
<script type="text/javascript" src="alternate_rows.js"></script>
Example CSS:
.odd {
background-color: #ddd;
}
.even {
background-color: #fff;
}
The class alternate_rows is obligatory, as well as adding a unique id to each table.
You can use this script to alternate classes on multiple tables on one page (that's also the reason why the table needs an id).
Example table:
<table class="alternate_rows" id="anyid"> <tr> <th>Numbers</th> <th>Alphabet</th> <th>Dates</th> <th>Currency</th> <th>Unsortable</th> </tr> <tr> <td>1</td> <td>Z</td> <td>01-01-2006</td> <td>€ 5.00</td> <td>Unsortable</td> </tr> <tr> <td>2</td> <td>y</td> <td>04-13-2005</td> <td>€ 6.70</td> <td>Unsortable</td> </tr> <tr> <td>3</td> <td>X</td> <td>08-17-2006</td> <td>€ 6.50</td> <td>Unsortable</td> </tr> <tr> <td>4</td> <td>w</td> <td>01-01-2005</td> <td>€ 4.20</td> <td>Unsortable</td> </tr> <tr> <td>5</td> <td>V</td> <td>05-12-2006</td> <td>€ 7.15</td> <td>Unsortable</td> </tr> </table>
Update notification
If you want to be warned about any updates to this script, email sortable [ at ] joostdevalk.nl with the subject "alternate subscribe". You will then be included in mailings about updates to this script.