Understanding JavaScript

Now that you have a good idea about some specifics of JavaScript, and how useful it is, its time you learned a bit about how it works.

The Object Model

JavaScript assumes that there are “objects” on your page. Each part of your web page is an object that JavaScript can use. An image is an object, a link is an object, and the web page itself is an object. So is the window that the web page is in. Some objects have to be named: images and links, for example, if you want to access them from another object on the page, will have to have a “name” set with “name="something"”.

The web page is called “document”. You can always access the current web page by calling for the “document”. The window is called “window”; you can access that by calling for “window”. Objects can contain other objects. The “window” object contains an object called “history” that has information about the web pages you’ve been to recently. If you want to access the “history” object, you use “window.history”.

Objects have properties and functions built in to them. Usually, you will recognize the properties as corresponding to the things that are inside the object’s tag. An <img> object, for example, has a “src” property. An <a> tag has a “href” property. You use these properties with object.property. So if you are working inside of a link (as we do above), and you want the “href” property, you would use “this.href”. “This” is always the “current” object. The one we are inside.

Objects also have properties that you don’t normally set. The web page, for example, has a “last modified” property, that tells the web browser when the page was last changed. The web browser uses this information to know whether or not to reload the page or use the “cached” version of the page. Because you call the web page “document”, you can access the time the page was last changed as “document.lastmodified”. We’ll be using this in the next section to create an automatic “time stamp” for our web pages.

We haven’t used any object functions yet. We’ve only created our own, standalone functions. When we do use object functions, they look a lot like a cross between functions and object properties. The “window” object, for example, has an object built into it called “history”, which contains the list of pages that the browser has been to recently. If you want to tell the browser to go back to the previous web page, you would use the “back()” function on the “history” object of the “window” object: “window.history.back()”.

You can give object functions “arguments” just like we’ve already done with our custom functions. For example, the “window” object has a function called “alert”. The “alert” function pops up a dialog box with a message on it. We need to tell “alert” what that message is: “window.alert("If you leave this page, I will no longer like you.")”.

The Event Model

“Events” are “things that happen on a web page”. If you click the mouse on a link, an “onClick” event takes you to the new page. If you move the mouse over a link, an “onMouseOver” event displays the URL in the status bar, and then when you move the mouse away, an “onMouseOut” event clears the status bar. Events get “sent” to objects, and then the object decides what to do with that event.

What we’ve been doing is intercepting events. The web browser already had something in mind for all the events we’ve intercepted. On “mouseover” a link, it shows the URL; on “click”ing a link, it moves to that link. We’ve intercepted those events (“onMouseOver”, “onClick”) so that the web browser does something different.

JavaScript normally works almost exactly opposite HTML. HTML does something and that’s it. It displays a page and it is done. The only thing the reader can do is read this static page, or click a link and go to another page. With JavaScript, you can react to what the user does: as long as you can find an event that corresponds to what the use has done and an object to intercept that event.

Scripting

JavaScript is a programming language. It is generally much less forgiving than HTML. Commands end with semi-colons. Carriage returns are important. Curly brackets enclose blocks of JavaScript code. You can’t play around with those rules and expect to get a working JavaScript web page.

You will also notice that I “indent” parts of JavaScript code. Usually, anything inside of curly brackets gets indented by one tab more than the line just above it:

function bless_me(saintname) {
if (saintname == "Helena") {
window.alert("You are blessed by the shroud. ");
} else {
window.alert(saintname + " blesses you. ");
}
}

This indentation is not necessary. If you leave it out, your programs will work just fine. However, indenting like this makes it much, much easier to see what your program is doing. You will always want to indent in a standard format (which usually means using tabs).

Loops

One of the advantages of using a programming language is its ability to automate tasks that would otherwise require repetitious typing. For example, suppose we have several different sets of images to display, and we often add or subtract an image from the list. Rather than adding a new line to our list each time, as we did above, we could keep a list of just the images, and create a JavaScript function to turn our simple list of images into an HTML list.

Remove the list from your HTML code: everything from the opening “<ul>” to the ending “</ul>”. Replace it with:

