Dreamweaver: Alternating table row color with simple JavaScript and CSS
In this tutorial I will show you how to alternate table row colors using Javascript and CSS. You can create this script using any HTML editor or a notepad. But in this example I am using Dreamweaver to:
- create a table
- define CSS rules
- add JavaScript function that does all the work
How does the script work?
The script calculates number of rows and determines which predefined CSS class to use for which row.
Create Table
- From the Dreamweaver's insert toolbar, click the table button
- Create a table with three columns and five rows.
Assign an ID to the table
- select the table
- assign an ID "alternate" to it

Define CSS Rules
- Click the New CSS Rule icon in the CSS panel
- Create a Class selector "row-one'
- Select background category and specify background color

Repeat steps 1 - 3 for another row color. Change the name of the selector to "row-two" in step 2 and background color in step 3.
Add JavaScript
Add following JavaScript code inside of the head element, or separate JavaScript file.
function alternatecolor(id){
if(document.getElementsByTagName){
var table = document.getElementById(id);
var rows = table.getElementsByTagName("tr");
for(i = 0; i < rows.length; i++){
if(i % 2 == 0){
rows[i].className = "row-one";
}else{
rows[i].className = "row-two";
}
}
}
}
JavaScript Breakdown
As you can see this JavaScript code is fairly simple. It contains only one function
that takes a table ID as a parameter.
function alternatecolor(id){
}
This if statement ensures that javascript doesn't break in older browsers
if(document.getElementsByTagName){
}
In these two lines we are getting table rows based on the table ID parameter passed to this function, and assigning those table rows to a variable called rows.
var table = document.getElementById(id);
var rows = table.getElementsByTagName("tr");
Next is a FOR loop that iterates through all rows (rows.lenght). By using modules (%) operator we are assuring that all rows with even (i) numbers get assigned color_one class and all odd (i) numbers get assigned color_two class.
for(i = 0; i < rows.length; i++){
if(i % 2 == 0){
rows[i].className = "row-one";
}else{
rows[i].className = "row-two";
}
Applying JavaScript function to the table
Add "onload" attribute to the tag .
< body onload="alternatecolor('alternate');" >
Comments
No Comments

Add Comment | Contact me