Lesson 8 -- Printer Friendly Version

INSTRUCTIONS:

IMPORTANT: This version of your lesson is for saving or printing only. All links and images have been disabled to decrease download time and help you avoid printer difficulties.


Chapter 1

As you've learned, the hypertext markup language (HTML) can be used to produce some fairly spectacular web pages. When it comes to efficiently describing the laying of a web page, HTML is one language that can't be beat.

But if you want to build a web page that people can interact with, HTML will be of little use. Web developers who want to build interactive web pages usually turn to programming languages like C++, Perl, Java or Visual Basic. Unfortunately, most of these programming languages take weeks to learn, and months to master.

In 1995, the Netscape Communications Corporation introduced a powerful, yet easy-to-use scripting language called JavaScript. Unlike programming languages, a scripting language like JavaScript does not require a sophisticated compiler or complex debugger. Instead, your script is interpreted by any web browser that recognizes JavaScript. Both Netscape Navigator 2.0 (or greater) and Microsoft Internet Explorer 3.0 (or greater) will interpret and run JavaScript.

You don't need a Master's degree in programming to use JavaScript. All you have to do is type a few lines of code into your HTML file and the Netscape Navigator or Microsoft Internet Explorer will do the rest. Today, you'll learn how Javascript works by creating a couple of very basic scripts. In the next lesson, you'll learn how to use JavaScript to create a web page that seems to respond to the user's every movement.

-Event Handlers-

A script written in JavaScript is generally triggered by a line of code that waits for a certain event to happen. This line of code, called an 'event handler,' is usually inserted into the <body>, <img>, <a> or <input> tags on your web page.

Here are three noteworthy JavaScript event handlers:

onMouseOver

This event handler is usually inserted into <a> tags in an HTML file. It is triggered when your mouse moves over the link.

onClick

This event handler is designed to be used with buttons on a form. It is activated when a visitor to your page clicks the button.

onLoad

This event handler can be inserted into <body>, <img>, and <frameset> tags in an HTML file. It is triggered when the web page finishes loading.

We'll learn about the OnLoad and onClick event handlers today. We'll have some fun with the onMouseOver event handler in the next lesson.

-Our First Script-

The following web page contains a snippet of JavaScript:

 <HTML> 
<BODY onLoad="window.status='Welcome to my web page.'; return true;">   
<P>Look below for an important message!</P> </BODY>   </HTML>

See it tucked inside the <BODY> tag? This script, which is triggered when the web page finishes loading, prints a little message on the status bar at the bottom of your browser window.

Try it out: copy the lines above to your favorite text editor, save it as an HTML file, and load it in your (JavaScript friendly) web browser. Check out the gray status bar at the very bottom of the browser.

Note: if you don't have a status bar, see if you can turn it on through the browser's 'View' menu. Also, please remember that JavaScript only works with the Netscape Navigator and Microsoft Internet Explorer web browsers.

Once you've seen the script in action, you're probably dying to know how it works. To make things easier to understand, I'm going to separate the JavaScript from the HTML. The JavaScript portion of the <BODY> tag is reproduced below:

onLoad="window.status='Welcome to my web page.'; return true;"

Chapter 2


Let's dissect this little script. In the process, we'll learn six fundamental rules about scripting in this new language.

-Rule 1-

All JavaScript code is activated by an event handler. The event handler you use determines what event causes your program to run. We chose an event handler called onLoad, which will cause our script to run immediately after the page loads.

onLoad is the most popular event handler in JavaScript. Most JavaScript programmers are proud of their work and want to make the script run immediately and automatically. Using onLoad as the event handler ensures that it will do so.

Please be aware that event handlers are case-sensitive. Typing 'OnLoad' or 'onload' or 'ONLOAD' instead of 'onLoad' won't cut it. Event handlers are also sensitive to typographical errors (typos). If you mis-spell onLoad or put a space or a hyphen or any other character between 'on' and 'Load' (or anywhere else inside the event handler, your script will simply refuse to run.

-Rule 2-

The event handler (onLoad, in this example) must be followed by an equal sign (=). The equal sign tells the browser to get ready to carry out one or more commands each time the event occurs.

-Rule 3-

The commands that follow the equal sign must be surrounded by one pair of double quotes. Again: all of your commands must be surrounded by only one pair of double quotes.

The first double quote should appear immediately after the equal sign.

The second double quote should appear at the end of the last command.

This particular script contains two commands:

