Skip to main content.

Web Based Programming Tutorials

Homepage | Forum - Join the forum to discuss anything related to programming! | Programming Resources

Special Edition Using Java Script

chapter 5 -- Built-In JavaScript Objects

Chapter 5

Built-In JavaScript Objects


CONTENTS

JavaScript is designed to be easy to learn and convenient to use by almost anyone who seeks to create dynamic Web pages and client-side checking of input forms (as well as many other uses discussed in this book). Because the authors of JavaScript have had this in mind, they have provided you, the programmer, with many built-in objects that you will probably use quite often. These built-in objects are available through both the client-side JavaScript (inside the Netscape Navigator on your desktop) and through LiveWire (Netscape's server-side application). In addition, JavaScript has three functions that you can use throughout your scripts without having to declare them.

The three built-in objects are: the String object, the Math object, and the Date object. Each of these provides great functionality, and together they give JavaScript its power as a scripting

language. These built-in objects are discussed in depth in this chapter and you will find many examples for use in your own projects.

The String Object

As you saw in chapter 4, you can create a string object by assigning a string literal to a variable.

You call a string's methods by the same dot notation you would in other objects. For example, if demostring is "Some text here!" then demostring.bold() returns "Some text here!".

You can also use string methods on literals, as follows:

"This is some text".italics()

This line of code returns "This is some text", as displayed by your Web browser.

Table 5.1 shows the various methods that you can call with the string object to alter its HTML formatting.

Table 5.1  String Object Methods for HTML Formatting

Method Name
Example
Returned Value
anchor"foo".anchor("anchortext") <A NAME="anchortext">foo</A>
big"foo".big() <BIG>foo</BIG>
blink"foo".blink() <BLINK>foo</BLINK>
bold"foo".bold() <B>foo</B>
fixed"foo".fixed() <TT>foo</TT>
fontcolor"foo".fontcolor("green") <FONT COLOR="green">foo</
fontsize"foo".fontsize(-1) <FONT SIZE="-1">foo</FONT>
italics"foo".italics() <I>foo</I>
link"foo".link("linktext") <A HREF="linktext">foo</A>
small"foo".small() <SMALL>foo</SMALL>
strike"foo".strike() <STRIKE>foo</STRIKE>
sub"foo".sub() <SUB>foo</SUB>
sup"foo".sup() <SUP>foo</SUP>
toLowerCase"UPPERcase".toLowerCase() uppercase
toUpperCase"UPPERcase".toUpperCase() UPPERCASE

Figure 5.1 shows how the string "foo" would be rendered in your browser if you used each of the methods listed in table 5.1.

Figure 5.1 : String methods as rendered by Netscape Navigator.

Text without any modifications (denoted as Normal Text) is placed between some lines to help you see how each method changes the appearance of the text. Figure 5.2 shows you the source script that was used to create figure 5.1. Note that all of the strings were called as literals-that is, not as variables as you might normally see them.

Figure 5.2 : Source code for figure 5.1.

Chaining Methods

Not only can you change the formatting of the text in one way at a time, you can "chain" the various methods together to mimic the behavior of nesting HTML tags around a piece of text. This can be particularly useful if you generate HTML automatically via a script. For example, the following displays a blinking "FOO" on the page:

document.write("foo".blink().toUpperCase().bold())

Remember to include the parentheses after each of the methods even though they do not take any arguments. The preceding code appears to the browser as the following:

<B><BLINK>FOO</BLINK></B>

You can see that the BLINK tag is nested inside the B tag, since the blink method was called first. (JavaScript reads code from left to right and from top to bottom.) If you wish to have a desired effect with nesting tags, remember that the order of nesting is the leftmost string method nested inside the next method called to the right. The reason you can nest these methods is that they all accept and return a string object so it appears to the next method as a simple string-as if you had typed it in.

Nesting Methods Versus Chaining Methods
There are usually two ways you will see methods called in scripts you encounter. You might see something like this:
foo().bar().baz() "Chaining"
or you might see this:
foo(bar(baz()))) "Nesting"
The difference here can be subtle. With foo().bar().baz(), JavaScript will determine the result value of foo(), then treat that value as if it were the object called with .bar(). You must make sure that the value returned by the leftmost method is valid in order to have the second method "appended" to it, to continue calculations. It is valid here if foo() and bar() return strings, since string literals (what each of these methods return) can subsequently have other string methods. foo(bar(baz())) is different in that evaluation is conducted in right-to-left order. baz() is evaluated first and then is passed as a parameter to bar(). bar() must be able to accept a parameter of this type in order for this to work. For some methods, this difference in evaluation has no effect, but for others, you might get incorrect values.

