jQuery Alternating Gray Rows in a Table, and Highlight Table Row Mouseover Example

Click the Activate button to add alternating gray rows and a mouseover effect to the table below.



Column 1 Column 2 Column 3 Column 4
A1 B1 C1 D1
A2 B2 C2 D2
A3 B3 C3 D3
A4 B4 C4 D4
A5 B5 C5 D5
A6 B6 C6 D6
A7 B7 C7 D7
A8 B8 C8 D8
A9 B9 C9 D9


JavaScript

The JavaScript that makes this work is as follows:
$("#mytbody > tr:even").addClass("even");
$("#mytbody > tr:odd").addClass("odd");
$("#myheaderrow ~ tr").bind( "mouseover", function(e){
   $(this).toggleClass("highlight");
});
$("#myheaderrow ~ tr").bind( "mouseout", function(e){
   $(this).toggleClass("highlight");
});
Usually this code would go inside of your $(document).ready() jQuery handler so that the alternating rows and highlight bindings
are applied when the DOM is ready. For the sake of this demo, I'm setting everything up once the user clicks the activate button.


CSS

The supporting CSS classes for the gray rows and highlighting are as follows:
tr.even { background-color: #efefef; }
tr.odd { background-color: #fff; }
.highlight { background-color: #fffdcd !important; }

HTML

The <table> HTML I used in this example is as follows:
<table id="mytable">
    <tbody id="mytbody">
      <tr id="myheaderrow">
        <th>Column 1</th>
        <th>Column 2</th>
        <th>Column 3</th>
        <th>Column 4</th>
      </tr>
      <tr>
        <td>A1</td>
        <td>B1</td>
        <td>C1</td>
        <td>D1</td>
      </tr>
      ...
   </tbody>
</table>