Command 1: window.status='Welcome to my web page.';

Command 2: return true;

In the actual script, please notice how command 1 is preceded by one double quote, and command 2 is followed by a second double quote. Only one single solitary pair of double quotes was used to surround both commands.

-Rule 4-

You must place a semicolon (;) at the end of each command. Check the code again. See the semicolon at the end of command 1? See the semicolon at the end of command 2? Those aren't optional.

-Rule 5-

The last command in your script should always be 'return true;'. This command simply lets the browser know that all is well--your script is over and there are no more commands to process.

-Rule 6-

Like the event handler, all of the commands in your script are extremely sensitive to case and typos. You must be very careful to type your commands with a high degree of precision, or your script will not run.

Your job as a new JavaScript programmer will be to familiarize yourself with the commands that form the foundation of this powerful language. Learning JavaScript is a bit like learning to master a foreign tongue--it can take many weeks of concentrated study and practice to achieve a level of proficiency.


Although I will be introducing several commands in this lesson and the next, I will only be scratching the surface of this remarkable programming tool. If this introduction to JavaScript has captured your imagination and you're interested in furthering your JavaScript studies, I can heartily recommend the following pair of fine books:

The JavaScript Bible
Danny Goodman
IDG Books
JavaScript--the Definitive Guide
David Flanagan
O'Reilly Books

Chapter 3


As you have learned, a script written in JavaScript consists of a series of commands. In the sample script above, our script contained the following command:

window.status='Welcome to my web page.';

In a nutshell, this command tells the browser to display the words 'Welcome to my web page.' on the status bar at the bottom of your browser window.

JavaScript has a special name for this region of your browser window: 'window.status'

What if you wanted the status bar to say something else? Well, you'd just need to change the window.status command. For example, if you wanted to write a script that printed the word 'Hello' on the status bar, you might create an HTML file that looks like this:

 <HTML>  
 <BODY onLoad="window.status='Hello'; return true;">
 <P>Look below for an important message!</P>  
 </BODY>  
 </HTML>
Obviously, the window.status command we've been using is not the only weapon in our JavaScript arsenal. Here's another:

 <HTML>  
 <BODY onLoad="alert('Welcome to my site.'); return true;">
 <P>Isn't this a blast?</P>  
 </BODY>  
 </HTML>
Notice that we have given our event handler a new command to work with:

alert('Welcome to my site.');

This command will cause a small dialog box containing the words 'Welcome to my site' to pop up each time your page is loaded in a browser. This dialog box is called an alert() box. An alert() box will display any message that you insert between the parentheses. Please notice that the message itself must be surrounded by single quote marks.

What if you wanted the dialog box to say 'Warning: Kids only!' instead of 'Welcome to my site?' Well, try this code on for size:

 <HTML>  
<BODY onLoad="alert('Warning: kids only!'); return true;"> <P>Isn't this a blast?</P> </BODY> </HTML>
-The onClick Event Handler-

As you have seen, the onLoad event handler will cause your script to run as soon as your page loads.

But let's say that you'd rather let your visitors decide whether or not your script should run. The onLoad handler won't allow that. It forces the browser to begin processing your script commands the instant a visitor loads your page.

The onClick event handler is a bit more flexible. It provides your visitors with the opportunity to activate your script by clicking a button.

In order for this event handler to work, you have to create a form with at least one button. Then, you insert the onClick handler and its associated commands directly into the tag you used to create the button. Here's an example:

 <HTML>  
 <BODY>  
 <FORM>  
 <INPUT TYPE="button" NAME="mybutton" 
 VALUE="Click Me"  onClick="alert('Thanks'); 
 return true;">
 </FORM>  
 </BODY>  
 </HTML>
Notice how our FORM tag does not include a METHOD or an ACTION. This is because we're not interested in creating a real form. The only reason our HTML file includes FORM tags is because most browsers won't display a button unless it is snuggled safely between a pair of <FORM> and </FORM> tags.

At any rate, when your visitor clicks the button named 'mybutton', an alert() box containing the word 'Thanks' will pop up.

Now, let's try creating a form with three buttons, Each button will have an onClick event handler poised to trigger a different script:

 <HTML>  
 <BODY>  
 <P>How many feet are in a mile?</P>  
 <FORM> 
 <INPUT TYPE="button" NAME="button1" 
 VALUE="5,280"  onClick="alert('Correct.'); return true;"> 
 <INPUT TYPE="button" NAME="button2" 
 VALUE="6,000"  onClick="alert('Not quite.'); return true;"> 
 <INPUT TYPE="button" NAME="button3" VALUE="12,684"  
 onClick="alert('Are you insane?'); return true;">
 </FORM>  
 </BODY>  
 </HTML>
