Night and Day - Page 3
November 30, 2001
Figure 1-2: A "day" page
|
Figure 1-3: A "night" page
|
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.
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>
Applying onMouseOver To Your Links - Page 2
Designing with JavaScript, 2nd Edition
The Script Tag - Page 4
|