DHTMLdev.com — Dedicated to quality Web development articles and tutorials
Alternating Table Row Colors with JavaScript PDF Print E-mail
Thursday, 01 December 2005

JavaScript is a great programming language for solving certain Web page design challenges. The example in this article will use JavaScript to reduce the labor and maintenance of an HTML table that has alternating colors for each table row.

Using JavaScript might or might not be a good idea for your situation. There are alternatives to the solution I am about to explain. See the section Alternative Solutions for some ideas.

Update

A alternative JavaScript solution has been posted on the forums. See the Alternating Table Row Colors post. The alternative solution will modify an existing HTML table and is now the preferred solution. This article will be superceded by a new article when time permits me to write it. For now, see the solution posted in the forums. For a quick working example of the new DOM solution, see Alternating Table Row Background Colors with JavaScript and CSS.

Table of Contents

  1. Example Table
    1. Table Example 1
    2. HTML code for Table Example 1
  2. The Problem with Hand Coding the Table
    1. Table Example 2
    2. Table Example 3
  3. The JavaScript Approach
    1. How JavaScript will Save Us Time and Effort
    2. Planning the Code
    3. What Our JavaScript Code Needs to Do
    4. What the JavaScript Code Will Do
  4. The JavaScript Code
    1. Alternating Table Row Background Colors Using the Modulo Operator
    2. Complete Code Example
  5. Alternative Solutions
    1. Visual Basic Scripting
    2. Server-Side Scripting
    3. XML and XSL

Example Table

Here is an example HTML table that uses alternating background colors. Each odd-numbered row has a background color of medium gray and each even-numbered row has a background color of light gray. To create the alternating background colors, I defined a CSS class called alt and applied it to each even-numbered table row. Here are an example table and the code to create it.

Table Example 1

Example Table 1 with Alternating Row Colors
First row
Second row
Third row
Fourth row
Fifth row

HTML Code for Table Example 1

<table class="content" style="width: 300px;">
<caption>Example Table with Alternating Row Colors</caption>
<tbody>
<tr>
<td>First row</td>
</tr>
<tr class="alt">
<td>Second row</td>
</tr>
<tr>
<td>Third row</td>
</tr>
<tr class="alt">
<td>Fourth row</td>
</tr>
<tr>
<td>Fifth row</td>
</tr>
</tbody>
</table>

The Problem with Hand Coding the Table

So, what is the potential problem in the above code? It's the CSS alt class typed into every other table row. Example Table 1 had only 5 rows. Typing the CSS code class="alt", in every other table row, by hand would not be that big of a deal. But if you had to type it a few hundreds times, in a much longer table, it would get tedious keeping track of which rows need to class="alt" and which rows should have no class added to the table row code. Also, if the table content changed, you would most likely have to go back and update dozens of rows, adding class="alt" to some rows and deleting from other rows, in order to maintain the alternating background colors.  would be easy enough to not warrant JavaScript. Consider that creating and editing HTML tables can be tedious because there is so much table code to read through. Just finding where to start editing is tedious. And mistakes are easy to make when editing code in long tables. If you have created and edited a lot of HTML tables, you know what I am talking about.

Here is an example of a table where the content changed and now the alternating table row colors are off. Note that the first two rows have the same background color. Table Example 2 would require that nearly all table rows be edited, adding class="alt" to some rows and removing from other rows. Alternating the table row color is so tedious and predictable, can't it be automated so that when the table content changes the code is rewritten, correctly, when the page is reloaded?

Table Example 2

Example Table 2 with 20 Rows
First row
Second row
Third row
Fourth row
Fifth row
Sixth row
Seventh row
Eigth row
Ninth row
Tenth row
Eleventh row
Twelfth row
Thirteenth row
Forteenth row
Fifteenth row
Sixteenth row
Seventeenth row
Eighteenth row
Ninteenth row
Twentieth row

To make matters worse, and this is the real problem, what happens when someone decides that one row needs to be deleted? This will throw off all the following rows. In Example 3, the second row was removed. This throws off the alternating colors for rows 3 through 20. Also note that this also throws off the content. Now, the third row needs to light background, and the fourth row needs the medium gray background, etc.—all the way down, the background color for each row needs to change. Retyping this table will not be fun. Now imagine if it had 200 rows and you had to change every row after row 2! Another consideration is that even with medium length tables, like with 20 rows, people typing code make mistakes: you might find after finishing the table that you made a mistake and might have to go back and change 10 rows for some reason.

Table Example 3

Example Table 3 with Row 2 Removed
First row
Third row
Fourth row
Fifth row
Sixth row
Seventh row
Eigth row
Ninth row
Tenth row
Eleventh row
Twentieth row
Thirteenth row
Forteenth row
Fifteenth row
Sixteenth row
Seventeenth row
Eighteenth row
Ninteenth row
Twentieth row

The JavaScript Approach

The solution is to not type out the code for each row by hand. Instead, we will use JavaScript to dynamically write out each table row, which saves us time and trouble in three ways.

How JavaScript will Save Us Time and Effort

  • We will not have to type each table row by hand
  • We will not have to wade through a lot of HTML table code, which can be difficult to read, in order to figure out where to add or remove content from the page
  • We will not have to keep track of which row uses which CSS class
  • If the table changes later, we would not have to retype a lot of table rows

Planning the Code

The first step to creating our JavaScript solution is to write out what the code will need to do. In our case, the code will need to write out an HTML table row for each item we want to add to the table and it will need to add our alt CSS class to each odd-numbered row. The JavaScript code will also need a way to store the information it will write out. We should write all this out so we know everything we need to code when we start coding.

