Search the Catalog
Designing with JavaScript, 2nd Edition

Designing with JavaScript, 2nd Edition

A Definitive Introduction

By Nick Heinle & Bill Pena
2nd Edition November 2001
1-56592-360-X, Order Number: 360X
230 pages, $34.95

Chapter 1
Diving into JavaScript

If you've read other JavaScript books, you may have had to slog through pages and pages about functions, methods, operands, and so on, before ever learning how to write even the simplest script. As you get into JavaScript, you'll need to understand those concepts and more, but you can start spiffing up your web pages just by diving into JavaScript.

That's what this chapter is about. By the time you've finished, you'll know two handy scripts, one to add descriptive comments to the status bar, and the other to use the time to serve custom pages. More importantly, you'll understand why the scripts do what they do, and you'll be ready to wade a little more deeply into JavaScript.

The concepts we'll cover in this chapter include:

Adding descriptive links

Do you ever wish links could talk? In other words, wouldn't it be helpful to be able to tell users what to expect if they click on a link? You can do this easily with JavaScript.

Figure 1-1 shows the O'Reilly & Associates web site. Each of the book covers shown on the page takes the user to the book's catalog page, where there is more detailed information about the book. However, a book cover thumbnail doesn't tell users much about where they'll go if they click on the image. To solve this problem, we can display a short description of the link in the browser's status bar when the user moves the mouse over a cover image. If the descriptions are well written, they'll add useful context to the site. Here, putting the mouse over the Learning Cocoa cover displays the text "Click here to see the catalog page for this book" in the status bar. This is really quite simple to do, as shown in Example 1-1.

Example 1-1: Code for adding status bar text to a link

<a href="http://www.oreilly.com/catalog/learncocoa/" 
   onMouseOver="window.status = 
      'Click here to see the catalog page for this book'; return true;">
<img width="44" height="100" border="0" src="learning_cocoa.gif"></a>

Figure 1-1. Displaying additional information in the status bar

 

The event

The link in Example 1-1 looks like a normal link, but it's obviously a little different. Inside the <a> tag, there is a small piece of JavaScript code. The code starts (and the HTML ends) with onMouseOver; this is one of JavaScript's built-in event handlers. An event handler is code that runs when an event occurs. What's an event? It's something that happens, such as the user placing the mouse over a link or a page loading.

In this case, we're dealing with the onMouseOver event, which occurs when the mouse moves over the link. Since this event handler is located in the link that surrounds the image, the event occurs when the mouse is placed over that image, and not anywhere else on the page.

Event handlers can be used in many elements of the page, including links, form buttons, and images. Table 1-1 lists some common event handlers supported by JavaScript, the tags where they can be used, and the events they handle.

Table 1-1: Common event handlers supported by JavaScript

Event name

Where it goes

When it works

onMouseOver

Links (and images within links)

When the mouse moves over a link

onMouseOut

Links (and images within links)

When the mouse moves out of a link

onClick

Links (and images within links), button elements

When the user clicks on a link or button element

onChange

Select menus, text input elements

When an option is selected or the text is changed

onSubmit

Forms

When the form is submitted

onLoad

Body, frameset, images

When the document or image is done loading

onUnload

Body, frameset

When the document is exited

The code that follows onMouseOver runs when the event occurs (in this case, when the mouse moves over the link). Combining the event handler with some useful code gives you a link that does something when the mouse moves over it. In Example 1-1, the code displays the description of the link in the browser's status bar.

It is important to note that onMouseOver is followed by an equal sign (=). The equal sign says, "When onMouseOver occurs, run the following code." The code that follows must be surrounded by double quotes so the handler knows which code to run (all the code in quotes, and nothing else). In programming terms, the equal sign assigns a value to the event handler. Of course, this shouldn't be a foreign concept, as you use the equal sign to assign values to attributes in HTML all the time (e.g., <a href="page.html">).

Applying onMouseOver to your links

Now that you know how to use onMouseOver, it's time to learn about the code that follows it:

"window.status = 
    'Click here to see the catalog page for this book'; return true;"

The code tells the browser's status bar (window.status, as JavaScript knows it) to display the text "Click here to see the catalog page for this book". That's really all there is to it, but there are several things to notice even in this simple code:

So far so good, but what are the words return true; at the end of this code? For now, it's enough to know that it's some magic required to keep the browser from doing its normal job of displaying the URL in the status bar. If those words weren't there, the user would never see our status bar message, because it would be immediately overwritten by the URL. We'll discuss this return feature in more detail in a number of scripts later in the book.

To apply this technique to your site, just replace the text between the single quotes (and the URL and content, of course).

If you've tried this script, you've probably noticed that the text in the status bar doesn't go away when you move the mouse out of the link. To solve this problem, we need to add a second event handler, for onMouseOut events, to the link, as shown in Example 1-2.

Example 1-2: Improved code for adding status bar text to a link

<a href="http://www.oreilly.com/catalog/learncocoa/"
   onMouseOver="window.status =
      'Click here to see the catalog page for this book';
      return true;"
   onMouseOut="window.status = '';">
<img width="44" height="100" border="0" src="learning_cocoa.gif"></a>

The code for the onMouseOut event handler simply sets window.status to an empty string (''). The onMouseOut event handler is triggered when the mouse moves out of the link, so this effectively erases the text in the status bar.

Night and day

Now it's time to make your first real script; this involves learning some new concepts. If you're not familiar with programming (in C, C++, VB, Pascal, or whatever), this script is for you. While the last example did incorporate JavaScript, it was more of an enhanced <a> tag than an actual script. This example is more involved.

Assuming that people's web-surfing interests vary by time of day, your web site might be well served by promoting different content depending on whether it is day or night. For instance, a ski resort could feature skiing information such as trail conditions or snow depth during the day and lodging specials and entertainment at night. Winter Park Ski Resort's home page reflects that variety by rotating different images depending on the time of day. Figure 1-2 and Figure 1-3 show two possible pages.

Figure 1-2. A "day" page

 

Figure 1-3. A "night" page

 

How is this done with JavaScript? In short, a script checks the time and then delivers either the daytime or nighttime HTML. We'll cover a number of concepts in this little script:

Example 1-3 shows the code for a page that displays content that differs, depending on the time of day. We'll explain the code in greater detail in the sections following the example.

Example 1-3: The night and day script

<html>
<head>
<title>Night and Day Script</title>
</head>
<body>
<script language="JavaScript">
<!--
var now = new Date(  ); 
var hour = now.getHours(  );        
if (hour >= 4 && hour <= 16) {  
    document.bgColor = "#FFFFFF"; 
    document.fgColor = "#000000"; 
    document.write("<img height='150' width='250' src='photo-day.jpg'>");
    document.write("<p>Wouldn't you rather be skiing powder than sitting ");
    document.write("in front of a computer screen?</p>");
}
else { 
    document.bgColor = "#000000"; 
    document.fgColor = "#FFFFFF"; 
    document.write("<img height='150' width='250' src='photo-night.jpg'>");
    document.write("<p>After a full day of skiing, throw back a few cold ");
    document.write("ones before you settle in for the evening.</p>");
}
//-->
</script>
</body>
</html>

The script tag

All scripts start and end with one common element: the script tag. The HTML document in Example 1-3 is basically one big script tag; there's no other content in the body of the document. As you can see, the syntax is:

<script language="JavaScript">

The browser considers everything within the script tag to be pure JavaScript and nothing else. This is where most of your scripts will reside. script tags can be placed anywhere inside an HTML document, in the head or in the body. In this case, the script tag is placed where the script does its work of printing out a page--in the body. In other documents, you'll see functions defined in a script tag in the head of the document and then called from other script tags placed elsewhere on the page.

You may be asking yourself, "Why is there a language attribute in the script tag?" That's because JavaScript is not the only web scripting language. VBScript, a scripting language based on the Visual Basic programming language, can also be used. But VBScript is supported only in Internet Explorer, which limits its practical use.

There are also different versions of JavaScript, each supported by different browsers. JavaScript 1.0 appeared in Netscape Navigator 2.0. Since then, JavaScript has evolved to Version 1.5, currently supported by Netscape 6 and Internet Explorer 5.5. JavaScript has also been standardized under the name ECMAScript (ECMA-262).

So, are these different versions something you need to worry about? Usually, no. Most of the scripts in this book use features supported by all the browsers released in the last four years. When they don't, we'll let you know. If a script uses a feature in the latest version of JavaScript, you need to make only a slight modification to your script tag:

<script language="JavaScript 1.5">

Hiding JavaScript from really old browsers

The only problem with putting a script in a web page is that really old browsers don't understand the script tag and will display the code in the web page as normal text. But there is a simple way to get around this using HTML comments:

<script language="JavaScript">
<!-- hide me from antiquated technology
JavaScript code
// stop hiding me -->
</script>

Older browsers will ignore the <script> tags and everything between the <!-- and the -->. These types of comments can only be used at the beginning and the end of a script, and it is important to put these comments on their own lines. If you put them on the same line as some code, that code will be commented out and your script won't work. For more details on how these comments work, see the "A few comments" sidebar, later in this chapter.

We've used the script hiding technique in Example 1-2, so that you can be familiar with what it looks like. But we won't be using it in any of the other examples throughout the book, since virtually all browsers understand the script tag nowadays.

The Date object and variables

The first part of the night and day script detects the time of day, using the system clock on the user's computer. It does this with the Date object, which is built right into JavaScript:

var now = new Date(  ); 
var hour = now.getHours(  );

The first line simply creates a new Date object and gives it the name now. In programming parlance, now is called a variable, which is just a fancy way of saying that it's a name associated with a piece of information. Thus, from this point on, the current date and time can be referred to as now. Next the script says, "Take now (the current date and time), ask it for the current hour (getHours( )), and call the answer hour." As you'll understand shortly, getHours() is a method of the Date object. Now we can also refer to the current hour by name, using the variable hour.

As you can see in the night and day script, we create a variable with var followed by the name of the variable. Once we've created a variable, we can assign a value to it with the equal sign followed by the initial value for the variable, as we've done here with now and hour.

A few comments

Code comments allow you to place descriptions of your code within the code itself. Comments are useful both as a reminder to yourself about what the code does and as an aid to other scripters who may be looking at your code. In large scripts or scripts that are used and modified by lots of other people, comments are essential. Code comments are also useful for temporarily taking a line or two of code "out of commission" when you are testing a script. We will use comments throughout this book to describe and discuss code.

There are two types of JavaScript comments: one-liners and block comments. One-liners comment out a single line:

// This is a one-line comment