If your visitor clicks button1, an alert() box containing the word 'Correct' will pop up. If button2 is clicked, the alert() box will say 'Not quite.' And if button3 is clicked, another message will be displayed.

-Exercise-

Try creating an HTML form containing two buttons arranged just below the question 'Are dogs friendlier than cats?'

Give the first button a value of "Yes".

Give the second button a value of "No".

Use onClick event handlers to generate a different alert() box for each button. I'll leave the content of each of your two alert() boxes up to you.

If you have difficulties, please feel free to post a note on the class bulletin board.

Now, let's try letting our onClick event handler run a completely different kind of command.

Instead of opening an alert() box, let's have our buttons link to other websites:

 <HTML>
 <BODY> 
 <P>Choose your search tool:</P>  
 <FORM>
 <INPUT TYPE="button" 
 NAME="button1" VALUE="Ask Jeeves"  
 onClick="window.open('http://www.askjeeves.com'); 
 return true;"> <INPUT TYPE="button" 
 NAME="button2" VALUE="snap.com"  
 onClick="window.open('http://www.snap.com'); return true;"> 
 <INPUT TYPE="button" NAME="button3" VALUE="Metacrawler"
 onClick="window.open('http://www.metacrawler.com'); 
 return true;"> 
 </FORM>  
 </BODY>  
 </HTML>

If one of the buttons on your form is clicked, your script will open a new browser window and load the page located at the address you specified.

Chapter 4


Most of the scripts you'll type will be too long to tuck neatly into a <BODY> or <INPUT> tag. If a script gets a bit lengthy (four or more commands), you might want to type the script at the beginning of your HTML file instead. You can then give the script a name and call it up as needed.

JavaScript programmers refer to these sorts of scripts as 'functions.' A function is just a script that:

a) is located at the beginning of your HTML file;

b) has been assigned a name; and

c) can be called upon by name when needed.

Although the first script we created today wasn't anywhere near long enough to warrant being converted to a function, here's how it would have looked as a function:

 <HTML>  
 <HEAD>  
 <TITLE>Our first function!</TITLE>  
 <SCRIPT language="JavaScript">  
 <!--
 function Howdy(){window.status="Hello there!";} 
 //-->
 </SCRIPT>  
 </HEAD>  
 <BODY onLoad="Howdy(); return true;">  
 <P>Voila!</P>  
 </BODY>  
 </HTML>

In this example, we named our function Howdy() and defined its purpose at the beginning of our HTML file (inside the HEAD). Later in that same file, the onLoad event handler called upon the function.

Here are six important points to remember about functions:

1. Functions go inside the <HEAD> of your HTML document.

2. Functions begin with a <SCRIPT> tag and end with a </SCRIPT> tag.

3. Because some (antiquated) browsers react unpredictably when they encounter Javascript, you must surround all your code with one big comment tag. You must open the comment tag by typing <!-- on its own line, just after you type the <SCRIPT> tag.

Then, you close the comment tag by typing //--> on its own line, just before you type the </SCRIPT> tag.

Because old browsers ignore everything they find inside of a comment tag, your program code won't cause a JavaScript- hostile browser any grief.

4. Next, you must declare that you are creating a function by typing the word 'function' followed by a space and the function name. The function name can contain letters or numbers, but cannot contain spaces. The function name must end with a pair of parentheses ().

5. After you name the function, it's time to type the commands. Each command must end with a semicolon (;). All the commands put together must be surrounded by one single pair of curly brackets {}.

