Documente Academic
Documente Profesional
Documente Cultură
Chapter 1
1
Adding descriptive links
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.
Figure 1-1
The event
The link in Example 1-1 looks like a normal link, but it’s obviously a little
The onMouseOver event handler different. Inside the <a> tag, there is a small piece of JavaScript code. The
is invoked when the user moves the code starts (and the HTML ends) with onMouseOver; this is one of Java-
mouse over a link. Script’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
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">).
Example 1-2: Improved code for adding status bar text to a link
The onMouseOut event handler is
<a href="http://www.oreilly.com/catalog/learncocoa/"
triggered when the mouse moves onMouseOver="window.status =
out of a link. '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.
Figure 1-2
A “day” 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
Figure 1-3
A “night” page
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.
NOTE
The Date object and variables
The first part of the night and day script detects the time of day, using the What’s in a name?
system clock on the user’s computer. It does this with the Date object, A variable name must start with a
which is built right into JavaScript: letter or an underscore character.
Subsequent characters can be letters,
var now = new Date( ); underscores, or digits. Thus, these are
var hour = now.getHours( ); valid variable names: myCan, Can1, and
The first line simply creates a new Date object and gives it the name now. In _Can1. These are not: 1Can, $Can, and
!Can.
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 under-
stand shortly, getHours() is a method of the Date object. Now we can also
refer to the current hour by name, using the variable hour.
NOTE 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
Case matters can assign a value to it with the equal sign followed by the initial value for
In JavaScript, variable names (and the variable, as we’ve done here with now and hour.
function names) are case-sensitive. For
instance, now and Now refer to two
different variables. After you create a Displaying the page
variable, be sure that you always use
Now that we have the current hour, we need to do something with it. This
the same case to refer to that variable.
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'>");
A few comments
built-in methods in this book. JavaScript also allows you to define your
own functions, as we’ll discuss in Chapter 2. The document.write() method
allows you to print HTML directly
onto a web page.
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 some-
thing 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
}
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
An if statement runs some code if run if the condition isn’t met:
a condition is true, and optionally
if ( this is the case ) {
some other code if it is not. 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 pro-
motional 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 night-
time 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.
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.
First, the script creates a new Date object named now for the current date TIP
and another named then for Halloween. The current date, now.getTime( ),
is then subtracted from Halloween’s date, then.getTime( ), and the View source
resulting value (the remaining time between the two dates) is stored in the One of the best ways to learn
variable gap. So we have the difference in time between now and Hal- JavaScript is to examine and
loween in the variable gap, but there’s a problem: it’s in milliseconds. We experiment with existing code.
need to convert milliseconds to days. We do this by dividing gap by the Fortunately, it is easy to look at other
number of milliseconds in a day (1000 milliseconds × 60 seconds × 60 people’s code, using the View ➝
Source feature that is built into every
minutes × 24 hours): web browser.
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 dis-
played on the page with document.write( ).