Hover effects with jQuery

This example takes the stripy table to the next level by adding a hover effect.

In the example below, we've used the jQuery .hover function to apply a new style to a row when the mouse poiter is hovering over it. In addition, we've changed the stripe statement so that it uses .addClass. This is better than using inline CSS and allows us to control the visibility of the hover background colour. CSS specificity would always make the inline colour dominant, which is not what we want in this case.

Top 10 counties by population

Rank County Region Population Density
1 Greater London London 7,813,600 4,979
2 West Midlands West Midlands 2,655,200 2,945
3 Greater Manchester North West 2,629,500 2,061
4 West Yorkshire Yorkshire and the Humber 2,249,500 1,109
5 Kent South East 1,427,500 382
6 Essex East 1,412,900 385
7 Merseyside North West 1,353,400 2,099
8 South Yorkshire Yorkshire and the Humber 1,328,300 856
9 Hampshire South East 1,296,900 344
10 Lancashire North West 1,169,300 380

Here's the script that does the work:

<!-- load jQuery from Google CDN -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/
jquery.min.js"></script> <script> $(document).ready(function(){ $("#counties tbody tr:even").addClass("even-row"); $("#counties tbody tr").hover(function(){ $(this).toggleClass("row-hover"); }); }); </script>

Here is part of the markup for the table:

<table id="counties">
   <thead>
      <tr>
         <th>Rank</th>…
…
   <tbody>
      <tr>
         <td>1</td>
         <td>Greater London</td>…

Here are the 2 CSS rules that are added by jQuery:

.even-row{
   background-color:#e8f2ff;
}
.row-hover{
   background-color:#b2d526;
   color:white;
}

The order of these 2 rules in the stylesheet is very important. The row-hover rule must always come after the even-row rule because it has to overwrite the static rule on hover.