<script language="JavaScript">
imageList = {
"Christmas_Thumb": "Christmas",
"Lego_Thumb": "Legos",
"Gender_Thumb": "Lenses of Gender"
};
listImages('http://www.hoboes.com/jerry/Gallery', 'gallery', imageList);
</script>

Even though this is a programming language rather than HTML, it already looks easier to create and easier to understand than the previous, HTML list with embedded JavaScript events. If we choose to add a fourth image to this list, we need only add a line with the image’s filename and the image’s title text. Note that each line except for the final line ends with a comma. This is an “associative array”, which means that this is a list where the first item in each pair is “associated with” the second item in the pair. Lego_Thumb is associated with Legos, for example.

This is only half of the solution, however. The last line inside the script tag calls a function named “listImages()” that takes three options: the base of each image’s URL (most likely the folder the images are stored in if you were to use this on your own site), the name of the image display img tag, and the list of images we want the reader to choose from.

//imgFolder is the base of the URL for the images

//imgName is the name of the img tag that will display the images

//imgList is the list of image files we want to display, in the form "image name":"image filename"

function listImages(imgFolder, imgName, imgList) {
document.write("<ul>");
for (currentImage in imgList) {
aText = imgList[currentImage];
aHREF = imgFolder + "/" + currentImage + ".jpg";
onClick = "onClick=\"return change_img('gallery', this.href);\"";

aTag = '<a href="' + aHREF + '" ' + onClick + '>' + aText + '</a>';
listItem = "<li>" + aTag + "</li>";

document.write(listItem);
}
document.write("</ul>");
}

See the example at http://www.hoboes.com/NetLife/Web_Scripting/lessons/lesson4a.html. You’ll see a lot of “document.write()” in these examples. That’s something that documents--that is, web pages--can do in JavaScript: insert text into themselves. Wherever document.write() is called, some HTML is being inserted into the web page. At the beginning of this function we write an opening list tag and at the end we write the closing list tag.

for (currentImage in imgList) {

}

The meat of this function is inside a “for” loop. Loops begin and end with { and }, just as functions do. The stuff inside the loop gets done over and over again. We’ll see different kinds of loops later, but the “for” loop goes through its contents once for every item in the list. The list is the container after the keyword “in”. In this case, it is our list of images and image titles. The word listed before the “in” keyword is a container that contains each item of the list as we go through it. In this case, the first time we go through the loop, “currentImage” contains one item; the next time, it contains another item; and so on, until we have looped once for every item the imgList list contains.

aText = imgList[currentImage];

Recall that when we created the image list, we did so using pairs: the image’s file name (without the “.jpg”) and the text that we want to appear on the link that displays the image. The currentImage container contains only the first item in that pair. To get the second item, we need to ask the list for it. When we use “listname[keyword]” we are asking the list for the item that is paired with that keyword. The keyword is always the first item in the pair of items. The result is always the second item which is associated with that keyword.

aHREF = imgFolder + "/" + currentImage + ".jpg";
onClick = "onClick=\"return change_img('gallery', this.href);\"";

aTag = '<a href="' + aHREF + '" ' + onClick + '>' + aText + '</a>';
listItem = "<li>" + aTag + "</li>";

These four lines construct the list item, what in our original HTML was “<li>...</li>”. The first two lines construct the parts of the link (the “a” tag). The third line constructs the “a” tag from those parts. The fourth line constructs the full “li” tag.

Each line does this by adding together the pieces. The third and fourth lines use the parts that were constructed in the preceding lines.

document.write(listItem);

Finally, we use another “document.write()” to write out the list item. Thus, for each image in the list we will write one “<li>...</li>” tag.

By construction our list using a function, we not only make it easier to add and remove images from the list, we can also more easily change our mind later. For example, we might choose to display them as a table, with thumbnails. Rather than modifying each page that displays a set of images, we need modify only the function that each page calls.

Note also, of course, that by doing it this way anyone who does not have JavaScript will not be able to see that list of images displayed on their browser.