Anchor and Link

Anchors and links are often confused because they appear to create similar output. An anchor in HTML is a location for a link to point to, and is given a name for subsequent links to identify that anchor. A link is a clickable area of text or an image that jumps the browser to the anchor. See chapter 4 for more discussion of this difference.

If you want to create an anchor in JavaScript such as the following:

<A NAME="section2">Starting Up</A>

you could use:

Avariable = "Starting Up"
Avariable.anchor("section2")

or you can just use the following:

"Starting Up".anchor("section2")

It helps to read the string like this:

"Starting Up using an anchor of name section2."

Links are used in a similar fashion. Only in this case, instead of giving an anchor a name, you are giving a link a URL. For example, to display a link to Yahoo, you would write the code in listing 5.1.


Listing 5.1  list5-1.txt  An Example Using link

var  linktext = "Yahoo"
var URL = "http://www.yahoo.com"

document.open()
document.write("This is a link to" + linktext.link(URL))
document.close()

This is equivalent to writing the following:

This is a link to <A HREF="http://www.yahoo.com">Yahoo</A>

In this case, you could read the string as:

"Yahoo's link is http://www.yahoo.com"

TIP
You can quickly create long strings from short ones by using the plus concatenator (+). The expression "Cat Fish" + " Sandwich" yields "Cat Fish Sandwich". Also, you can use the += operator (called the "plus-equal" concatenator) to tack a string on the end of another. If string1 = "hello", then string1+=" there" would become "hello there".

In addition to changing the formatting of a string object in HTML, you can also return parts of the string without having to know the actual contents of that string. This is extremely useful for parsing out different keywords or commands within some given input string by the user of your script.

Table 5.2 lists the methods of the string object that pertain to displaying subsets of the strings contents.

Table 5.2  String Object Methods for Displaying Subsets of Strings

Method NameExample(s)
Returned Value
charAt"netscape
navigator".charAt(0)
"netscape navigator"
.charAt(10)
n

a
indexOf"netscape navigator"
.indexOf("scape")
"netscape navigator"
.indexOf("n",2)
3

9
lastIndexOf"netscape navigator"
.lastIndexOf("a")
"netscape navigator"
.lastIndexOf("a", 12)
14

10
substring"netscape navigator"
.substring(0,7)
"netscape navigator"
.substring(7,0)
"netscape navigator"
.substring(0,50)
netscap

netscap

netscape navigator
length"netscape navigator"
.length
"netscape navigator"
.substring(0,7).length
18

7

Note that length is a property of a string and receives its value indirectly based on the number of characters in a string. You cannot directly assign a value to the length property.

charAt

The method charAt returns the character at the index specified. Characters are numbered from 0 to the length of the string minus 1.

Its syntax is:

stringName.charAt(index)

For example, the following returns "n":

thisstring = "Internet World"
thisstring.charAt(5)

indexOf

This method can be used to search down a string (from left to right) until it finds a string fragment matching the specified value. It returns the index of the first character of the matching string. You can use this information with the method substring (mentioned later in this section) to find keywords in a given string. This is useful when you allow the user to input some information and you wish to place parts of that information into different variables. For example, the following returns 9:

thisstring = "Internet World"
thisstring.indexOf("World")

If the keyword is not in the string, then indexOf returns a -1.

lastIndexOf

This method is identical to indexOf except that the method searches from right to left down the string to find the given keyword. It also returns the index value of the first character of the found keyword. For example, the following returns 5:

"Internet World".lastIndexOf("n")

substring

substring completes the suite of subset text methods. This method returns a substring given beginning and ending index values. Note that the values do not have to be in numerical order. The string returned from substring(1,9) is identical to the one returned from substring(9,1). Also, if you leave off the second index integer, substring assumes you want it to return everything from the first index to the end of the string. And leaving off both indices returns the entire string. For example, listing 5.2, which can be found on the CD-ROM as list 5-2.txt, returns "World":


Listing 5.2   list5-2.txt  An Example Using substring

thisstring = "Internet World"
thewordnum = thisstring.indexOf("World")
theword = thisstring.substring(thewordnum)
document.open()
document.write(theword)
document.close()

