Article

JavaScript 101 - Part 1

Page: 1 2 3 4 5 Next

A Practical Example

At the beginning of this article, I said that JavaScript was a lot of fun. After wading through the last few pages of introductory material, you may be starting to question that assertion. To try to make up for the dry first impression that the mundane details of JavaScript invariably give, let's finish off with an example that you can actually use.

A common way of sprucing up a table of dull figures is to give the rows of your table alternating background colors. The effect looks like this:

My Table
Item 1Value
Item 2Value
Item 3Value
Item 4Value

The problem is that if you go back and add or remove a row sometime down the line, you have to shift all the colors below the new or removed entry to keep the colors of the rows lining up. By using JavaScript to handle the row colors, you can avoid this problem entirely!

Before we begin, there's one more built-in function that you need to know. We've already seen alert, which takes a single parameter and displays it in a message box. document.write performs a similar function, but instead of displaying the parameter you pass it in a message box, it slots it into the current HTML document for you. Take the following a simple example:

<html>    
<head>    
<title> document.write example </title>    
</head>    
<body>    
<script language="JavaScript">    
<!--    
document.write("<p>This JavaScript stuff is pretty <i>neat</i>.</p>");    
//-->    
</script>    
</body>    
</html>

All this results in is an HTML document that says "This JavaScript stuff is pretty neat." Not too impressive at first glance... but wait and see what we can do by using this function with all the other tools we've seen so far!

First, let's pick the two HTML color codes for our table rows and assign them to variables:

var color1 = "#6691BC";    
var color2 = "#769DC5";

We'll also need a variable to keep track of what row number we're on. We'll set it to 1 because when we start off we'll be on the first row.

var rownumber = 1;

Now we'll write a function. The job of this function will be to write the <tr> tags of our table for us, slotting the right color in each time (are you starting to see where this is going...?):

function tablerow() {    
 var currentcolour;    
 if (rownumber % 2 == 0) {    
   currentcolor = color1;    
 } else {    
   currentcolor = color2;    
 }    
 document.write("<TR BGCOLOR=\"" + currrentcolor + "\">");    
 rownumber = rownumber + 1;    
}

There are a couple of new tricks in the code above, but mostly it's stuff we've seen already. Regardless, let's step through it line by line to see what's going on.

The first line just says that we're creating a function for ourselves called tablerow. Since there's nothing between the parentheses, our function won't take any parameters, but the parentheses are required nevertheless.

On the second line, we create a variable called currentcolor. It's important to realise that variables created inside of functions only exist for as long as that function is executing. So each time this function is called, a variable called currentcolor will be created, and then will disappear when the function finishes doing its thing. Contrast this with the variables color1 and color2 that we created above. Since these variables weren't created inside any functions, they'll exist for as long as the document is loaded in the browser, and can be accessed by any piece of JavaScript code (including our function, as we're about to see).

The third line is the start of an if-else control structure. You'll remember that this structure allows us to execute one set of statements or another depending on whether some condition is true or not. The condition in this case is (rownumber % 2 == 0). The only thing that should be scary about this is the percent sign. This is actually just another mathematical operator like + or -, but is not as common. Known as the modulus operator, it calculates the remainder obtained when dividing one number by another. In this case, our condition is checking if the remainder of dividing rownumber by 2 equals 0. In simpler terms, we're checking if rownumber is even!

Thus, the fourth line only gets executed if rownumber is even. If it is, we set the value of currentcolor to the value of color1, "#6691BC". If it isn't, the sixth line gets executed instead, and currentcolor is assigned the value of color2, "#769DC5".

With the if-else behind us, the eighth line gets executed regardless of the outcome of the condition. This is where our document.write function comes into play. What we want to be written into our document is the following:

<tr bgcolor="_______">

where the underscore needs to alternate between our two color values. So far, our function has picked one of the two color values depending on whether we're on an even or odd row of the table. All that's left is to write the line with the correct color in it. For convenience, I'm repeating the line here:

document.write("<tr bgcolor=\"" + currrentcolor + "\">");

Thinking back to how alert works, this looks just about right. The value of currentcolor is plugged into the HTML code and is written to the document by document.write. The only point of confusion is the two occurrences of \" that I've highlighted above. Since the double quotes are used by JavaScript to mark the beginning and end of a string of text, using them in the text itself would confuse JavaScript. It would think that the string of text was ending, when in fact you just wanted to put double quotes in the string. To overcome this, JavaScript lets you put a backslash (\) before any character that would usually have a special meaning, to indicate that the special meaning should be disregarded and that the character should appear in the string of text as-is. With this in mind, this line of code does exactly what we need!

As its last order of business, our function adds one to the rownumber variable, by setting its new value to its old value plus one. This ensures that the next time the function is called, the other color will be used for the row background.

Now whenever we want to start a new row in our HTML document and have JavaScript decide on the background color, we replace the <tr> tag with a call to our function:

Before:
<tr bgcolor="#??????">

After:
<script language="JavaScript">
<!--
tablerow();
//-->
</script>

Pretty neat, huh? Here's the complete example for you to refer to:

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links