School Map:  Home / Enroll $ Student Records; Class  
$ News @ LIVE Tech Radio * Support/FAQ | Store

Script School JavaScript Course #7 - Week #1

Printable Version of this page HERE

What JavaScript can and cannot do

With JavaScript You can create friendly, dynamic user interfaces that are formatted in HTML. Javascript is a set of instructions that run on the surfer's computer - in their internet browser program. These instructions or 'scripts' can run while a page is being organized for viewing, and while a page is being viewed.

JavaScript Can:

JavaScript Can't:

    We will discuss sending information to a web server, through input forms, in Week #2.
     Loading information into JavaScript from a web server will be introduced in Week#5.

Getting Started

Tools

Web pages are basically text files that have been saved with the suffix '.htm' or .html'.  Simple text editors such as Notepad and Wordpad included in Windows and SimpleText on the Mac are sufficient to write both HTML and JavaScript.  More sophisticated programs are available that include ways to ease page creation, scripting and uploading. A few of these are: Arachnophilia(free!), 1st Page 2000(free!), Web Notepad(free!), CoffeeCup, HotDog, Adobe GoLive, Dreamweaver, or, if You're on OSx or Linux You might want to try bluefish(free!).  These are merely a few suggestions, not endorsements.  Many other HTML/JavaScript editors are available. Professional editors have JavaScript debuggers built in and are also excellent for server side scripting and databases.

Adding Scripts

JavaScript 'lives' inside HTML, and goes inside the HEAD and/or BODY tags. Script in the HEAD can be run before the BODY loads and remain available to scripts in the BODY. Scripts in the BODY are usually associated with Event Handlers that affect objects like links, buttons and forms. Scripts in the BODY can also be used to write a formatted HTML document 'on the fly', perhaps deciding on output according to conditions.

Most JavaScript code is bracketed within <SCRIPT> tags that tell the browser to read it as JavaScript. HTML comment tags <!--  --> nested inside, tell browsers that can't understand JavaScript, that they should not output Your script as text to the screen.  Event Handlers don't use the <SCRIPT> tag. We'll discuss JavaScript that's associated with Event Handlers later in this weeks class.

If You are pasting or writing scripts into the HEAD of Your HTML document, ALL of them can go inside one set of the nested HTML comment and script tags.
Otherwise, folks who have their browsers set to ask permission before running scripts will get multiple requests.

   <HTML>
      <HEAD>
         <TITLE>~~~~~~~</TITLE>
         <SCRIPT LANGUAGE=JAVASCRIPT TYPE="TEXT/JAVASCRIPT">
            <!-- 
               // SCRIPT GOES HERE
			    // line_of_script;
            //-->
         </SCRIPT>
      </HEAD>
      <BODY>
          <SCRIPT LANGUAGE=JAVASCRIPT TYPE="TEXT/JAVASCRIPT">
            <!-- 
               /* 
                 SCRIPT GOES HERE
				  line_of_script;
               */
            //-->
          </SCRIPT>
      </BODY>
   </HTML>

We have shown the area where script is placed using single line comment tags  //  and the multiple line comment tag pair   /*  and   */
These tags allow You to add useful comments to Your scripts. Their contents are not interpreted by the browser as script or output to the page,
they are only visible in Your source code. The 'commented out' script won't be run by the browser. Don't nest /*   */ sets inside each other, use one set for the entire section to be 'commented out'. You may have noticed the final single line JavaScript comment tags just inside the closing HTML comment tags - it is there to accommodate an old browser.

Debugging

From time to time we humans make mistakes, yes, even programmers.