Length

The length property appears in many types of objects across JavaScript, and pertains to a different value based on the context in which it is used. In strings, this value is an integer based on the number of characters in a string (counting whitespace, etc). For a null string, this value is zero. You cannot directly alter this value except by adding or removing characters from a string. Since the value returned by "foo".length is a number, you can perform mathematical operations on it like any other number.

For instance, the following returns 7:

"Hi There".length - 1

The Math Object

As you saw in chapter 4, the Math object provides built-in constants and methods for performing calculations within the script.

The Math object's syntax is the following:

Math.propertyname

or

Math.methodname(parameters)

Table 5.3 summarizes the various methods and properties.

Table 5.3  Math Object Methods and Properties

Method NameExample Returned Value
absMath.abs(-79) 79
acosMath.acos(.5) 1.047197551196597631
asinMath.asin(1) 1.570796326794896558
atanMath.atan(.5) 0.4636476090008060935
ceilMath.ceil(7.6) 8
cosMath.cos(.4) 0.9210609940028851028
expMath.exp(8) 2980.957987041728302
floorMath.floor(8.9) 8
logMath.log(5) 1.609437912434100282
maxMath.max(1 , 700) 700
minMath .min(1 , 700) 1
powMath.pow(6,2) 36
randomMath.random() .7877896 (not fully implemented)
roundMath.round(.567) 1
sinMath.sin(Math.PI) 0
sqrtMath.sqrt(9801) 99
tanMath.tan(1.5*Math.PI) INF (infinity)

Math Methods

Although most of the methods used by Math are self-evident-such as using Math.sin to calculate the sine function of a number-they are summarized in the following sections, with examples for your reference.

abs  abs returns the absolute value of its numeric argument.

For example, the following returns 1:

     Math.abs(-1)

acos, asin, atan, cos, sin, tan  These return the appropriate trig function in radians. The a is short for arc, as in atan = arctangent.

For example, the following returns 3.141592653589793116:

     Math.acos(-1)

ceil  Returns the smallest integer greater than or equal to the argument passed to it. This is equivalent to always rounding up to the nearest integer.

For example, the following returns 15:

     with (Math) {
          foo = ceil(14.49999999);
      }

See also floor.

