JavaScript: Overview

JavaScript introduces a whole range of new functions and controls into designing for the web, including new vocabularies but also new ways of thinking about designing for the screen. JavaScript extends HTML into areas that could be termed "interactive", as they respond to the user's actions or inputs more than HTML can, or to other external conditions like the day, the platform, or the history of pages the user has visited. JavaScript is also a little closer than HTML to other scripting languages (Flash 5's ActionScript is based on JavaScript, and there are similarities to Director's Lingo) in its syntax and structure. Some of these terms will be familiar, while others will very soon become familiar.

A great resource page, by the authors of the JavaScript: Visual Quickstart book, is available at http://www.chalcedony.com/javascript; check out the script examples section.

object: property: value

This is a scheme we've seen before, even in HTML: if you think of <FONT> as an object, you can see that a font can have many properties: its face, its size, its colour, its weight, and so on. Each of these properties has a value, what it is currently set to. All font families share the same properties, but have different values, so that "font-family:Arial" and "font-family:Times" have two different values, "Arial" and "Times", for the property font-family.

Sometimes values become objects themselves. For example, document.images is an object, the document, which is the current HTML file, and its property, images, which is a list of all the images used within that document. document.images[1] is an item in that list, or a single image; that image is itself an object, though, with properties such as height, width, src, border, name, and so on. document itself is a property of window, so there's quite a bit of nesting involved.

If you're trying to figure out how to put different parts of JavaScript together, try to think about the relationship between an object and its properties, and it will help to determine where things go.

object: event

Objects also have events, of which there were few in HTML. An event is something that happens, either on the part of the user or something within the running of the browser program. onMouseover, for example, is an event that happens when the user rolls the cursor over the object (usually an image or an HREF link). What happens when that event occurs, though, is up to you. In JavaScript, there is a relationship between objects and events: not all events can be attached to all objects. onLoad, for example, is an event attached to the document object, and can't be arbitrarily attached to an image object, or a link.

object: method

Some objects also have methods, which are actions. One of the most common is .write(), which the documentobject can use to display something on screen.

arrays

Arrays are lists of items. document.images, for example, is a list of all the images used in a document, so document.images[0].src would give me the src location of the first image in the document (arrays are zero-counted, so the first item in the list is referred to as item zero), or, and this is the good part, if I set document.images[0].src to equal something, as in document.images[0].src = "rollover.gif", the document will update this information, and the image will change on screen.

if...then statements

If...then statements are the core of many programming languages; they allow you to test for a variety of conditions and then take certain actions based on the results. The form is like this:

if (a) {
}

if the situation "a" is met, then the actions between the braces {} will happen. If you need something to happen if a turns out not to be the case, then something like

if (a) {  
} else {  
}

will do the trick. This can be expanded quite a bit:

if (a && b) {  
} else {  
}

will test to see if conditions a and b are both true before proceeding.

if (a || b) {  
} else {  
}

will test to see if either a or b is true.

if (a) {  
} else if (b) {  
} else {  
}

will do one thing for a, another for b, and something else if neither condition is met.

Some of the ways you can test or measure conditions:

Here's a concrete example which will detect an operating system and browser:

if (navigator.userAgent.indexOf("Macintosh")){
	platform="Macintosh";
} else if (navigator.userAgent.indexOf("Windows")){
	platform="Windows";
} else {
	platform="something other than a Mac or Windows";
}
if (navigator.userAgent.indexOf("Safari")){
	browser="Safari";
} else if (navigator.userAgent.indexOf("Opera")){
	browser="Opera";
} else if (navigator.userAgent.indexOf("OmniWeb")){
	browser="OmniWeb";
} else if (navigator.userAgent.indexOf("MSIE")){
	browser="Internet Explorer";
} else if (navigator.userAgent.indexOf("Netscape")){
	browser="Netscape";
} else if (navigator.userAgent.indexOf("Gecko")){
	browser="Gecko";
} else {
	browser="something other than Safari, Opera, OmniWeb, MSIE, Netscape, or Mozilla";
}
document.write("You appear to be using "+browser+" on "+platform+".");

What this is doing is searching something called the userAgent to find out what browser the user has; the full userAgent looks like this:

indexOf is a small test to see if the userAgent contains the keyword, so navigator.userAgent.indexOf("Safari") will be true if the userAgent is Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/125.2 (KHTML, like Gecko) Safari/125.7, as it is for Safari 1.2. Note that there's a specific order above, too: because the userAgent for Safari also contains the keywords "Mozilla" and "Gecko", testing for "Gecko" before "Safari" will always return true for Gecko, and never get down to checking for Safari.

