Table Zebra Color


In the ReferenceDesigner.com practical example of the jQuery we present code that will beautify an existing Table by coloring the alternate rows with contrast color. This will be done with a single powerful odd even selector.

We present the complete code the output rendered here itself. Note that you can make changes in the code and check the output right here on this page.

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>jQuery alternate row color | Referencedesigner.com</title>
  5. </head>
  6. <script type="text/javascript" src="jquery-1.8.0.min.js"></script>
  7.  
  8. <script type="text/javascript">
  9. $(document).ready(function() {
  10.  
  11. $("table tr:nth-child(even)").addClass("alternateblue");
  12.  
  13. });
  14. </script>
  15.  
  16. <style type="text/css">
  17. table {
  18. background-color: black;
  19. }
  20. th {
  21. background-color: brown;
  22. color: white;
  23. }
  24. tr {
  25. background-color: ghostwhite;
  26. margin: 1px;
  27. }
  28. tr.alternateblue {
  29. background-color: lightblue;
  30. }
  31. td {
  32. padding: 1px 8px;
  33. }
  34. </style>
  35.  
  36.  
  37. <body>
  38.  
  39. <table>
  40. <tr>
  41. <th>S No</th>
  42. <th>Cars</th>
  43. <th>Price</th>
  44. </tr>
  45. <tr>
  46. <td>1</td>
  47. <td>Toyota Corolla</td>
  48. <td>$18,000</td>
  49. </tr>
  50. <tr>
  51. <td>2</td>
  52. <td>Honda Civic</td>
  53. <td>$18,500</td>
  54. </tr>
  55. <tr>
  56. <td>3</td>
  57. <td>Ford Focus</td>
  58. <td>$17,500</td>
  59. </tr>
  60. <tr>
  61. <td>4</td>
  62. <td>Camry</td>
  63. <td>$21,500</td>
  64. </tr>
  65. <tr>
  66. <td>5</td>
  67. <td>Accord</td>
  68. <td>$22,150</td>
  69. </tr>
  70. </table>
  71. </body>
  72. </html>



You may like to try this example here.

Exercises


This is an interesting example, so we present the code here again in highligted form. We will then ask you to make chanhes in the exercise section below it.

Exercise 1 - How do you highlight the odd rows in place of even rows ?

Exercise 2 - Remove the jQuery script and check how the code renders the table.

Exercise 3 - How do you change the alternate color from lightblue to some other color.


Exercise 3 - In the above code make changes such that all row colors will be normal ( But with header row in brown background and white text). Add a button that says beautify Table. On clicking the button, it should make alternate rows in lightblue background color ( Hint : Makes use of addClass method.) Check the solution code. You mush give your try before seeing the solution.