exp  Returns e to the power of its argument. Where if x is the argument, exp returns ex . (e is Euler's constant-the base of natural logarithms.)

For example, the following returns 148.4131591025765999:

     Math.exp(5)

floor  Returns the greatest integer less than or equal to the value passed to it. This is equivalent to always rounding down to the nearest integer.

For example, the following returns 1:

     numberone = Math.floor(1.9999999);
     document.write(numberone);

See also ceil.

log  Returns the natural log of the argument passed to it. The base is e.

For example, the following returns the log to the base e of pi, which is 1.144729885849400164:

     pie = Math.PI;
     pielog = Math.log(pie);
     document.write("The log to the base e of PI is: " + pielog + ".");

max, min  Given two numbers, max returns the greater of the two, and min returns the lesser of the two.

For example,

     with (Math) {
          document.write("Between Euler's constant and 
      PI, "+ max(E,PI) + " is                 greater.")
     }

Between Euler's constant and pi, 3.141592653589793116 is greater.

pow  Given a base and an exponent number, this returns the base to the exponent power.

For example, the following returns 10000:

     Math.pow(10,4)

random  Available only to UNIX platforms (Solaris, specifically) as of this writing, this returns a pseudorandom number between 0 and 1.

For example, the following returns 0.09983341664682815475:

     Math.random()

round  This method returns the argument rounded to the nearest integer. It rounds up if the number contains an integer of .5 or greater, and down otherwise.

For example, the following returns 1:

     with(Math) {
     java = round(1.4999999999);
     document.write(java);
     }

sqrt  Returns the square root of its argument. Note: the argument must be non-negative, otherwise the sqrt returns 0.

For example, the following returns 12:

     Math.sqrt(144);

An Example Sine Plotter  In figure 5.3, we see a Web site that has implemented a script that quickly generates a sine curve.
Figure 5.3 : A Web site using math methods.

Math Properties

The Math object provides you with a few constants that you can use for various scientific and algebraic functions. Note that these properties are constants and cannot be changed by JavaScript. The following is a list of each property and its approximate values:

Table 5.4 sumarizes the Math object properties and gives examples.

Table 5.4  Math Object Properties Summary

Property NameExample Returned Value
E (2.718281828459045091) Math.E*513.59140914229522501
LN10 (2.302585092994045901) Math.LN10/60.3837641821656743168
LN2 (0.69314718055994529)Math.LN2-Math.E -2.025134647899099694
PIMath.sin(2*Math.PI/4) 3.141592653589793116
SQRT21/Math.SQRT2 0.7071067811865474617

Using with and Math Objects

Using the Math object is essentially identical to using other objects in JavaScript with a few exceptions. If you use several Math constants and methods together in a block of code, you can use the with statement to avoid having to retype Math. over and over again.

For example, the following:

beta = Math.E * 62;
gamma = Math.PI / 4;
delta = x * Math.sin(theta);

becomes

with (Math) {
     beta  = E * 62;
     gamma = PI / 4;
     delta = x * sin(theta);
}

The Date Object

As you saw in chapter 4, the Date object provides information about the current date and time on the client's machine. The Date object is useful for designing sites that are sensitive to the time of day, or use time-based information to present to the user new information without having to use a CGI to access the server's clock.

NOTE
You cannot work with dates prior to 1/1/70. This is due to the cross-platform nature of this language-for example, UNIX machines consider 00:00:00 GMT January 1, 1970 to be "zero" on their clocks. Other operating systems have older zero settings (like Macintosh's January 1, 1904) so the most recent of them is considered the baseline for time.

The Date object is similar to the String object in that you create new instances of the object when you assign it to a variable. It differs from the String object in that you use a statement called new to create it. Using the new statement, you create a Date object that contains information down to the millisecond at that instant. Note: This data is created based on the time and date on the client's machine, not the time on your server. So if your page is located on the east coast, and a user visits your site from the west coast, the time reflects his location, not yours. It is important to note this because you have no control over the time on his machine. His clock may be wrong, or not even running (although unlikely). If your script depends heavily on having an accurate time in which to base its calculations, you might get strange effects when your script encounters these special cases. For instance, you might change the foreground text and background colors to reflect the time of day, but if the machine's clock is off, your page will seem "off."

The Syntax for Creating a New Date Object

To create a new Date object, you use the new operator. The Date object is pre-defined in JavaScript, and will build this instance filling in the current date and time from the client's system clock. Here is the syntax:

variableName = new Date(parameters)

For example,

today = new Date();

You have several optional parameters that you may send to the Date object, as follows:

TIP
Each of these forms has a few conventions you should be aware of. The first form, in which you omit all parameters, automatically sets the current date and time in the standard format of:
Day Month Date Hours:Minutes:Seconds Year
For example,
Sat Feb 24 14:43:13 1996
If you use the second or fourth form and omit the hours, minutes, or seconds, JavaScript automatically sets them to 0.

Using Date Methods

Once you have created a Date object, you can then use the many Date methods to get or set the month, day, year, hours, minutes, or seconds of this instance. Note: You cannot set the Day attribute independently-it depends on the month, year, and date attributes. As with most object methods, you simply call a Date method as follows:

     varibleName.methodname(parameters)

For example,

     today.setHours(7);

There are two exceptions to this rule with the Date object: The UTC and parse methods are "static" methods and are always called with just the generic Date object name.

For example,

     Date.UTC(parameters)
     Date.parse(parameters)

Table 5.5 summarizes the different Date methods.

Table 5.5  Date Object Methods

MethodExample Returns
getDatetoday.getDate() 5
getDayyesterday.getDay() 2
getHourstoday.getHours() 5
getMinutestoday.getMinutes() 30
getMonthyear.getMonth() 6
getSecondstime.getSeconds() 13
getTimenow.getTime() *****
getTimeZoneoffsettoday.getTimeZoneoffset ******
getYearnow.getYear 96 (the years since 1900)
parseDate.parse(July 1, 1996) *****
setDatenow.setDate(6) -
setHoursnow.setHours(14) -
setMinutesnow.setMinutes(50) -
setMonthtoday.setMonth(7) -
setSecondstoday.setSeconds(7) -
setTimetoday.setTime (yesterday.getTime()) -
setYeartoday.setYear(88) -
toGMTStringyesterday.toGMTString() Sat, Feb 24 1996 14:28:15 GMT
toLocaleStringtoday.toLocaleString() 2/25/96 14:28:15
UTCDate.UTC(96,11,3,0,0,0) -

Using all these methods' strings and numbers may look like a daunting task, but if you approach the Date object with a few concepts in mind, it makes working with this object much easier.

First, all of the methods can be grouped into four categories: get, set, to, and parse. get methods simply return an integer corresponding to the attribute you requested. set methods allow you to change an existing attribute in a Date object-again by passing an integer-only this time you are sending a number instead of receiving it. to methods take the date and convert it into a string-which then allows you to use any of the string methods to further convert the string into a useful form. parse methods (parse and UTC) simply parse-or interpret-date strings.

Secondly, Date attibutes like month, day, or hours are all zero-based numbers. That is, the first month is 0, the second 1, and so on. The same goes for days, where Sunday is 0, Monday is 1, and so on. The reason why numbering starts at 0 instead of 1 is that JavaScript closely mirrors Java in many respects-like always starting an array of "things" with 0. This is a convention followed by many languages and is considered a good programming practice. Table 5.6 lists the numeric conventions.

Table 5.6  Date Object Number Conventions

Date Attribute Numeric Range
seconds, minutes0 - 59
hours0 - 23
day (0 = Sunday, 1 = Monday, and so on) 0 - 6
date1 - 31
month (0 = January, 1 = February, and so on) 0 - 11
year0 + number of years since 1900

Thirdly, when a Date object is created, it takes the information from the Netscape Navigator's environment-usually right as the Web page is being loaded or sometime shortly after.(The Navigator gets information about its environment from the operating system. Other examples of environment variables are the number of other programs running, the current RAM used, and so on, although these may not be accessible by JavaScript.)

In the following sections, each Date method is described with a brief example.

get Methods

These methods allow you to retrieve information from the current Date object. This information can be the seconds, minutes, hours, day of the month, day of the week, months, or years. Notice that there is a getDay method that will give you the day of the week, but you cannot set this value, since the day of the week is dependent on the month, day, and year. See figure 5.4 for examples of the get methods.

Figure 5.4 : get method examples.

getDate  Given a date object, this returns the date as an integer between 1 and 31.

For example, the following returns 24:

today = new Date("February 24, 1996")
document.write(today.getdate())

getDay  This returns the day of the week.

For example, the following returns "Today is Saturday":

           today = new Date("February 24, 1996")
     if (today.getDay == 0) {document.write("Today is Sunday")}
     if (today.getDay == 1) {document.write("Today is Monday")}
     if (today.getDay == 2) {document.write("Today is Tuesday")}
     if (today.getDay == 3) {document.write("Today is Wednesday")}
     if (today.getDay == 4) {document.write("Today is Thursday")}
     if (today.getDay == 5) {document.write("Today is Friday")}
     if (today.getDay == 6) {document.write("Today is Saturday")}

getHours  This gives you the number of hours since 12:00 A.M.

For example, the following returns, "It's been 16 hours since our party last night!":

     today = new Date();
     document.write("It's been "+ today.getHours +
            " since our party last night!");

getMonth  Returns the month attribute of a given Date object.

For example, the following returns 1 (if this month is February):

     now = newDate()
     nowmonth = now.getMonth();
     document.write(nowmonth);

getSeconds  Returns the seconds of the given Date object.

For example, the following displays a different image about 50 percent of the time the user loads this page:

     now = newDate();
     if (now.getSeconds >30) {document.write("<img src = 
            'randimage1.gif'>")}
     if (now.getSeconds <=30) {document.write("<img src = 
            'randimage3.gif'>")}

getTime  Returns the number of milliseconds since January 1, 1970. This is useful in setting the time of another Date object.

For example,

     thisDay = new Date("September 25, 1969");
     myBirthday = new Date();
     myBirthday.setTime(thisDay.getTime());

See also setTime.

getTimeZoneoffset  Gives you the difference between the local time and GMT (Greenwich Mean Time).

For example,

     now = new Date()
     timeDifference = now.getTimeZoneoffset;
getYear  Returns an integer representing the year of the 20th century. Add 1900 to this number to get the current year.

For example,

          today = new Date("January 1, 1997");
     thisYear = new Date();
     var output = "Hi!";
     if (today.getYear == thisYear.getYear) { output +=" and Happy 
      New Year!"};
     document.write(output);

If the year is 1996, this returns "Hi!" If it is 1997, it returns "Hi! and Happy New Year!"

set Methods

These methods allow you to add or change attributes of the Date object. You can change the date, month, year, hours, minutes, and seconds of the Date object (see fig. 5.5). All of these methods require integers. Although you will probably use the get methods more often, these methods are handy when you want to quickly create a date and time-perhaps for displaying on a page with a modification date.

Figure 5.5 : setmethod examples.

setDate  Sets the numeric date of a Date object.

For example, the following returns 4:

     today = new Date("July 1, 1996")
     today.setDate(4);
     document.write (today.getDate())
setHours  This sets the hours of the given time.

For example, the following sets the hours attribute ahead 3 hours:

     today = new Date()
     today.setHours=(today.getHours() + 3);

setMinutes  This sets the minutes of the given time object (a number between 0 and 59).

For example, the following returns the current Date object (now) with the minutes set for 45:

now = new Date()
now.setMinutes(45)

setMonth  This sets the month integer in the given Date object.

For example, the following returns today (with the month now May):

today = newDate()
today.setMonth(4)

setSeconds  This sets the seconds of the given Date object.

For example, the following returns now (with the seconds set ahead 5 seconds):

now = new Date()
now.setSeconds(now.getSeconds()+5)

setTime  Sets the time value using an integer representing the number of seconds since January 1, 1970.

For example,

aDate = new Date();
aDate.setTime(4000*1000*1000*100);
document.write(aDate);

returns:

Sat Sep 04 08:06:40 1982

TIP
Instead of using a large integer as a parameter, you could pass a getTime() from another date, such as:
thisDay.setime(thatDay.getTime())

See also getTime.

setYear  This sets the year of the current date.

For example, the following returns now (with the year now 1997):

     nowYear = new Date()
     nowYear.setYear(97)

to Methods

These methods convert date information into another format. You can convert a date into a string (based on some set of conventions-as explained later). Once you have converted the date into a string, it can be treated just like any other string for HTML formatting, etc. (see fig. 5.6). Note that the original date object is not affected. These methods simply parse the date object and return a string based on the information it found.

Figure 5.6 : Using to methods.

toGMTString  This method converts the date to a string using the GMT convention.

For example,

     today = new Date()
     document.write((today.toGMTString).bold)

This returns <B>Sat, 24 Feb 1996 17:55:33 GMT</B>. This is also rendered to the Netscape Navigator in bold text. Note that the bold method appended the <B> and the </B> to the string, and is not a default action of toGMTString method. This illustrates how you can compact your code based on the assumption that a method returns a known type that you can then use with other methods.

toLocaleString  This method converts a date to a string using the locale conventions. Locale conventions are specific to each area that will view this site-meaning that toLocaleString might return a different string in Europe than in the U.S., since in Europe the day is presented before the month. So 09/03/96 might mean September 3rd to the U.S., whereas in Europe, it would mean March 9th.

For example, the following:

     thisdate.toLocaleString()

would return the following in the U.S., if the date was October 4th, 1996:

09/04/96 08:06:40

In Europe, it might return:

04/09/96 08:06:40

parse Methods

parse methods take strings and convert them to a resulting date object. These methods complement the to methods, in that they perform the converse of taking a date and coverting it into a string. parse methods are handy in rapidly creating a Date object or simplifying the process of passing a new value to a setTime() method (see fig. 5.7).

Figure 5.7 : Examples of parse methods.

parse  This method returns the number of milliseconds since January 1, 1970 00:00:00. It takes a string such as Feb 25, 1996 and is useful for setting date objects that already exist. It is acceptable to use the IETF standard date syntax, such as Sat, 24 Feb 1996 18:15:11 GMT. It understands U.S. time zone abbreviations, but Netscape recommends you use a time zone offset (thus, the use for the getTimeZoneoffset method). Note: The parse function is a static method of Date, so it is always called using Date.parse(), not with the name of the specific date object instance.

For example,

          netTime = new Date()
     timeString="Jul 10, 1908"
          netTime.setTime(Date.parse(timeString));

This returns the current Date object netTime with the changed month, day, and year.

UTC  UTC stands for Universal Time Coordinated and is equivalent to GMT. This method is static for Date, and is always called via Date.UTC. It is called using the following syntax:

     Date.UTC(year, month, day) 

or

     Date.UTC(year, month, day, hours, minutes, seconds)

Remember that JavaScript is case-sensitive, so always use uppercase UTC. Also, remember that you use the same integer conventions listed in table 5.6.

For example,

     theDate = new Date(Date.UTC(96 ,  1 ,  24 , 12 , 45 , 22));

JavaScript Examples Using the Date Object

Now that you have survived learning all of the various methods, examples, and numbers listings, it's time to begin doing some interesting things with your knowledge. The following sections show two examples of JavaScript scripts that use the Date object in very different ways. One gives you a straightforward clock to add to your Web pages, and the other gets around the limitation in the current version of JavaScript (in Netscape 2.0) of not having a working random() function. By taking the current hours, minutes, and seconds of a user's visit to your Web page, you can generate a "pseudorandom" number.

A Simple Clock in JavaScript  This script samples the time every second, converts that information into a readable string, and displays that string in a small textbox on the screen.


Listing 5.2  A Simple Clock

<HTML>
<HEAD>
<TITLE>JavaScript Clock</TITLE>
<script Language="JavaScript">
<!- Hide me from other browsers
// Netscapes Clock - Start
// this code was taken from Netscapes JavaScript documentation at
// www.netscape.com on Jan.25.96
var timerID = null;
var timerRunning = false;
function stopclock (){
        if(timerRunning)
                clearTimeout(timerID);
        timerRunning = false;
}
function startclock () {
        // Make sure the clock is stopped
        stopclock();
        showtime();
}
function showtime () {
        var now = new Date();
        var hours = now.getHours();
        var minutes = now.getMinutes();
        var seconds = now.getSeconds()
        var timeValue = "" + ((hours >12) ? hours -12 :hours)
        timeValue += ((minutes < 10) ? ":0" : ":") + minutes
        timeValue += ((seconds < 10) ? ":0" : ":") + seconds
        timeValue += (hours >= 12) ? " P.M." : " A.M."
        document.clock.face.value = timeValue;
        // you could replace the above with this
        // and have a clock on the status bar:
        // window.status = timeValue;
        timerID = setTimeout("showtime()",1000);
        timerRunning = true;
}
// Netscapes Clock - Stop  ->
</script>
</HEAD>
<BODY bgcolor="#ffffff" text="#000000" link="#0000ff"
alink="#008000" vlink="800080" onLoad="startclock()">
<form name="clock" onSubmit="0">
<div align=right>
<input type="text" name="face" size=12 value="">
</div>
</form>
<H1>Now you can add a clock to your pages!</H1>
</BODY>
</HTML>

Figure 5.8 shows how this would appear on your page.

Figure 5.8 : A simple clock example.

The heart of this script is the function showtime(). This function creates a Date object called now and pulls out (via getHours, getMinutes, and getSeconds) the hour, minutes, and seconds values. It then creates a variable called timeValue and assigns the hour to it as a string. timeValue is interpreted by JavaScript as a string even though hours is a number because the first value assigned to timeValue was the empty quotes (""). Notice that if the hours value is greater than 12 it is reduced by 12 to account for conventional 12-hour time notation. Notice also that if the number of seconds or minutes is less than 10, the function appends a "0" before that number to keep the number of digits the same space, and to avoid confusion between 03 and 30. This script runs the function showtime() every 1000 milliseconds (once a second) to display the current time in a format that is easy for the user to interpret.

One of the most useful aspects of JavaScript is that it uses an object-oriented approach to programming. What this means is that you (the scripter) can easily take functions that you worked so hard to perfect in one script and adapt them quickly to another script-often with little or no modifications. You can see in the comments of listing 5.2 that if you want, you can direct the output of the function showtime() to the status bar on the bottom of your browser, instead of displaying it in the textbox field on the page. You would do this by commenting out or deleting the following line:

document.clock.face.value = timeValue;

You would also need to remove the comments (the // ) from the following line:

// window.status = timeValue;

It would then look like this:

window.status = timeValue;

Using the status line has the advantage in that the text is less likely to flicker when it updates, as many rapidly updated form fields tend to do. Also, you can easily modify this code-instead of displaying the current time on the screen-to send it to another function. This function might then use that changing information to reload a clockface image (or almost anything your imagination comes up with).

Pseudorandom Generator  Listing 5.3 shows how you can simulate a seemingly random event. This is currently one of the few ways to work around the fact that the math.random() function is not enabled in all versions of Netscape Navigator (across platforms). The background behind this script is this: I wanted to find a way to generate a short three-word sentence based on a list of verbs, adjectives, and objects. These words came together to create a "Magic Talent," which simu-lates what happens to a number of fictional characters in various fantasy novel series. As someone enters the page, the date is sampled and used as a "seed" number to select one word from each list. These words are then concatenated together on-the-fly and displayed on the page. Essentially, it takes advantage of the fact that someone is unlikely to visit the page at exactly the same hour, minute, and second each day, so it appears to the page visitor that the selection is truly "random." The illusion disappears, though, if he repeatedly reloads this page-since the sentence will change only slightly.


Listing 5.3  The Random Talent Generator

<HTML>
<HEAD>
<TITLE>Random Talents Generator</TITLE>
</BODY>
</HEAD>
<BODY bgcolor=#ffffff>
<script language="JavaScript">
<!- Random Talent Generator
var currentdate=0
var spacer= " "
var talent= " "
var theverb= " "
var theadj = " "
var theobjec = " "
var core = 0
var description = "Here is your randomly generated 
Random talent. <br> Reload after a while for a new one. <br>"
function StringArray (n) {
        this.length = n;
        for (var i = 1; i <= n; i++) {
                this[i] = ''
        }
        return this
}
verb = new StringArray(10)
verb[0] = 'grow'
verb[1] = 'banish'
verb[2] = 'transform'
verb[3] = 'lift'
verb[4] = 'control'
verb[5] = 'shrink'
verb[6] = 'enlarge'
verb[7] = 'age'
verb[8] = 'youthen'
verb[9] = 'speak to'
adj = new StringArray(10)
adj[0] = 'large'
adj[1] = 'small'
adj[2] = 'green'
adj[3] = 'invisible'
adj[4] = 'mirage'
adj[5] = 'glowing'
adj[6] = 'wooden'
adj[7] = 'armored'
adj[7] = 'imaginary'
adj[8] = 'glass'
adj[9] = 'ghostly'
objec = new StringArray(10)
objec[0] = 'dragons'
objec[1] = 'animals'
objec[2] = 'plants'
objec[3] = 'fruit'
objec[4] = 'humans'
objec[5] = 'centaurs'
objec[6] = 'swords'
objec[7] = 'castles'
objec[8] = 'trees'
objec[9] = 'pies'
function getVerb (){
        currentdate = new Date()
        core = currentdate.getSeconds()
        adcore = Math.floor(core/6)
        core=adcore
        theverb = verb[core]
        return (theverb)
}
function getAdj (){
        currentdate = new Date()
        core = currentdate.getMinutes()
        adcore = Math.floor(core/6)
        core=adcore
        theadj = adj[core]
        return (theadj)
}
function getObjec (){
        currentdate = new Date()
        core1 = currentdate.getSeconds()
        core2 = currentdate.getMinutes()
        core3 = core1 + core2
        adcore = Math.floor(core3/12)
        core = adcore
        theobjec = objec[core]
        return (theobjec)
}
// main program
document.write("Random Talent Generator".fontsize(6) + "<p>")
document.write(description + spacer + "<p>" +
getVerb() + spacer + getAdj()+ spacer + getObjec())
document.write("<p>")
// ->
</script>
<p>
If you dont see anything above this line, you dont have Netscape 2.0.<br>
</BODY>
</HTML>

Figure 5.9 illustrates how this page would appear.

Figure 5.9 : The Random Talent Generator.

When the user loads this page, the script creates three string arrays and fills them in with the strings I provided. It then uses the getVerb(), getAdj(), and getObjec() to get one of the strings in the array based on the number of seconds, minutes, or the average of the two. This is done by taking the number of seconds in the currentdate.getSeconds, dividing it by 6, and then using the Math.floor method to return an integer between 0 and 9.

Since there is no real way to know when someone will visit this page, and the seconds change rapidly, there is a good chance that it will be difficult for someone visiting only once or twice a day to discern that the "Talents" aren't actually random.

You also see an example of using the string method fontsize(). The method fontsize() allows you to replace the "<FONT SIZE=''>...</FONT> tags with just a number passed to the fontsize() method. Usually this will be a negative or postive 1.

Note that it works fine with the string literal "Magic Talent Generator". We could just as easily have assigned that string to a variable, say titleString, and then used titleString.fontsize(6)

TIP
You may find yourself using many of the same functions over and over in many different scripts. It's good practice to keep a personal library of useful functions so you can find them (and use them!) over and over again.

.