variables

Variables are ways of storing bits of information. Variables have two parts: a name, and the data they contain. In this example, a variable called "userName" will store whatever the user chooses to enter, then return that, with some extra text:

userName = prompt("Please enter your name:");  
document.write("Hey, it's great to see you, " + userName + ".");

functions

Functions are customized methods: they perform any action you want them to, when they are called. Functions are sometimes called handlers, because they often handle events.

Functions are always declared as such, as in

function changeImages(imageName,imageState) {  
  document.images[imageName].src = "images/" + imageName + imageState + ".jpg";  
}

The function is declared a function, is given a name, and is given a couple of arguments or parameters to work with. The function won't do anything until it is called by an event, which could be anything, but in this case is probably a mouseover event, as in:

<a href="biography.html" onmouseover="changeImages('biography','-1')" onmouseout="changeImages('biography','-0')">  
<img name = "biography" src="images/biography-0.jpg" border=0></a>

The function is going to look for an image named "biography" in the document.images array, and, on the mouseover, concatenate "biography" and "-1" and ".jpg" to "biography-1.jpg" (notice the use of single and double quotes: it's important to nest them properly, so that anything within onMouseover="..." uses single quotes, so as not to break the command being called; onMouseover="changeImages("biography","-1")" will break, because the double quote in front of biography appears to close the one started in front of changeImages).

Other ways of calling functions

You may want to call functions without moving from your current location - say you want to open a window on top of the current window. Although you need to trigger the window opening via the <A HREF> tag, you don't want to specify a new address. One way to work around this, which may suit your needs, is to put a single hash (#) mark into the <A HREF> tag, and call a function through the onClick() event:

<a href="#" onclick="popWin('map/images/germantown.jpg',300,300)">open window</a>

open window

This methods works most of the time, but some browsers, detecting the hash symbol, will jump back to the top of the document, disrupting the overall effect you want. A better method, one which prevents the main window from moving, is this:

<a href="#" onclick="popWin('map/germantown.jpg',300,300);return false;">open window</a>

open window

loops

Loops are great for reducing repetitive tasks to one or two lines. Imagine that we wanted to have twenty instances of an image in a row. In HTML, the code might look like this:

<img border=0 src="dot.gif">  
<img border=0 src="dot.gif">  
<img border=0 src="dot.gif">  
<img border=0 src="dot.gif">  
<img border=0 src="dot.gif">  
<img border=0 src="dot.gif">  
<img border=0 src="dot.gif">  
<img border=0 src="dot.gif">  
<img border=0 src="dot.gif">  
<img border=0 src="dot.gif">  
<img border=0 src="dot.gif">  
<img border=0 src="dot.gif">  
<img border=0 src="dot.gif">  
<img border=0 src="dot.gif">  
<img border=0 src="dot.gif">  
<img border=0 src="dot.gif">  
<img border=0 src="dot.gif">  
<img border=0 src="dot.gif">  
<img border=0 src="dot.gif">  
<img border=0 src="dot.gif">

But we could instead define a simple loop to do this twenty times, as in:

for (i = 1; i < 21; i++) {  
  document.write("<img border='0' src='dot.gif'>");  
}

for (i = 1; i < 21; i++) sets up a loop, which will run while the conditions within the parentheses are true;
for (i = 1; i < 21; i++) sets a variable, here called "i" (i is frequently used where variables aren't being stored, and so don't need a more descriptive name, and where i is usually an integer), to 1;
for (i = 1; i < 21; i++) we want this to run twenty times, so only if i is less than 21 should the following occur;
for (i = 1; i < 21; i++) is the JavaScript shorthand to iterate an integer up by one, so every time through the loop i gets one larger.

Here's another example which is a little easier to see:

for (i = 1; i < 21; i++) {  
  document.write(i + ", ");  
}

which will give us this:

Other kinds of loops could include things like:

for (image in document.images) {  
  document.write(image.name + ", " + image.src);  
}

which loops through the array document.images with the item image, a variable, and prints both the image name and the image source into the document.

Warning
It is possible to set up loops that will run forever, which will force the user to quit the browser:

while (i < (i + 2)) {  
  document.write(i + ", ");  
}

for example, will run infinitely, as i will always be less than i + 2. And as loops can be nested within each other, it's possible to set up a loop sequence that will run much longer than intended:

for (i = 1; i < 101; i++) {  
  for (k = 1; k < 101; k++) {  
    document.write(i * k);  
  }  
}

This set of loops will run 10,000 times, as it multiplies all integers from 1 to 100 by all integers from 1 to 100.