Javascript Tutorial

by Boris Mordkovich

INTRODUCTION

As I got farther into web development I wanted to go beyond the limitations of HTML. HTML cannot make decisions, be very interactive, or store information. Javascript was the answer. It was developed by Netscape and was originally called LiveScript. The name was later changed to show the relation to Java. Now it is supported by both of the most popular browsers, Microsoft Internet Explorer and Netscape Navigator.

Note: Parts of this tutorial assume you know HTML. If you do not, consider reading this tutorial on HTML first. This tutorial is lengthy but very thorough.

CONTENTS

Part 1 - Defining a Script
Part 2 - Creating a Simple Script
Part 3 - Variables, Strings, and Arrays
Part 4 - Testing and Comparing Variables
Part 5 - Loops and Functions
Part 6 - Objects
Part 7 - Events

Part 1 - Defining a Script

There are 3 places you can define a script.

  1. The first place you can define a script is within the head of the HTML document. Scripts here aren't automatically executed when the page loads but can be referred to by other scripts within the document.
  2. The next place you can define a script is within the body of the HTML document. Scripts here are executed as the page loads.
  3. The last place you can define a script is within an event handler. You will learn more about these later.

When defining scripts in the head and body of HTML documents you are required to use a script tag, while if you are defining a script within an event handler, this tag is not required.

You can include the src attribute to the script tag if you would like to save your script to an external file and include it in the HTML file. Remember to use the .js extension when saving Javascript to an external file.
     <script src="menu.js">
The above would include the Javascript from the menu.js file.

THE <script> TAG

When defining scripts in the head and body of HTML documents you are required to use a script tag, while if you are defining a script within an event handler, this tag is not required.

There are several attributes that you can use other than the src attribute you learned about earlier. You can also include the language attribute. This allows you to define the script within the script tag as being Javascript. You can also define the version of Javascript. You can put the type attribute, it will always be text/javascript. None of these are necessary but they will help with compatibility for older browsers. If a browser does not support that version of Javascript, instead of displaying errors, it will not run the script. The below statement defines a Javascript with the version of 1.3 and using the external menu.js file.
     <script language="JavaScript1.3" src="menu.js" type="text/javascript">

JAVASCRIPT VERSIONS

  • Javascript 1.0 - supported by Netscape 2.0 and Internet Explorer 3.0
  • Javascript 1.1 - supported by Netscape 3.0 and mostly supported by Internet Explorer 4.0
  • Javascript 1.2 - supported by Netscape 4.0 and partially supported by Internet Explorer 4.0
  • Javascript 1.3 - supported by Netscape 4.5

OLDER BROWSERS

To hide your scripts from older browsers you can enclose them with comments (just the script, not the script tag).
     <script language="Javascript">
     <!--
     your script here
     // -->
     </script>

You can also include the <noscript> tags to display content for visitors with browsers that don't support Javascript.

JAVASCRIPT COMMENTS

You can use comments for the same things you use them in HTML, to include notes to remind you of the purpose of certain parts of the page. There are two ways to include comments.
     // this would be a comment