What Our JavaScript Code Needs to Do

  • Store the table content to write out
  • Write out the content inside HTML table rows
  • Add a CSS class name alt to each odd-numbered table row

What the JavaScript Code Will Do

  • Will store the content inside a JavaScript array
  • Write out a table row for item in the array
  • Use the modulo operator to figure out whether to add the alt CSS class to each row

The JavaScript Code

Finally, the code! While planning out the project and the code are always, always, always necessarily, finally getting to the code itself is always the most fun. It's like planning a party and then finally having the party. Now we will go through writing the code, but you will have wait a little longer to see the real point to this whole article. If you are already familiar with using JavaScript arrays and functions to output HTML tables, then skip ahead the end where I explain the use of the modulo operator for outputting alternating colors.

Alternating Table Row Background Colors Using the Modulo Operator

This is the JavaScript modulo operator: %

The modulo operator is THE key to alternating the table row colors. Here is what the modulo operator gives you: knowing if the table row is odd or even. And that is the key. If the table row is odd (first, third, etc.) or even (second, fourth, etc.) you know which background color it shoud have. How does the modulo operator tell us whether the row is odd or even?

The modulo operator gives you the remainder of division. And if you divide by 2 and look at the remainder, you know whether the row is odd or even. Consider the code example below. Note that when using getting the remainder of dividing by 2, the remainer will always be 0 or 1, which is how we will know whether a row is odd or even. if the remainer is 1, we know the row is odd. If the remainder is 0, we know the row is even.

var remainder = 1 % 2 // remainder would equal 1
var remainder = 2 % 2 // remainder would equal 0
var remainder = 3 % 2 // remainder would equal 1
var remainder = 4 % 2 // remainder would equal 0
var remainder = 5 % 2 // remainder would equal 1

Using our knowledge of the modulo operator, we can use it inside a JavaScript For loop that outputs each table row to output the correct background color for each row. The For loop iterates over the JavaScript array we created eariler.

Complete Code Example

This code example includes all the code needed to make this solution work. It includes the JavaScript, as well as the CSS code for the alt class. The line of code using the modulo operator is in bold.

Note The code below had an error that is now corrected: class="alt" was changed to class='alt', to fix a string error. Apparently, the program I had used to escape the characters failed to escape them properly and I did not notice the code would not work when copied from this page. It is now corrected.

<style type="text/css">
.alt { background-color:#efefef; }
</style>
<script type="text/javascript">
// Declare and populate array with content
var arrContent = new Array;
arrContent[0] = "First row";
arrContent[1] = "Second row";
arrContent[2] = "Third row";
arrContent[3] = "Fourth row";
arrContent[4] = "Fifth row";
// Declare variable and start saving table code
var strOutput = "<table>";
for(var i=0;i<arrContent.length;i++)
{  if(i%2==0)   
       // If remainder is even, output tr with class="alt"
       {  strOutput += "<tr class='alt'><td>" + arrContent[i] + "</td>";   
  }
      else  // Else, output tr with no class
      {  strOutput += "<tr><td>" + arrContent[i] + "</td>";
       }
}
// Close table
strOutput += "</table>";     
// Write out table code to HTML page 
document.write(strOutput); </script>

Alternative Solutions

Although I will not explain how to implement these alternative solutions, you should be aware of them and when to consider them. The alternatives include using other programming languages besides JavaScript, using server-side programming, and not even using a programming language to dynamically generate the table at all but using XML and XSL to output static HTML pages.

Visual Basic Scripting

Visual Basic Scripting is a language similiar to JavaScript. The problem is that it only works in the Internet Explorer Web browser. So I would definitely not use Visual Basic Scripting, unless you were to run it on the server side on a Microsoft Web server using ASP.

Server-Side Scripting

The term server-side scripting is a general term for running code on the Web server instead of running it in the Web browser client. Running code in The Web browser is called client-side scripting. Server-side scripting has the advantage on not depending on the client's Web browser to properly run the code. For more information, search for server-side scripting on Google.

Server-side scripting is definitely a better option than client-side scripting for the type of solution we are considering here for the HTML table row examples. Unfortunately, JavaScript can be run as server-side code, setting up server-side JavaScript support is usually not an option with most Web server configurations. So you will probably never write any server-side JavaScript.

The most likely candidates for server-side scripting will be PHP or ASP.

XML and XSL

You could also using XML and XSL to ouput the HTML table rows. This is a good approach. It has the advantage of server-side scripting in that the code does not have to run in the Web browser. You output the code and then save it in a static HTML page that is served to the client. You could also mix client side scripting and XML and XSL, by using JavaScript to use the XML and XSL, but I do not recommend that. It's too complicated for this solution and you might as well just use JavaScript arrays to store the content rather than XML. But using XML and XSL to output the HTML code and then add it in the HTML page could be a good solution, especially if you cannot write or do not the ability to run server-side code.

The downside is that managing your content and publishing it will become more complicated, because either you start storing the whole page as XML or you have two source files (or more): one HTML source file for most of the page and XML files for each HTML table. Also, the XSL used to transform the XML into HTML is another source file to keep track of. To really benefit from using XML you would have to justify it's use through the economy of scale principle: if you use a lot of XML to solve a lot of problems (besides the one we are discussing in this article) and you implement a process for publishing the XML to the Web that makes a lot of sense, then you could really benefit in many ways from using XML. Most of the time, though, using XML in this way only makes sense for large publishing operations, and does not make sense for solving small individual problems that can be isolated and solved independently.

Last Updated ( Sunday, 13 August 2006 )
 
< Prev