|
|
|
|
Designing with JavaScript, 2nd EditionA Definitive IntroductionBy Nick Heinle & Bill Pena2nd Edition November 2001 1-56592-360-X, Order Number: 360X 230 pages, $34.95 |
Chapter 1
Diving into JavaScriptIf 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:
- Event handlers
- Variables
- Working with objects
- Writing to a document
- The if statement
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:
- This code is enclosed in double quotes, which are used as a way of indicating where the code starts and where it stops. This, too, should be a familiar construct, since we use double quotes in HTML to indicate the beginning and end of a value (e.g., <a href="page.html">).
- window.status is JavaScript's way of referring to the status bar. It actually refers to the status property of the window object. We'll discuss what these terms mean later in this chapter.
- The equal sign here is used to assign a value to window.status, giving it a string of text to display.
- The text after the equal sign is enclosed in single quotes. Again, we use the quotes to indicate the beginning and end of the value, but here we use single quotes instead of double quotes. That's because the text occurs inside the double-quoted JavaScript string. If we used double quotes for the link description, the JavaScript interpreter would think that the JavaScript code ended with the second double-quote character. Whenever you're nesting a string inside another string, you must alternate between single and double quotes.
- The semicolon after the description text indicates the end of a line of JavaScript. Get used to seeing semicolons; virtually every line of JavaScript ends in a semicolon.
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:
- The Date and document objects
- Variables
- Properties and methods
- The if statement
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
<script language="JavaScript"> <!-- hide me from antiquated technology JavaScript code // stop hiding me --> </script> 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
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
houris 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
<html> <body> <form name="mailform"> <input type="text" name="address"> </form> </body> </html> 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
myCar.accelerate(15); This would accelerate the car by 15 miles per hour. 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
© 2001, O'Reilly & Associates, Inc.
webmaster@oreilly.com