The two forward slashes (//) are what indicate the comment here. Everything after the // is ignored. One-liners can also be used on the same line as some actual code:

var now = new Date() // Create a Date object

Block comments can span multiple lines, so they have both an opening indicator, /*, and a closing indicator, */. For example:

/* This comment
spans a number
of lines */

Everything between the /* and the */ is ignored.

Outside of the script tag, we can also use HTML comments:

<!-- This is an HTML comment -->

Now you can see that our technique for hiding JavaScript from really old browsers takes advantage of both HTML and JavaScript comments. The comment that starts the hiding process is a plain HTML comment. The ending comment, however, combines a JavaScript comment with an HTML comment, //-->. As the closing HTML comment (-->) is not valid JavaScript code in itself, we need to add an additional JavaScript comment (//) in front of it to prevent any potential JavaScript error from being generated.

Displaying the page

Now that we have the current hour, we need to do something with it. This script's whole purpose is to use that information to display (or "print," in programmer-speak) the appropriate content.

This brings us to one of the most useful applications of JavaScript: the ability to "print" HTML directly onto a web page. This is done with a method called document.write( ):

document.write("<img height='150' width='250' src='photo-day.jpg'>");

Everything between the double quotes in the call to document.write( ) is printed onto the page. This example prints the HTML to display the image, but you can print any text or HTML this way, including tables, forms, or whatever.

As you'll see as we progress through this book, much of what you do in JavaScript involves functions and methods. In JavaScript, a function is simply a name for a set of instructions to the web browser. Methods are similar, but there's a subtle difference; see the sidebar "Objects, properties, and methods" later in this chapter for the details. Some methods, like document.write( ), are built into JavaScript; we'll be using lots of built-in methods in this book. JavaScript also allows you to define your own functions, as we'll discuss in Chapter 2.

Putting it all together

You now have two pieces of knowledge: how to get the current time in hours and how to print out the page. But how do you combine the two so you can print appropriate content based on the hour? You use something called an if statement. if statements use a very simple concept: "If this condition is true, then do that." In JavaScript, the simplest form of an if statement looks like this:

if ( this is true ) { 
    run this code 
}

It looks like fractured English, and there's a reasonafter all, JavaScript is a language. Every if statement consists of the word if followed by a statement in parentheses and then a block of code in braces. The parentheses contain the condition that is being checked. The braces contain the code that is run if the condition is met. Consider the following code:

if (hour > 22) {
    document.write("My, it's getting late!");
}

If the variable hour is greater than 22, meaning it is later than 10 P.M. (hours are specified with a 24-hour clock), the code prints a message about how late it is.

An if statement can also have an else portion that contains code that is run if the condition isn't met:

if ( this is the case ) { 
    then run this code 
}
else {
    otherwise run this code
}

This is the format we're using in the night and day script, where we're checking the hour and displaying the time-appropriate graphic and promotional text. If the hour is between 4 A.M. and 4 P.M., we'll serve the daytime photo; if it's between 4 P.M. and 4 A.M., we'll serve the nighttime photo. Here is a simplified version of the code from Example 1-3:

if (hour >= 4 && hour <= 16) { 
    document.write("<image src='photo-day.jpg'>");
}
else {
    document.write ("<image src='photo-night.jpg'>");
}

The first line says, "If the value of the variable hour is greater than or equal to 4 and less than or equal to 16, run the code in braces." You probably remember the greater-than or equal (>=) and less-than or equal (<=) signs from math class; the double ampersands (&&) mean "and".

What happens if it's 7 P.M? Since we weren't testing for this time, the else statement applies. With else, we're saying, "If the condition isn't true, then do this instead." If it's 7 P.M., it's not between 4 A.M. and 4 P.M., so the script runs the code following the word else. In this case, the code prints out the nighttime image and text.

Document properties

Now that we've conquered the logic of if and else, let's look at the actual code for these pages. Notice that not only the graphics and text are different, but the background color and the text color as well.

If the hour is between 4 and 16, the script changes the background color to white and the text color to black, displays the graphic photo-day.jpg, and writes the text about skiing powder. If the hour is not between 4 and 16, the else statement tells the script to change the background color to black and the text color to white, display the graphic photo-night.jpg, and write the text about having a drink.

Changing the colors involves setting two properties of the current web page, or, as JavaScript knows it, the document object. The properties of the document object describe different characteristics of the object. Assigning a hexadecimal value to the document.bgColor property changes the background color; document.fgColor changes the text color. You can change the background color on the fly, at any time during the document's existence, but in some browsers, the property for the text color can only be changed when the document is initially displayed, so it is best not to change this after the document has been displayed. We'll learn how to change the color and appearance of text on the fly in Chapter 9.

The JavaScript tree

The document object and its bgColor property are separated by a period. Thus, document.bgColor refers to the background color property of the document. That seems simple enough, but what do you make of this?

document.mailform.address.value

It refers to the value of the address element of a form called mailform, which is in the document. Clear as mud? It makes a little more sense if you think of it as a tree.

In general, JavaScript organizes all parts of the browser window and all elements on a page (e.g., forms and images) like a tree. First, there's a main object (the trunk), then there are objects off the main object (branches), and finally there are methods and properties off those objects (leaves). As you'll see in later chapters, this is referred to technically as the document object model, but the tree metaphor is an easier way to think about it for now.

The main object, the trunk, is always the current browser window, referred to as window. There are many branches off the browser window: the page currently displayed in the window, called document, the current location of the window, called location, the history of all the visited pages of the window, called history, and the value of the status bar, status. Inside each of these branches, you'll find more

objects. For example, the document object contains all the elements on a given page: forms, images, and links are all reflected as objects. To illustrate this concept, the figure shows a small "slice" of the JavaScript tree.

As you can see, the tree begins with the browser window and branches off from there. (This is by no means the complete JavaScript tree, which would take up about 20 pages.) Whenever you want to access something in the JavaScript tree, you have to "climb" up to it. To better understand this, let's create our own example of "climbing the tree" using a simple HTML document:

<html>
<body>
<form name="mailform">
<input type="text" name="address">
</form>
</body>
</html>

The names of the form and the text input field specified in their HTML tags correspond to the names used by JavaScript. Here we have a form named mailform that contains a text input field named address. To get the text entered by the user, you need to ask for the value of address. That's the value of address in form mailform in the document in the window:

window.document.mailform.address.value

Because it is very common to access elements in the current page, JavaScript lets you take a shortcut and start climbing the tree at document. Thus, you can also access the text of the address field as:

document.mailform.address.value

What else can you do with the date?

In the night and day script, we worked with the time in hours. Of course, JavaScript lets you access all parts of the date and time, but the syntax isn't exactly plain English. Table 1-2 shows how to get the various parts of the date and the form in which they're returned.

Table 1-2: Getting the time from JavaScript

Unit of time

How to get it

How to use it

Second

second = now.getSeconds( );

The time in seconds is returned as a number 0 through 59.

Minute

minute = now.getMinutes( );

The time in minutes is returned as a number 0 through 59.

Hour

hour = now.getHours( );

The time in hours is returned as a number 0 (midnight) through 23 (11 P.M.).

Day

day = now.getDay( );

The day of the week is returned as a number 0 (Sunday) through 6 (Saturday).

Month

month = now.getMonth( );

The month of the year is returned as a number 0 (January) through 11 (December).

Year

year = now.getFullYear( );

The year as a full four digit year
(e.g., 1998, 2001).

Keep in mind that when you get times and dates from JavaScript, they are returned as numbers, not words. This means that if you ask a Date object for the day of the week, using getDay( ), you get a number 0 through 6, not the name of a day, like Sunday or Monday. Though numbers are useful for database applications and the like, you may want to put them into a more digestible form. For example, you can create a script that uses getDay( ) in combination with if statements to translate the numeric values to their actual names, as shown in Example 1-4.

Example 1-4: Connecting number values to day names

<script language="JavaScript">
var now = new Date(  );
var day = now.getDay(  );
var dayname;
if (day == 0) { 
    dayname = "Sunday";
}
if (day == 1) {
    dayname = "Monday";
}
if (day == 2) {
    dayname = "Tuesday";
}
if (day == 3) {
    dayname = "Wednesday";
}
if (day == 4) {
    dayname = "Thursday";
}
if (day == 5) {
    dayname = "Friday";
}
if (day == 6) {
    dayname = "Saturday";
}
document.write("Today is " + dayname + ". <br>");
</script>

So how does this work? First, a new Date object named now is created, and the day of the week, which is in number form, is given to a variable named day. Then a series of if statements matches up the number of the day with the day's full name and stores the name in the variable dayname. For example, if day is 0, it must be Sunday; if day is 1, it must be Monday, etc. Finally, the day's full name, in variable dayname, is displayed on the page using document.write( ). Note that this script creates the variable dayname without giving it a value at the same time; the value is assigned later when we actually figure out what day it is.

You can use this technique for various parts of the date to create a script that displays the fully formatted date on the page (e.g., Monday, July 30, 2001). The best way to do this involves arrays, something you'll learn more about later in this book. If you're curious, see "Doing the date right," in Chapter 5.

Objects, properties, and methods

There are millions of "objects" in the real world: trees, telephones, people... almost everything we deal with is an object. You could even say that we live in an object-oriented world. Because of this, some programming languages, such as Java and C++, are object-oriented as well. JavaScript is also an object-oriented language, although it does things a little differently than Java or C++, so some programmers don't consider it a true object-oriented language. Regardless, you should treat JavaScript as an object-oriented language.

In JavaScript, there are a large number of objects, the majority of which will be discussed in this book. For example, the page is an object: document. The (browser) window is an object as well: window. Another one we encountered in this chapter is Date, which refers to the date and time showing on the user's computer.

In JavaScript, we can do things not only to objects but also to their properties. For instance, in our first script, the status bar is a property of the window object, referred to as window.status.

To understand how this works, it's helpful to relate it to real life. Let's be a little abstract and think of your car in terms of JavaScript. First of all, let's create a new Car object, which we'll call myCar:

var myCar = new Car( );

You saw this syntax in the night and day script, when we created a new Date object. Now we can begin to manipulate the myCar object, and in the process learn a few things about object-oriented programming.

The property concept

Your car has many different properties: color, brand, horsepower, and price, to name a few. What if you want to paint your car red? In JavaScript terms, you would change the color property of your car to red, like so:

myCar.color = "red";

Your car object, myCar, is separated from its property, color, by a dot. This is the equivalent of saying, "the color of myCar." After you have referred to your car's color property in this way, you can then do something with that property.

In this example, the color property of myCar is set to "red" using =. This is like finishing the sentence, "I want the color of myCar... to be red."

To apply this to JavaScript, let's introduce another property of the window object: location. Simply put, the

location property controls the location of the window (i.e., the file that is currently being displayed). The following code, for example, takes the (browser) window to a document located at http://www.yahoo.com:

window.location = "http://www.yahoo.com";

Just as color is a property of your car, location is a property of the browser window. To change the location of the window, use the same syntax you used before, separating the window object from its location property with a dot and setting the combination to a value.

Methods to the madness

With properties, we can change certain attributes of our objects, but to do more with JavaScript, we have to use methods. A method, like a function, is simply a name for a set of instructions to the browser. The difference is that a method is directly associated with an object and operates on that object exclusively.

Think about it again in terms of your car: myCar. In addition to having properties, your car has actions that you can do to it, such as accelerate, brake, and honk. These actions, when associated with the car object, are referred to as methods. To accelerate your car object, you might run its accelerate( ) method:

myCar.accelerate( );

This looks like a property, but it has one important difference: those parentheses indicate that this is a method. A more useful accelerate( ) method would allow you to tell the car object by how much you want to accelerate. Perhaps you could pass it the speed in miles per hour:

myCar.accelerate(15);
This would accelerate the car by 15 miles per hour.

In the night and day script, we used the getHours() method of the Date object to get the current hour and the document.write( ) method to display some HTML on the page. You always pass the document.write( ) method a value, as you did with myCar.accelerate( ). The value that you pass to document.write( ), most likely some text or HTML, is displayed on the page:

document.write("My, it's getting late!");

There are a multitude of objects in JavaScript, and therefore a multitude of properties and methods as well. Learning to use JavaScript is largely a matter of learning how to manipulate the properties and methods of built-in objects to achieve the effects you want.

Time shifts

The Date object is not limited to the current time; you can also create a Date object for a specific date in the past or future. For example, to create a new Date object for October 31, 2001, any of the following is acceptable:

var then = new Date("October 31, 2001");
var then = new Date("October 31, 2001 00:00:00");
var then = new Date("Oct 31, 2001");
var then = new Date(2001, 9, 31);

Notice that you are passing a specific date to the new Date object. In JavaScript terminology, the information you pass to an object, whether it is a string of characters, a number, or even another object, is called an argument. When an object (or function) receives an argument, the object uses the data to perform its job. In this case, the Date object uses the argument to create a Date object for the specified date.

This feature of the Date object is commonly used to create countdowns to specific times or dates, such as anniversaries, product launches, etc. So, if you need a script to display the number of days between now and Halloween, create a Date object for the current date, a Date object for Halloween, and subtract to find the difference. The script in Example 1-5 shows you how to do this.

Example 1-5: How long until Halloween?

<script language="JavaScript">
var now = new Date(  );
var then = new Date("October 31, 2001");
var gap = then.getTime() - now.getTime(  );
gap = Math.floor(gap / (1000 * 60 * 60 * 24));
document.write ("Only " + gap + " days  \'til Halloween");
</script>

First, the script creates a new Date object named now for the current date and another named then for Halloween. The current date, now.getTime( ), is then subtracted from Halloween's date, then.getTime( ), and the resulting value (the remaining time between the two dates) is stored in the variable gap. So we have the difference in time between now and Halloween in the variable gap, but there's a problem: it's in milliseconds. We need to convert milliseconds to days. We do this by dividing gap by the number of milliseconds in a day (1000 milliseconds × 60 seconds × 60 minutes × 24 hours):

gap / (1000 * 60 * 60 * 24) 

The difference in time, which is now in days, is then rounded down to the nearest full day with Math.floor( ). Finally, the number of days is displayed on the page with document.write( ).

Back to: Sample Chapter Index

Back to: Designing with JavaScript, 2nd Edition


oreilly.com Home | O'Reilly Bookstores | How to Order | O'Reilly Contacts
International | About O'Reilly | Affiliated Companies | Privacy Policy

© 2001, O'Reilly & Associates, Inc.
webmaster@oreilly.com