An error in a script can be very difficult to recognize - especially if You just wrote the script.
Debugger programs help You locate and identify errors.
They allow You to 'step through' scripts or add 'break points' to stop execution and examine and change variables.
(We'll be discussing variables in the next section.)

If You are running Netscape You can type 'javascript:' into the location text box.
The whole expression   javascript:  with a colon. 
Then press the 'Enter' key on Your keyboard.

If You are using Microsoft Internet Explorer, You can download a script debugger .
{
http://msdn.microsoft.com/downloads/default.asp?url=/downloads/sample.asp?url=/msdn-files/027/001/731/msdncompositedoc.xml }
Or search for "Microsoft Script Debugger" in Your favorite search engine... links change...
Documentation on it's use is available from it's download page.

By temporarily turning off lines or sections of code by 'commenting them out', it is often possible to locate errors quickly.  We discussed comments in the previous section.

To help avoid error soup, test after every significant change and save Your work frequently.
A good saving scheme is to start with a file that has a basic page name and create a duplicate, sequentially numbered, new, 'work bench' version.  After each improved 'work bench' version is tested, save it as -overwrite- the basic page file, to maintain the links on Your site.  The new basic page is then duplicated as the next new, sequentially numbered, 'work bench' version.  The process is repeated until You reach perfection - or at least create something You can live with.

The Ultimate 'Bug' - they just turn off JavaScript in their Browser

To communicate with folks who have JavaScript turned off, use <NOSCRIPT></NOSCRIPT> tags within the <BODY> tags of Your HTML document. The contents within <NOSCRIPT> tags won't be shown by JavaScript enabled browsers.

   <HTML>
	<HEAD>
         ...
	</HEAD>
	<BODY>
		<NOSCRIPT>
			You must enable JavaScript to view this page.
		</NOSCRIPT>
		<SCRIPT LANGUAGE=JAVASCRIPT TYPE="TEXT/JAVASCRIPT">
		   <!-- 
			document.write("Welcome to the ScriptSchool JavaScript Class!");
		   //-->
		</SCRIPT>     
	</BODY>
   </HTML>

JavaScript disabled browsers will output ONLY:

     You must enable JavaScript to view this page.
JavaScript enabled browsers will write to the document window ONLY:
     Welcome to the ScriptSchool JavaScript Class!

Our script is using the write 'method' of the document 'object', which is the current HTML document in the window.
'Objects' are entities that exist in HTML and scripts, like buttons, images and the document itself.
A 'method' is just an action, a function, which is associated with an 'object'.
Like a noun and a verb: "water.fall( )" "moon.shine( )"

We call a method of an object with 'dot' syntax:

	object.method();
   -or-
	document.write("");
Methods have parentheses( ).  The parentheses ( ) can be used to send in 'parameters' to the method, also known as 'arguments'. How and when arguments are used depends upon the method. In the write method, we use quotes to send in a 'string' of characters. Please notice that the output itself does not have these quotes. We tell the JavaScript interpreter that it has reached the end of a line of script with a semi-colon ';'

'dot' syntax also allows us to 'drill down' through objects that contain other objects to get to a method:

	parentObject.childObject.method(); 
Example: earth.moon.shine();  -or- perhaps the address starts higher:  sun.earth.moon.shine(); or sun.earth.water.fall();
We'll see more of this when we discuss multiple windows and framesets in Week 3.

Another Debugging Method

Many programmers like to check their scripts using feedback they create themselves.
This is often done with the JavaScript alert method.
This method shows a message in a special 'modal' window, which stays open until You click 'OK'.

	<SCRIPT LANGUAGE=JAVASCRIPT TYPE="TEXT/JAVASCRIPT">
		<!-- 
		var username = "John Doe"; 
		alert("The variable 'username' contains: " + username);
		//-->
	</SCRIPT>

Running this script creates:

The variable 'username' contains: John Doe                     

But - Whoa! What the heck is:
	var username = "John Doe"; 

And that sure is a different way of passing an argument in the alert method...
And, hey, What's a 'variable'?

Variables

You can think of a variable as a container that holds information or values.  The variable is given a name so that we can get a handle on the contents.  In variable names, upper and lower case letters are not the same.  MyVariable and myvariable would be names of two different variables.  The generally accepted practice is to use all lower case letters for variable names.  In variables that will hold 'constants' or non-changing values, all upper case letters are used.  The first character of a Variable name can be a letter or an underscore.  Variable names may not start with a number, or contain spaces or punctuation marks.  Numbers may be used in variable names after the first character, and often are used at the end of a name for a related series of values.  Reserved programming language keywords can not be used as variable names.  A list of forbidden keywords is provided HERE.  We will discuss creating, opening, closing and customizing pop-under and pop-up windows like this Keyword List in Week #3.

Variables can hold different types of information - character 'strings', decimal numbers, integer numbers, boolian (true or false) or just 'null' (empty).  Variables can also hold Functions and Objects which we will discuss next week.   JavaScript is 'loose' about variable 'type'. You don't have to indicate the type of value a variable will contain.  And, unlike some other computer languages, the type of value that a variable contains can be changed.  A common example of this is a variable that initially contains a 'string' of characters that we wish to manipulate as a number - and continue to call by the same variable name.

Creating Variables

Variables must be named, or declared, before they can be used. We will get an error if we try to return a value from a variable that doesn't exist yet.  Although it is not required, it is good practice to declare individual variables using the key word 'var'.

	var username;  // the name of this user

We have added a comment to clarify the use of our variable. 'var' can also be used to declare several variables at the same time.   Follow each name with a comma and end the statement with a semicolon:

	var fname,   //  first name
	lname,       //  last name
	email,       //  email address
	phone;       //  phone number

Setting Values

These declared variables have not been given any values yet. If we view their values we will get the string 'undefined'. We have merely named them and written some comments about them to clarify their purpose. They are ready to be used in our script.  This is useful in situations where a value is to be stored in a variable further along in a script.

To put a value into a variable we use the assignment operator, the = symbol.  As we saw in the last section:

	var username = "John Doe"; 

The = symbol can be read as: gets the value of.  In this case, a variable named 'username' gets the value of the string of characters: "John Doe".  Strings are indicated by single or double quotes.

It is also possible to declare and insert values into several variables in one statement:

	var fname = "John",            //  first name
	lname = "Doe",                 //  last name
	email = "johndoe@domain.com",  //  email address
	phone = "(123)456-7890",       //  phone number [as a string]
	age = 26,                      //  age [as an integer number]
	bodytemp = 98.6,               //  temperature [as a float, a decimal number]
	member = true,                 //  membership status [boolian, true or false]
	backdues = null;               //  back dues owed [currently null]

Number values are not enclosed in quotes when placing them in variables.  The values true, false and null are special keywords that are used without quotes.  If they are used within quotes they become regular strings and won't have their special qualities in the script.

Getting and Manipulating Values

To get the value of a variable use it's name without quotes.
We have seen:

	alert("The variable 'username' contains: " + username);

In this case our variable contains string data.
Strings are joined together, or 'concatenated' into single larger strings using the + symbol.
In this statement we are sending the alert method a single string argument.
The single argument is the string data returned from our variable joined to another string.
JavaScript also uses the + symbol for mathematical addition.  The type of operation depends on the type of variable.
Be sure Your numbers are not strings.  Don't quote number values when storing them in variables.

Variable to Variable

A variables value can also be set from the value of another variable:

   <SCRIPT LANGUAGE=JAVASCRIPT TYPE="TEXT/JAVASCRIPT">
      <!-- 
	var currentvalue = "90%";  // current value of percent
	var newvalue     = "95%";  // new value of percent
	document.write("Variable 'currentvalue' before update contains: " + currentvalue + "<br>");
	// 'currentvalue' gets the value of 'newvalue' 
	currentvalue = newvalue;
	document.write("Variable 'currentvalue' after update contains: " + currentvalue);
      //-->
   </SCRIPT>

This script, when placed in an HTML document, produces the following:

Variable 'currentvalue' before update contains: 90%
Variable 'currentvalue' after update contains: 95%

    As You can see:
  1. First we set 'currentvalue' to 90%,
  2. then we set 'newvalue' to 95%,
  3. then we output the original value of 'currentvalue',
  4. then we placed the value of  'newvalue' into 'currentvalue',
  5. then we output the new value of 'currentvalue'.

HTML in Strings

You may have noticed that we included some HTML in our argument to the first write( ) method. We used another + symbol after outputting the value of 'currentvalue' and then used double quotes to write a string containing the <br> HTML tag.  HTML tags inside strings are interpreted as HTML by the browser.  This happens because the write( ) method actually writes the HTML which is sent to the browser. By including the <br> tag (line break), we send the next output to a new line.

Nesting Quotes

We have used single quotes to designate our variable names inside strings we created with double quotes.  This is OK when single quotes are nested inside double quotes or vice versa.  When You want to output a quote character inside a string of the same type of quotation mark that was used to create the string, You have to 'escape' the otherwise active quote character, or the browser will think You are at the end of Your string. You use the \ character to indicate that the next character is to be escaped, or printed literally.  It is also possible to create strings using the single quote, and there are times when this is preferable as we will see in the weeks ahead. Let's escape single and double quotes inside strings created with their quote type:

      document.write('The O\'Reilly publishing house has books on programming.<br>');
      document.write("The paper is 7\" (inches) wide.");

When these statements are placed in a script they produce the following output:

The O'Reilly publishing house has books on programming.
The paper is 7" (inches) wide.

We don't have to escape the parenthesis characters ( ) because they are just ordinary characters in the string.

      // The following would be an ERROR:
	  alert('The O'Reilly publishing house has books on programming.');  

The string would stop after: 'The O' 
The rest will have no logical meaning to the JavaScript interpreter so it will kick out an ERROR and stop running Your script.

Escaping Plain Text

The alert method uses plain text, not HTML. 
Several escaped characters are used to format plain text:
\n for newline, \t for tab, \r carriage return within the same line, \\ shows a single backslash character, and as we have seen, \' and \" escape and show their respective characters.

      alert("To Join, \nClick: \n\n\"New Membership\" \n\n\tThank You");
Alert Box - result of last code snippet.                     

Final Notes on Strings

At times You may need to convert strings to Integers and Floating decimal numbers - See parseInt() and parseFloat()

All the characters of a string must be on the same line of a file.  Don't format Your script files with carriage returns between the two quotes used to create a string.  Most development environments, even Notepad, will automatically 'wrap' long lines, so that You won't have to use a horizontal scroll bar to work on a line which contains a long string...

By now You may be thinking: "I want to learn about creating friendly user interfaces for my surfers... I want to know how they can interact with my pages...  can we push it, please?" 

Events

Events are User actions.  Event Handlers are built in methods that allow Your scripts to respond to User actions like pushing their mouse over a link or rollover button and clicking.  Activated areas trigger Event Handlers. We will examine a few of the most common Event Handlers that work in all recent versions of the major browsers.  Many additional Event Handlers are only available within specific browsers - perhaps useful within uniform intranets - however, they are not recommended for general use on the internet.  Different browsers also have unique 'event capture' syntax to 'get' and 'set' various properties that are available during events - for example, to determine the actual key that was pressed during a onKeyDown event.  We will not discuss 'event capture' during this introductory class, You may want to take a look at the developer sites of the various browser corporations.

A Chart of Common Event Handlers can be found HERE

Event Handlers can be used inside HTML tags and within scripts. Event Handlers inside scripts are methods of objects.
We will see Event Handlers used in scripts in the weeks to come. 

Here we see a typical link to a page on Your server:

	<A href="page2.html">Page 2</A>

We can add an 'onClick' event handler to an HTML link tag:

	<A href="page2.html" onClick = "alert('Link to Page 2 Clicked');">Page 2</A>

  Note: The Event Handler is being placed inside a HTML tag - it is not inside script tags.
When we click the link, we get the following alert box:

alert - Link to Page 2 Clicked                     

After clicking 'OK' we are sent to Page 2.

Event Handler syntax

When placed inside HTML tags, Event Handler syntax is: eventHandler = " script statement here;[additional statement;[additional statement;]]"
where the [ ] indicates optional additional statements, each separated by semi-colons, just as we would write lines of code within script tags. You'll see a script using the optional extra statements in the example for the Advanced assignment.

Blind Links

We can also write 'blind links' into the href with the syntax:

href = " javascript:script expression here"

      <A href="javascript:alert('Blind Link Clicked');">Blind Link</A>
or
      <A href="javascript:void('')" onClick="alert('Blind Link Clicked');">Blind Link</A>

Either will produce:

alert - Blind Link Clicked                     

In the first version we used the javascript: syntax to place our alert('') expression directly into href.  We use the link's internal click response.
In the second version we placed void('') into the href and then used an onClick Event Handler to trigger alert('').

void( ) is a special operator that executes (runs) an expression without returning a value - in this case, to a parent expression. We have executed: '' - a blank string - which does nothing. The expression '' runs, but since void( ) does not return values, href does not replace the current page.  An expression can be sent to void( ) and run - to create an action in a script - without returning a value.   void( ) runs expressions without returning values.

There is a difference in what these two versions show in the status bar of the browser when You 'mouse over' them... they have been written as active links on this page so You can try them Yourself to see what happens...
the first shows:     javascript:alert('Blind Link Clicked')
the second shows:     javascript:void('')
We will discuss sending our own customized special messages to the status bar, in the next section.

Now that we know how to create 'blind links' let's see how we can use some other Event Handlers.

Using onMouseOver and onMouseOut

The following link responds to a MouseOver event:   (live link - try it)

<A href="javascript:void('')" onMouseOver="alert('MouseOver');">MouseOver</A>

alert - MouseOver             

The next example responds to a MouseOut Event:   (live link)

<a href="javascript:void('')" onMouseOut="alert('MouseOut');">MouseOut</A>

alert - mouseout             

Write to Status Bar

The status bar has been mentioned. It is a property of the window object.
You address it with the 'dot' operator.
You 'set' the property with an expression written with the following syntax:
    window.status = 'message';

Lets combine onMouseOver and onMouseOut with messages written to the status bar:   (live link)

<a href="javascript:void('')"
onMouseOver="window.status='Status Message'; return true;"
onMouseOut="window.status=''; return true;">Status Message</a>

We are sending an empty string '' to the onMouseOut handler to clear the status bar when the mouse is moved away.
We add the line: return true; so that the window object shows the changed property setting after each event.
Each line of code sent to the Event Handler is terminated by a semicolon.
Although not required, each Event Handler expression is separated by a space or new line to facilitate reading Your code.
Recall that You should not split JavaScript strings to separate lines in Your .html file.
HTML ignores spaces and line breaks.  The code has been split safely within the HTML areas.

Image Links

Now let's use a picture button link with onMouseOver, onMouseOut, onClick to control the window's status message and throw an alert:

<A href="javascript:void('')"
onMouseOver="window.status='The Best Vacations Anywhere!!!'; return true;"
onMouseOut="window.status=''; return true;"
onClick="window.status=''; alert('The best Vacations Anywhere!!!'); return true;">
<img src="status.gif" alt="The Best Vacations Anywhere!!!" border="0">
</A>
The Best Vacations Anywhere!!! (working example)

Although we could have put the alert and status expressions inside the onClick handler in any order, it clears the status bar of javascript:void('') first this way. Expressions are run in the order they are written. See what happens in the status bar when You click on the previous 'Status Message' rollover link in the last section... and leave the mouse over the link.  Always put the return true; last.
We are using an image instead of a text link. The rest is just building on what we have learned and some HTML formatting. We set the img alt attribute used by some audio text readers, substitutes for images, and in some browsers shows a pop up message when the mouse hovers over the image. Setting the img border attribute to zero removes colored automatic 'link highlighting' around the image.

Image Rollovers

When we use the HTML tag IMG to present images, we are automatically creating an 'instance' of an Image object.

Objects are predesigned structures. You can think of them as templates or prototypes that have methods and attributes or 'properties'. We have already seen methods of other objects. A built-in automatic method of the Image object is showing images. The Image object has properties, which You can set and get. Some of the important properties of Image objects can be viewed HERE

Within IMG tags, the SRC (or source) property is set with the path to an image file.
We have left out properties like width, height and border for clarity:

	<IMG SRC = "image_file_name.type">
  or
	<IMG SRC = "up.gif"> 

Where image_file_name.type is the path and file name of Your image. The type is usually .gif or .jpeg  or .png although other formats are possible.

To manipulate this Image object it must be given a name.
To set this Image object's name we add:

	<IMG SRC = "image_file_name.type" NAME = "image_object_name">
  or
	<IMG SRC = "up.gif" NAME = "active_button"> 
Be sure to put the name in the IMG tag, not the <A HREF> tag.

Preloading Images

To make an effective rollover the replacement image should be pre-loaded. The script for preloading images is placed in the <HEAD> tag. The script creates an 'instance' of an Image object in JavaScript and designates it's source.

In JavaScript the syntax of using an objects' prototype to create an 'instance' of it is:

	var name = new Object; 

You create an instance of an Image object and name or 'declare' a variable to contain it, with the following syntax:

	var image_name = new Image;
  or 
	var over_button = new Image; 

A property of an Image object is the source of the image it contains. 
We set this property with the syntax:

	image_name.src = "image_file.type";
  or
	over_button.src = "over.gif";

Resetting Properties - Changing the Source to Create a Rollover

Just as we can set the value of one variable from the value of another variable... (See: Variable to Variable above)
We can refer to an Image object and set it's SRC attribute to that of another Image objects SRC with the syntax:

	document.image_name.src = other_image_name.src;
  or
	document.active_button.src = over_button.src; 

We put this in the <BODY> of our HTML document, inside an <A HREF> link.
Our image preloading script goes in the <HEAD>

The following document example creates a button that will operate like the one below:

<HTML>
<HEAD>
<TITLE>Image Rollovers</TITLE>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="JavaScript" type="text/JavaScript">
<!--    
	var over_button = new Image; // mouseover image	   
	over_button.src = "over.gif";   
	var up_button = new Image;  // mouseoff image  
	up_button.src = "up.gif";
	var down_button = new Image;  // mousedown image  
	down_button.src = "down.gif";
// -->
</script>
</HEAD>

<BODY>
<A HREF="javascript:void('')"
 onMouseOver="document.active_button.src = over_button.src;"
 onMouseOut="document.active_button.src = up_button.src;" 
 onMouseDown="document.active_button.src = down_button.src;"
 onMouseUp="document.active_button.src = up_button.src;"
  onFocus="this.blur();">
 <IMG SRC = "up.gif" name="active_button"
  width="150" height="75" border="0">
</A> 
</BODY>
</HTML>

Notice the onFocus Event Handler in the <A HREF> tag:

	onFocus = "this.blur();"

It removes any indicators like highlights or dotted lines around areas that have received focus.

Many people think these are less than esthetic, although occasionally they can serve useful purposes.

The 'this' refers to the current object in which the 'this' key phrase appears.
blur() is a method that removes focus from the link element (object). 

Project Assignments for Week #1

This week's basic assignment is writing a blind text link with a custom status bar message on mouse over. Make it to a complex URL with lots of extra 'junk' like click through credit id's tacked on.

For example: http://www.mysponsor.com/members?id=0357zQio1sb2j98
shows: www.mysponsor.com or "Click NOW for the Best Site in the Universe" in the status bar, when the mouse rolls over the link.  Hint: see Write to Status Bar. Recall that href can take URL's as well as "javascript:"

The advanced assignment is to create an image rollover link with a customized status bar message on mouse over. Hint: see Event Handler syntax for HTML tags.

Need help with your assignment or have questions about the first week's course?

Want a little more help? Here are some examples of completed assignments... but don't just copy them, write Your own!

About The Instructors

TDavid is co-owner, programmer and webmaster for several sites devoted to programming including his own http://www.tdscripts.com/ He has done custom programming in various programming languages for companies all over the world. Every Friday at 2pm PST you can catch his weekly radio show dedicated to the technical side of webmastering and programming at http://www.scriptschool.com/radio/

LogSpirit is a student of Script School, the co-author of this course and available for hire for custom programming.

Printable Version of this page HERE

School Map:  Home / Enroll $ Student Records; Class  
$ News @ LIVE Tech Radio * Support/FAQ | Store

advertising | link to us | privacy 
© Copyright 2000-2002 Script School Productions / KMR Enterprises
No part of this website may be reproduced, copied and/or distributed in any medium
without express written permission