Javascript Programming 101

Okay, now that you've got a handle on some of the basics, let's move on to something you can sink your teeth into: functions. Give this code a try:

<html>
<head>
<title>Test</title>
<script language="JavaScript">
function coloredText(color) {
document.write("<font color=" + color + ">Welcome to this page!</font>");
}
</script>
</head>

<body onLoad="coloredText('green');">
</body>
</html>

Alright, this time, inside our opening/closing JavaScript tags, we have this:

function coloredText(color) {

The first word, "function", tells JavaScript that we're creating a function. This is very similar to writing "var" before the name of a variable.

After that, we have the words "coloredText" - this is the name of the function. Just as variables have names, so do functions. Many people, for whatever reason, keep their function names in that basic format: the first word is all-lowercase, but any word after that is squished together (no spaces!), and the first letter is capitalized.

Next, we have the word "color" in parentheses, followed by a left bracket. The parentheses are there to hold any variables we want to pass to the function. The function's job is basically to execute the code inside the left and right brackets whenever it's "called". The good thing is that, in addition to calling it, we can send variables to it, and it can process the code using those variables! Most programmers call it "passing arguments."

In this case, we're passing a variable called "color" - this may be confusing now, but read on. All will be explained. Next two lines:

document.write("Welcome to this page!");
}

As you can see, we're using the document.write command again - we're printing some text again. This time, the parentheses have double quotes inside of them - the double quotes tell the script that we're using a string of text. As you'll remember, to print a variable, we simply called the document.write command and stick the variable name in parentheses right afterward - no quotes involved. Quotes are needed whenever we're storing a string of text, just as we did when we created the "message" variable, and as we've done here.

The first text to be printed is this:

<font color=

This, of course, is the start of an HTML tag - as such, it will be processed as HTML on our page, just as if we had typed it out normally, without the aid of JavaScript. After this, we end the string of text with a double quotation mark. After this is a plus sign ("+") - this tells the script that we're adding something to the text. In this case, it's the world "color" - which tells the script to print out the value of the variable named "color" - as you'll recall, we listed the "color" variable in the first line of the function as one of the variables/arguments we planned to pass to the code inside the function.