6. You call the function by typing its name (don't forget the parentheses) in an event handler as if the function name were a command.

-Bonus Lesson- The scroll() Function

Here's a JavaScript classic: the scroll() function. It will take any message you choose to type and set it in motion on the status bar.

First, the function stores your message in memory, using a storage device called a 'variable.' The function then automatically calculates the width of your message and displays the message on the status bar of your browser window.

One twist: the function keeps recalculating and changing the position of your message. This causes the message to scroll from right to left across the status bar!

This function is quite a bit more sophisticated than my first example--it contains quite a bit of mathematics, looping, decision making, and other capabilities that are a bit more advanced than we're ready to explore.

Don't worry too much right now about what's happening on each individual line of the function. Instead, notice how all the rules we set above are followed:

-The function is inside the <HEAD> of the HTML file.

-The function is surrounded by <SCRIPT> and </SCRIPT> tags.

-The function is inside a comment tag.

-The word 'function' is followed by the function name scroll().

-The function name ends with a pair of parentheses.

-All the commands in the functions are surrounded by curly brackets.

-The function is called by an event handler in the <BODY> tag.

-The event handler is followed by an equal sign.

-The commands in the event handler are surrounded by quotes.

-Each command in the event handler ends with a semicolon.

-The last command in the event handler is 'return true;'.


<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- 
var str=""; 
function scroll()
{
  if (str == "")
  {
    for (var i = 0; i < 120; i = i+10) 
    {
      str = str + "          ";
    }
    str = str + "Place your text here";
  }
  else
  {
    str = str.substring(2, str.length);
  }
  window.status = str;
  window.setTimeout('scroll()',100);
}
//-->
</SCRIPT>
</HEAD>
<BODY bgcolor="white" onLoad="scroll(); return true;">
<p>Look below!</p>
</BODY>
</HTML>

Go ahead and give this JavaScript function a whirl! The only thing you'll have to change is the message between the quotes on the line reproduced below:

 str = str + "Place your text here";

How it works: Before our function begins, we create a variable named 'str' to hold our scrolling message. Initially, we give it a value of "" (nothing).

var str="";
Once our function begins, we perform a test to see whether the var named 'str' has a value of "" or not.

if (str == "")
If the variable named 'str' has a value of "", then we know our function has not yet run. What we'll do now is use the variable named 'str' to store a whole bunch of spaces.
for (var i = 0; i < 120; i = i+10)     
{      
str = str + "          ";    
}
The lines above create a loop that runs over and over again, adding more and more spaces to 'str' until it is big enough to fill your status bar with spaces.

Next, we add your message to the end of 'str,' after all the spaces.

str = str + "Place your text here!";
If the function has run before, we do something else--snip the first two characters off of 'str.' This causes your message to shift leftward.

else
{
  str = str.substring(2, str.length);
}
Now, let's take the value of 'str' and place it on the status bar of our browser window:

window.status = str;
Finally, let's ask the function to pause for 100 milliseconds (0.1 sec) before it runs again.

window.setTimeout('scroll()',100);

In the next lesson, we'll learn more about this fascinating language and how it can be used to add a level of interactivity to your web pages.

Chapter 5


-Quiz 8-

When you feel you have a grasp on all of the concepts taught within this lesson, I would like you to take a short, multiple choice quiz. To get to the quiz, click on 'Quizzes' on the menu bar. When the form comes up, input your last name, e-mail address, and password, and make sure you have 'Quiz 8' selected.

Good luck!

-Assignment F-

Click here to preview the page that we'll be creating in this assignment. Click on the 'Assignments' link at the top of this page. When the 'Assignments' page appears, click fill out the form with your name, e-mail address, and password, and click on Assignment F. Then, click on the 'Submit' button. A form will appear with numbered text boxes. Fill in each line of code exactly as specified below. When you're typing a tag that contains multiple parameters, please include the parameters in the order specified in the directions below. When you're done, click on the 'Validate' button and your assignment will be validated for accuracy.

Line 1 - Type a tag that will open your HTML document.

Line 2 - Type a tag that will begin the BODY portion of your page.  Include a bit of JavaScript within the tag that will make a dialog box appear when the page is loaded.   The dialog box should say:

Hello

Line 3 - Type a tag that will create center aligned text that is a heading size '2.'

Line 4 - Type the following text:

JavaScript is fun!

Line 5 - Close the tag that created your size 2 heading.

Line 6 - Close the tag that created the BODY portion of your page.

Line 7 - Type a tag that will close your HTML document.

Chapter 6

When you feel you have a grasp on all of the concepts taught within this lesson, I would like you to take a short, multiple choice quiz. To get to the quiz, click on 'Quizzes' on the menu bar. When the form comes up, input your last name, e-mail address, and password, and make sure you have 'Quiz 8' selected. Good luck!

IMPORTANT: This version of your lesson is for saving or printing only. All links and images have been disabled to decrease download time and help you avoid printer difficulties. Do NOT attempt to click any of the links on this page.

Copyright 1999 by ed2go.com. All rights reserved.
No reproduction or redistribution without written permission.

1