Using the two forward slashes (//) hides everything on that line. If you need to make more than one line a comment you would use the following method.
     /*
     this would be a comment
     this would also be a comment
     */

Everything after the /* and before the */ becomes a comment.



Part 2 - Creating a Simple Script

In this section you will be creating a script to ask the user for his/her name and then write it to the page. This section isn't meant to teach you much about Javascript, but it is aimed more as an introduction so you can see the basics of Javascript.

GETTING THE USER'S NAME

To get the user's name we must use the prompt() method. We will enclose the prompt within a function and execute the function once the page loads. Then we will use the user's input to print a welcome message (don't worry if this doesn't make much sense to you at this point, it will in time). Let's start by defining the function. It should be within the <script> tags in the head of the page.
     function getNames() {
     }

This is a basic function. We won't get too in depth with functions here, you will learn more about them later. Let's ask the user for his/her name next.
     function getNames() {
     first = prompt('Please enter your first name.');
     last = prompt('Please enter your last name.');
     }

This would ask the user for his/her name and then store it as the variables first and last. Also, make sure to include these inside the braces, this is necessary to make it part of the function. Now we need to make this execute when the page loads. We need to add the following to the body:
     <body onload="getNames()">
This will execute the function once the page loads.

WRITING THE WELCOME MESSAGE

Now that we have gotten the user's name, we need to make it part of a welcome message. You can do it one of two ways:
     Welcome <script></script>!
or
     <script></script>
I personally prefer the last way but if the first one is easier for you, by all means use it. They will both result in something like the following:
     Welcome George Washington!
Notice that in the script I included a space between the names. The variables, first and last, do not have to be inside quotations, but the exact text that you want to appear along with those, the spaces and in the last one the welcome and exclamation point, must be. The issue of when to use quotations is discussed later.

As I said before, this chapter was meant to introduce you to various parts of Javascript, not to teach you all about them. You will learn in later chapters about these things in more detail.



Part 3 - Variables, Strings, and Arrays

VARIABLES

A variable is like a container used for storing information. This is one of the easiest and most often used parts of Javascript. Lets get to an example so you can see exactly what a variable does.
     var message = 'This is a test message';
Now lets discuss all of the parts to this variable; first, the var keyword, we will discuss it a little later; second, the variable's name is defined as message; third, the = operator assigns a value to the variable; forth, the opening quotation (the quotations can be either single quotes or double quotes), we will also talk about these more in-depth later; fifth, we have the variables value; sixth, we have the closing quote; and last we have the ;, it is used to end lines of Javascript (remember, Javascript is sensitive to where you end lines).

Types of Variables

Lets talk about the var keyword. This defines the variable as being a global variable. It should be defined outside any functions. Because it is a global variable it can be used within any script in that HTML document and within any functions. The other type of variable is a local variable. A local variable is used specifically for a function and is defined within that function. A local variable does not need the var keyword.

STRINGS

     var message = 'This is a test message';
Strings are variables that consist of a string of text. The variable above was an example of a string. Strings are one of the most simple kinds of variables.

There are several different methods and properties of strings you should be aware of. For starters, the length property.
     var test = message.length;
The above statement would result in the value of test equaling 22 because if you count each character in the message string you will end up counting 22 characters.
     var up = message.toUpperCase();
     var lower = message.toLowerCase();

These two methods are used to change the case of a string. They would result in up equaling THIS IS A TEST MESSAGE and lower equaling this is a test message. You can also use substrings, or parts of strings.
     var sub = message.substring(0,7);
The variable sub would equal This is. Notice that the indexing of the string starts at 0. If you were to put sub = message.substring(1,7) it would result in sub equaling his is. You can also get a single character, sub = message.substring(7);. Sub would equal s.

You're not done yet, Javascript still has more things you can do with strings. The next thing you can do is to search for a substring.
     var index = message.indexOf('test');
Index would then equal 10 because the substring test starts at the 10th character.
     var index = message.indexOf('test', 5);
This would return the same value for index but instead of starting at the beginning of the string, Javascript starts searching at the 5th character. This is great for searching for multiple occurrences of the substring.
     var index = message.lastIndexOf('test');
This would again return the value of ten but this time Javascript searches from the end of the string backwards.

You can also split strings, but we will learn about that when we get to arrays. You can also use all of the numbers these methods and properties return in mathematic calculations. We will learn about storing numbers as variables next.

NUMBERS

     var total = 3 + 6;
Javascript is capable of mathematics. For instance, the above statement would result in the value of total equaling 9. Because the value of total is a number you can then use it later in another statement.
     var max = total + 3;
The above two statements would result in the value of max being 12 because the value of total (9) was determined in the first statement and by adding 3 to total, it would be the same as saying 3 + 9. You will later learn that being able to store numbers in variables can be very useful.

If you have a string that contains a number at the beginning of it, you can use that number in calculations.
     var elephants = '30 elephants in the group';
     var totalElephants = parseInt(elephants);

TotalElephants would equal 30. You could then use the number 30 in calculations. parseInt() gives you a whole number while parseFloat() will give you a decimal number (if a decimal is needed). This comes in very handy when you are getting variables from forms because a number can be inputed into a text field (any information in a text field is, by default, treated as a string) and then that number can be used in calculations by using parseInt() and parseFloat(). You can add (+), subtract (-), multiply (*), divide (/), round up (Math.ceil()), round down (Math.floor()), and round (Math.round()) numbers.

ARRAYS

     var students = new Array(6);
     students[0] = 'John';
     students[1] = 'Sue';
     students[2] = 'Bob';
     students[3] = 'Billy';
     students[4] = 'Jane';
     students[5] = 'Jill';

Arrays are very useful and not very complicated once you get use to them. They are used to store a list of variables. Let's analyze all of the parts to this array. Students is the variable that holds this array. Notice all of the parts to the first line, the variable name students, the = operator, the new keyword, the array(), and the ;. The number 6 declares that the students array is 6 variables long, this is not necessary but is nice to include. If you need the length (the number of variables) of the array you can use students.length. On the following lines there are several more variables, all called students, but notice the brackets and the index for each and notice that the indexing of the variables starts at 0. Each of the variables under the student array are strings. You can make each of those variables strings, numbers, arrays, or objects. You can also sort arrays.
     var sorted = students.sort();
Sorted would then be an array that contained all of the variables in the students array but they would be in alphabetical order. Therefore students[3] and sorted[0] would both equal Billy.

You can also split strings. The reason I mention this in the array section is because Javascript stores the parts of the string in an array.
     var message = 'This is a test message';
     var parts = message.split(' ');

Parts would then equal an array with 5 variables. If you were to write out what the parts array looked like, you would get the following.
     parts[0] = 'This';
     parts[1] = 'is';
     parts[2] = 'a';
     parts[3] = 'test';
     parts[4] = 'message';

You can also use the join() method. It is used to join all of the variables in an array into one string. By default Javascript uses a comma but you can use whatever you want.
     var whole = parts.join('_');
Whole would then equal This_is_a_test_message.

You can also treat each variable in an array as if it weren't in an array.
     var students = new Array(6);
     students[0] = 'John';
     students[1] = 'Sue';
     students[2] = 'Bob';
     students[3] = 'Billy';
     students[4] = 'Jane';
     students[5] = 'Jill';

Because each variable in the students array is a string, you can use students[0].length to get the number 4 because 4 is the length of the students[0] string.

WHEN TO USE QUOTATIONS

When you use quotations largely depends on what type of variable you want or if you are trying to define a new one.
     var number = 4;
     var number = '4';

What is the difference between these two statements? Well you obviously noticed that the second one has quotations but the first does not, but what does that really mean? It tells Javascript to interpret the first as a number and the second as a string.
     var number = four;
     var number = 'four';

Again, what do the quotations mean here? Here the quotations tell Javascript to look for another variable named four in the first statement and define number's value as being the same as four's; the second statement tells Javascript to interpret number's value as equaling the string four, regardless of another variable named four's value.



Part 4 - Testing and Comparing Variables

THE if KEYWORD

The if keyword is one that you will use over and over again in Javascript. It is used to test and/or compare a variable. Lets get to the example.
     var name = 'John';
     if (name == 'Bob')

I admit, this isn't a very practical use for the script. The statement is basically saying if name equals Bob write Bob Curtis. But analyze the parts of the script, the name variable, the if keyword, the parentheses, the variable to be tested (name) the == operator, the string used to test the variable, and what to do if the statement is true.

OPERATORS

Operators are used to compare variables (such as the == operator above); they consist of two groups, conditional and logical.

Conditional

Conditional operators are the syntax used to compare the two variables.
==is equal to
!=is not equal to
<is less than
<=is less than or equal to
>is greater than
>=is greater than or equal to

Logical

Logical operators are the operators you use if you want to compare more than two variables.
&&and
||or
Just to give you an idea of how logical operators work, check out the syntax below.
     

THE else KEYWORD

If you are using several if statements to test the same variable and you want to include a choice that will be executed if none of the previous statements are true, you should use the else keyword.
     if (name == 'Bob')
     else if (name == 'Sue')
     else

The above statements would check to see if name equalled Bob and because it didn't it checked to see if name equalled Sue, if it reaches the else keyword and none of the above if statements have been true Javascript executes whatever is after the else keyword.

MORE COMPARISON

This section is sort of a miscellaneous section about comparisons.

Including More Executions for True Statements

Notice that in previous comparisons only one thing has been done if the statement has been true, you can use a different syntax to include many executions.
     if (name == 'Bob'){
       
       alert('Bob Curtis');
     }

(I know the alert() method is new, it is similiar to the prompt() method and the indentions aren't necessary but they do help to make the script a little easier to read).

The main difference here is that instead of including one item to execute if the statement is true you put braces around the things you want executed. You don't have to put the braces on separate lines but it makes your script look nicer and easier to read. You can also use this method for the else keyword.
     if (name == 'Bob'){
       
       alert('Bob Curtis');
     }else{
       
       alert('John Smith');
     }

True/False Comparisons

If you need to check a variable and do one thing if it is true and another if it is false check out the syntax below.
     (name == 'Bob')?document.write('Bob Curtis'):
First, you put the comparison; second, a question mark; third, what to do if the comparison is true; fourth, a colon; fifth, what to do if the comparison is false; last, the ending semicolon.

Using switch

If you need to use multiple if statements in a row to test the same variable for different occurrences.

You can write -
     if (name == 'Bob')
     if (name == 'Sue')
     else


you could use -
     switch (name){
       case 'Bob':
         
       break;
       case 'Sue':
         
       break;
       default:
         
       break;
     }


This performs the exact same thing as the series of if statements. This isn't a very practical use for switch, but you will find instances where it can become very useful.

Elements of the switch statement include:
  1. switch keyword
  2. parentheses enclosing the variable to be tested and the opening braces
  3. case keyword followed by the value you want to compare the variable to and a colon
  4. the statements to be executed (you can include multiple statements on multiple lines)
  5. break (this tells Javascript to stop executing statements, it is equivalent to the ending brace in an if statement)
  6. then comes the process repeated for every value used to test the variable and the end brace


Part 5 - Loops and Functions

Loops are pretty much what you would guess; they are used to repeat certain statements for a specified number of times. Loops can make the length of script decrease tremendously in size, thus saving you lots of time and effort.

THE for LOOP

For loops are used to repeat certain statements a specified number of times using a counter. Usually this counter is a number and has one added to it or taken away from it each time the loop executes. Time for an example.....
     for (i = 1; i <= 5; i++){
     
     }


Many people use the i variable as a counter. If you look at the scripts of many people you will often notice this. It is a very old programming tradition that started with a very old programming language called Forth.

Let's analyze what this script actually does. The loop is started by the for keyword and then it establishes a variable (the counter), the value to test the variable with, and how the variable is to be changed each time the loop executes and it also contains braces around the statements that are to be executed. In simpler terms, this script executes 5 times with value of i having one added to eat each time the loop executes. You use the same operators you used in the last chapter to compare values.

The result of the script would be 5 messages with a line break after each. It would appear like the following.
     Test message #1
     Test message #2
     Test message #3
     Test message #4
     Test message #5

THE while LOOP

While loops are usually used when you don't have a counter.
     var i = 1;
     while (i <= 5){
     
     }

This would achieve the same affect as the for loop above. Like I mentioned, you don't have a counter with while loops.

THE do...while LOOP

     do {
     
     }
     while (i <=5);

do...while loops are a lot like while
loops but they check the variables at the end of the loop instead of the beginning. This means that the loop will execute at least once.

MORE ON LOOPS

Starting/Stopping a Loop

To stop the loop you use the break keyword; you use the continue keyword to skip the rest of the current statements and test the variables again.
     while (i <= 5){
     
     if (i == 4) break;
     }

The above is an example of the break keyword. If you notice, in this example the break is kind of pointless. It would be much easier to change the loop itself, but you get the point of how the break keyword should be used.
     while (i <= 5){
     if (i == 4) continue;
     
     }

This would skip the write statement and test the variables again. The result would look like the following.
     Test message #1
     Test message #2
     Test message #3
     Test message #5

Infinite Loops

Infinite loops are something you generally want to avoid. Because the loop will never end, it can cause problems with the browser or even cause it to crash. Let me show you an example of an infinite loop so you can have a general idea of how they get started.      
     while (i < 5){
     
     }

Notice that the value of i doesn't change during the loop. This means that if i is less than 5 the loop will never stop executing and if it is greater than 5 it will not execute at all.

FUNCTIONS

Essentially, you should not have any problems understanding functions by now.
     function write(message){
     
     }

This would create the write function. You can give almost any name to your function (some names cannot be used because they are methods, names such as prompt) and you can include any number of statements inside the braces. The purpose of this function would be to write the text you send it.
     write('This is a test message');
This statement would call the function and send it the text - This is a test message. The text you send the function is stored in the message variable in this function. You can use it just like any other string. You do not have to have a function that requires a variable sent to it and you can also have multiple variables sent to it. Check out the examples below.
     function ask(prompt1, prompt2){
     pro1 = prompt(prompt1);
     pro2 = prompt(prompt2);
     
     }

This example shows how you can have multiple variables sent to the function. And below shows how you do not have to have a variable sent to the function.
     function greet() {
     alert('Welcome to EchoWeb! \n http://echodev.com/');
     }

You may be wondering what the \n does. Well, it is equivalent to a <br> in HTML. The difference is Javascript will ignore a <br> and HTML will ignore a \n. You have to be careful when you use them....



Part 6 - Objects

This is most likely the largest chapter of the entire tutorial and one if not the most complicated. You might want to read it in pieces and probably more than once, especially the part on custom objects.

UNDERSTANDING PROPERTIES AND METHODS

You have already used several objects but chances are you haven't realized it. You have used several objects such as the string and array objects. You can actually define strings by using the following syntax.
     var message = new String('This is a test message');
All objects are introduced by the new keyword. You have also used several properties and methods. Think of properties as variables that are in a container (the container being the object) and think of methods of being functions specific to a certain object. You have already used the length property of the string object. You have also already used the toUpperCase() and toLowerCase() methods. You can access the properties and methods by using the objects name followed by a period and the property or method like the following.
     message.length
     message.toUpperCase()

The above, as you should know, would return 22 and THIS IS A TEST MESSAGE. Objects can also contain other objects. For example, an array object can contain several string objects or even more array objects which would in turn contain additional objects. You should be beginning to realize the complexity of some parts of Javascript by now.

USING DATES

Javascript uses the number of milliseconds from midnight January 1, 1970 to store dates. This is called the epoch and any dates/times before then are not allowed. That means many programmers, unlike me, cannot store their birthday in a date object because it is before January 1, 1970.

   someday = new Date();
     someday = new Date('March 31, 2000 10:07:00');
     someday = new Date(3, 31, 2000);
     someday = new Date(3, 31, 2000, 10,07,00);

All of the above formats are correct. They will all store the same date and time (notice not all will store both date and time though). The first format will use the current date and time while the last 3 have a specified day and/or time.

Setting/Getting Dates

You can also set dates/times once the date has been established. You can use the following methods.
     setDate() - sets day of the month
     setMonth() - sets month
     setFullYear() - sets 4-digit year
     setTime() - sets time (and date) by specifying the number of milliseconds since January 1, 1970
     setHours() - sets hours
     setMinutes() - sets minutes
     setSeconds() - sets seconds
These are all methods so the following example would change the day of the month for the date someday from 31 to 1.
     someday.setDate(1)
You can't obtain the values in a date as properties; you must use the following get methods.
     getDate() - gets day of the month
     getMonth() - gets month
     getFullYear() - gets 4-digit year
     getTime() - gets time (and date) by specifying the number of milliseconds since January 1, 1970
     getHours() - gets hours
     getMinutes() - gets minutes
     getSeconds() - gets seconds

More with Dates

There are a few more things you can do with dates, such as converting between time zones and between date formats.      getTimeZoneOffset() - gets the offset from GMT (Greenwich Mean Time, also known as UTC)
     toGMTString() - converts date object to a string using GMT
     toLocalString() - converts date object to a string using local time
     Date.parse() - converts a string, such as April 4, 2000, to a date object
     Date.UTC - converts a date object to GMT

UNDERSTANDING DOCUMENT STRUCTURE

You can think of document structure as being similar to a tree because everything branches out from one object. You have already used document.write(). write() is actually a method of the document object and document is actually a child object of the window object. To use the write() method you could also use window.document.write(). (You can use document.write() instead of window.document.write() if you are working with a script that deals with only one window, Javascript will assume you mean the current window if you do not include the window object here.

I use the words "child" and "parent" often when talking about document structure and you may be wondering what they mean. A parent object is an object that contains another object. The object that is contained by the parent object is called the child object. (For instance, the document object is the child object of the window object therefore making window the parent of document)


To access objects, properties, or methods farther down in the document hierarchy you should include each parent object of the object, property, or method you are trying to use separated by a period.

WRITING TO A DOCUMENT

You have already used document.write() to write to a document. You can also use document.writeIn() to write to a document and include a newline character (\n) at the end. You can also use document.open() and document.close(). These don't actually write anything and they don't open or close a window, like window.open() and window.close(). document.open() opens the current document so that you can include several write() statements that will execute at the same time. After the write() statements you should include document.close(). This will clear the current document and display the content in the write() statements.

BROWSER'S HISTORY

One popular use of Javascript is to include back and forward buttons. You can use history.back() for a back button and history.forward() for a forward button but there is a better way. The back() and forward() methods do not work correctly in some browsers. You should use history.go() instead. You can use history.go(-1) for back and history.go(1) for a forward button. The go() method is more widely supported, so you should use it instead. You can include any number within the parentheses, negative for the number of pages to go back and positive for the number of pages to go forward (history.go(-5) is the equivalent of hitting back 5 times and history.go(5) is the equivalent of hitting forward 5 times). You must remember though that if the visitor does not have the number of items in his/her history folder that you use for your back or forward button they cannot go back or forward that many times.

Remember that when you are working with dates that the accuracy of the date or time depends largely on the accuracy of the clock on the computer from which the page is being viewed

THE location OBJECT

You can also change and receive the location of the page with Javascript. You can even load two frames or windows at once
     location.pathname - location of the window (the location in the address bar, ex. http://w3nation.com/)
     location.reload() - refreshes the page
     window.location = ' ' - you can define the location of a document just like a variable
     window.location.replace("") - takes you to another page without storing it in history

GETTING INFORMATION ABOUT THE DOCUMENT

You can get lots of information about the document using Javascript. You can access things such as the title, referrer, last modified date, location, background color, etc. Here are a couple of things I commonly use when scripting.
     document.title - title of the document (defined by the <title> tag)
     document.referrer - the page the visitor came from
     document.lastModified - the date the page was last modified (sent from the server, so Javascript depends on server accuracy and support for this feature)
     history.go() - used for back and forward buttons, use history.go(-1) for back and history.go(1) for forward
     location.pathname - location of the window (the location in the address bar, ex. http://w3nation.com/)
     document.location - location of the document (the location of the page)
The difference between the last two is that if you have frames on your page location.pathname will show the location of the frameset and document.location will show the location of the individual page.

CREATING CUSTOM OBJECTS

Now you're getting to some of the more complicated parts of Javascript (you might consider reading this section more than once). With a custom object you start pretty much from the ground up. You create the object, the properties, and the methods.
     function favorite(title, description, address){
     this.title = title;
     this.description = description;
     this.address = address;
     this.list = list;
     }

     function list(){
     
     
     
     }

Now your probably saying, what in the world is that suppose to mean? You start out with a custom object by defining a function. The name of the object is the same as the name of the function, favorite. Then you list all of the properties and methods. Every property and method includes the this keyword followed by a period and then the name of the property and method. If you will notice, there are three properties (title, description, and address) along with one method
(list()). The only difference is that this.list leads to another function instead of a variable. As you notice, all of the properties are used like any other variable except they have the this keyword and a period in front of them. Let's create a favorite object so you can see just what this script would do. There are two ways you can do this, let's look at both.
     w3nation = new favorite('w3nation', 'W3Nation: Where Everyone Has Access to the Code', 'http://w3nation.com');
     w3nation.list();

You could also use the following.
     w3nation = new favorite();
     w3nation.title = 'W3Nation';
     w3nation.description = 'W3Nation: Where Everyone Has Access to the Code';
     w3nation.address = 'http://w3nation.com';
     w3nation.list();

Both ways would work equally well. You can also use the methods more than once and you can define the properties at any time during the script. Both of the above examples would return the following.



This script would help you to display a large list of links in a nicely formatted manner. Most scripts use objects in this way, you send the object some info and it returns the info after it is formatted. Of course this script isn't all that complicated or elaborate, you can get extremely complicated when it comes to objects. I have seen several card games that use objects to store each card. If you think about 50+ objects in one script, you begin to get my point about how complicated a script can get.

ADDING TO OBJECTS

You can also add more properties and methods to objects that have already been created using the prototype keyword. One example is using the prototype keyword with the string object to create headings.
     function heading(level){
     if (level == 1 || level == 2) {
     head = '<p><b>';
     end = '</p></b>';
     }
     if (level == 3 || level == 4) {
     head = '<p>';
     end = '</p>';
     }
     text = this.toString();
     text = (level == 1 || level ==3)?text.toUpperCase():text;
     return head + text + end;
     }
     String.prototype.toHeading = heading;

     document.write('Test Heading'.toHeading(1));
     document.write('Test Heading'.toHeading(2));
     document.write('Test Heading'.toHeading(3));
     document.write('Test Heading'.toHeading(4));

This script would format the headers of a page much like that of this tutorial. The write statements would return the following.



Part 7 - Events

EVENT HANDLERS - USING THE MOUSE

Javascript can also execute on events, when something happens to the browser. All executions made by Javascript do not have to be made in a certain sequence. Event handlers are used to tell the browser what to do when a particular event occurs.
     <a href="#" onMouseOver="alert('This is a test link.')">Test Link</a>
This syntax would display an alert message when you move the mouse over. Test Link, that link would be the equivalent to the above syntax. As you can see when you move your mouse over the link you get an alert. This is your basic event. You can also use the following events.
     onClick="" - executes when the user clicks the mouse button
     onDblClick="" - executes when the user double clicks the mouse button
     onMouseOver="" - executes when the mouse is over the object
     onMouseOut="" - executes when the mouse goes off of the object
     onMouseDown="" - executes when the user presses the mouse button
     onMouseUp="" - executes when the user releases the mouse button
One thing about using event handlers with links is that the event handler is executed before the page changes. This means you can keep the page from changing (remember though, this could confuse and/or annoy your visitor). If your onClick event handler returns false the page will not change. You can use a confirm to make sure the user wants to leave your site.
     <a href="#" onClick="return confirm('Are you sure you want to leave this site?')">Leave this site</a>
If you click that link it will give you a confirm message and if you click OK the page will change but if you click Cancel the page will not change. This works because of the event handler receives a false value it does not execute the link. You could also use this in a more complicated script. As long as the event handler does not receive a false value it will execute the link.

EVENT HANDLERS - USING THE KEYBOARD

With Javascript 1.2 and 1.3 you can also respond to the events caused by the keyboard. I use the following script to capture key commands. I will explain it to you so that you can create your own, but you are free to use the one given if you wish. (Note: The numbers aren't needed, they are simply there to help you)
1.     if(document.layers){
2.     document.captureEvents(Event.KEYPRESS)
3.     }
4.     document.onkeypress=kpress;
5.
6.     function kpress(e){
7.     key=(document.layers)?e.which:window.event.keyCode
8.     key2=String.fromCharCode(key)
9.     if (key2=="," || key2=="<'"){
10.   left();
11.   }
12.   if (key2=="." || key2==">"){
13.   right();
14.   }
15.   }

The first 4 lines of this script are pretty much going to stay the same. They make sure that both Netscape and Internet Explorer will capture the keyboard events. The only thing that you would probably change is the last part of the 4th line, you could change the name of the function that is executed each time a key is pressed. You could change the name of the kpress function to anything you want (as long as you change it in line 6 as well). So each time a key is pressed the key that is pressed is sent to the kpress function. Next the key variable to an index number. Both IE and NS index the keyboard by a number but they sometimes use different indexes, thats where the key2 variable comes in. The key2 variable takes the index value stored in the key variable and makes it a string. Then you can check to see what key the user pressed with a series of if statements. Instead of executing a command onKeyPress you can also execute a function with 2 more events.
     onKeyDown - executes when the user presses a key
     onKeyUp - executes when the user releases the key. To use these you would need to add insert document.onkeypdown=kdown; and document.onkeyup=kup; after line 4. Then you need to make 2 new functions called kdown and kup. Remember, this is the script I use for capturing keyboard events, you can use any script you wish.