Skip to main content.

Web Based Programming Tutorials

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

Special Edition Using Jscript

Untitled

Chapter 5

Built-In JScript Objects


CONTENTS

JScript 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 JScript 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 JScript in Internet Explorer and also on the server. In addition, JScript has four objects that you can use throughout your scripts without having to declare them.

The four built-in objects are: the String object, the Math object, the Date object, and the Array object. Each of these provides great functionality, and together they give JScript 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. This chapter will discuss the first three built-in objects in detail (there really isn't much to say about the Array object).

Be sure to review Chapter 4 "JScript Objects," which introduced you to JScript's built-in objects.

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</FONT>
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> <STRIKE>foo</
sub "foo".sub() <SUB>foo</SUB>
sup "foo".sup() <SUP>foo</SUP>
toLowerCase "UPPERcase".toLowerCase() uppercase
toUpperCase "UPPERcase".toUpperCase() UPPERCASE

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. The CD-ROM file FOO.HTM contains the source. Note that all of the strings were called as literals-that is, not as variables as you might normally see them.

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".toUpperCase().blink().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, because the blink method was called first. (JScript reads code from left to right and from top to bottom.) If you want 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:
foo(bar(baz()))) "Nesting"
The difference here can be subtle. With foo().bar().baz(), JScript 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, because string literals (what each of these methods returns) 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 "JScript Objects," for more discussion of this difference.

If you want to create an anchor in JScript 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, but in this case, instead of giving an anchor a name, you are giving a link an URL. For example, to display a link to Yahoo!, you would write the code in Listing 5.1. This code is contained in the CD-ROM file list5-1.js.


Listing 5.1  list5-1.js  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 onto 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.

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

Table 5.2  String Object Methods for Displaying Subsets of Strings

Method Name Example(s)Returned Value
charAt "Internet
Explorer".charAt(0)
"Internet Explorer"
.charAt(10)
I

x
indexOf "Internet Explorer"
.indexOf("net")
"Internet Explorer"
.indexOf("e",2)
5

3
lastIndexOf "Internet Explorer"
.lastIndexOf("e")
"Internet Explorer"
.lastIndexOf("e", 12)
15

6
substring"Internet Explorer"
.substring(0,7)
"Internet Explorer"
.substring(7,0)
"Internet Explorer"
.substring(0,50)
Internet

Internet

Internet
Explorer
length"Internet Explorer"
.length
"Internet Explorer"
.substring(0,7).length
17

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 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 argument, 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 returns "World":


Listing 5.2   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 JScript, 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, and so on). For a null string, this value is zero. You cannot directly alter this value except by adding or removing characters from a string. Because the value returned by "foo".length is a number, you can perform mathematical operations on it, like any other number.

For instance:

"Hi There".length - 1
would return the following:
7

The Math Object

As you saw in Chapter 4 "JScript Objects," 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 of the Math object.

Table 5.3  Math Object Methods and Properties

Method Name ExampleReturned Value
abs Math.abs(-79) 79
acos Math.acos(.5) 1.047197551196597 631
asin Math.asin(1)
Math.ceil(7.6)
1.570796326794896 558
8
cos Math.cos(.4) 0.9210609940028851 028
atan Math.atan(.5) 0.4636476090008060 935
ceil exp Math.exp(8) 2980.957987041728 302
floor Math.floor(8.9) 8
log Math.log(5) 1.60943791243410 0282
max Math.max(1, 700) 700
min Math.min(1, 700) 1
pow Math.pow(6,2) 36
random Math.random() .7877896 (varies)
round Math.round(.567) 1
sin Math.sin(Math.PI) 0
sqrt Math.sqrt(9801) 99
tan Math.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 that 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. This 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. 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. This 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. This 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.141592653589793 is greater.

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

For example, the following returns 10000:

     Math.pow(10,4)

random. This method returns a pseudo-random number between 0 and 1.

For example, the following might return 0.09983341664682815475:

     Math.random()

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

For example, the following returns 1:

     with(Math) {

     tmp = round(1.4999999999);
     document.write(tmp);
     }

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

For example, the following returns 12:

     Math.sqrt(144);

Summary of Math Object Properties

Table 5.4 shows a summary of Math Object properties.

Table 5.4  Math Object Properties Summary

Property Name ExampleReturned Value
E (2.718281828459045091)
13.59140914229522501
Math.E*5
LN10 (2.302585092994045901)
0.3837641821656743168
Math.LN10/6
LN2 (0.69314718055994529)
-2.025134647899099694
Math.LN2-Math.E
PI 3.141592653589793116 Math.sin(2*Math.PI/4)1
SQRT2 0.7071067811865474617 1/Math.SQRT2

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 JScript. The following is a summary with each property's approximate values.

Using with and Math Objects

Using the Math object is essentially identical to using other objects in JScript, 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 "JScript Objects," 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 new information to the user 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 must use the new statement 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 the server. So, if your page is located on the East Coast, and a user visits your site from the West Coast, the time reflects your visitor's location, not yours. It is important to note this because you have no control over the time on users' machines. Their clocks may be wrong, or not even running (although this is 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 client machine's clock is off, your page will also 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 predefined in JScript and will build this instance by 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:

variableName = new Date(year, month, day, hours, minutes, seconds)

Tip
Each of these forms has a few conventions you should be aware of.
The first form, in which you omit all parameters, automatically gives 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, JScript automatically sets them to 0.

Using the 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
getDate today.getDate()
 5
getDay yesterday.getDay()
 2
getHours today.getHours()
 5
getMinutes today.getMinutes()
30
getMonth year.getMonth()
 6
getSeconds time.getSeconds()
13
getTime now.getTime()
*****
getTimeZoneoffset today.getTimeZoneoffset
******
getYear now.getYear96 (the years since 1900)
 
parse Date.parse(July 1, 1996)
*****
setDate now.setDate(6)
-
setHours now.setHours(14)
-
setMinutes now.setMinutes(50)
-
setMonth today.setMonth(7)
-
setSeconds today.setSeconds(7)
-
setTime today.setTime(yesterday.getTime())
-
setYear today.setYear(88)
-
toGMTString yesterday.toGMTString()
Sat, Feb 24 1996 14:28:15 GMT
toLocaleString today.toLocaleString()
2/25/96 14:28:15
UTC Date.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 that string into a useful form. parse methods (parse and UTC) simply parse-or interpret-date strings.

Second, Date attributes such as 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 JScript closely mirrors Java in many respects-such as 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, minutes
0 - 59
hours
0 - 23
day
0 - 6
(0 = Sunday, 1 = Monday, and so on)
 
date
1 - 31
month
0 - 11
(0 = January, 1 = February, and so on)
 
year
0 + number of years since 1900

Third, when a Date object is created, it takes the information from the browser's environment-usually right as the Web page is being loaded or sometime shortly after.

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, because the day of the week is dependent on the month, day, and year. See Figure 5.1 for examples of the get methods.

Figure 5.1:The get methods extract information from a Date object.

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 midnight.

For example, if it is 4 P.M., 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 2 (if this month is March):

     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. This function gives you the difference between the local time and GMT (Greenwich Mean Time) in minutes.

For example:

     now = new Date()
     timeDifference = now.getTimeZoneoffset;

getYear. Returns an integer representing the year of the Twentieth 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

These methods enable 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 Figure 5.2). All of these methods require integers. Although you will probably use the get methods more often, these methods are handy when you quickly want to create a date and time-perhaps for displaying on a page with a modification date.

Figure 5.2: The set methods modify information in a Date object.

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);

would return:

Sat Sep 04 11:06:40 1982

Tip
Instead of using a large integer as a parameter, you could pass the return value from using getTime() on 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, and so on (see Figure 5.3). 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 has found.

Figure 5.3: The Date to methods provide several different string output formats.

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 in bold text. Note that the bold method appended the <B> and the </B> to the string, and is not a default action of the 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 from in the U.S., because in Europe, the day is presented before the month. So, 09/03/96 would mean September 3rd in the U.S., whereas in Europe it would mean March 9th.

For example, if the date were September 4th, 1996, the following:

     thisdate.toLocaleString()

would return the following string in the U.S:

09/04/96 08:06:40

In Europe, it would 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 converting 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 Figure 5.4).

Figure 5.4: 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 it is safer to 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));

returns the current Date object netTime with the new 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 JScript 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));

JScript Examples Using the Date Object

Now that you have survived learning all of the various methods, examples, and numerical conventions, it's time to begin doing some interesting things with your knowledge. The following sections show two examples of JScript 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 provides a different way of generating random numbers. By taking the current hours, minutes, and seconds of a user's visit to your Web page, you can generate a "pseudo-random" number.

A Simple Clock in JScript. This script shown in Listing 5.3 samples the time every second, converts that information into a readable string, and displays that string in a small text box on the screen.


Listing 5.3  A Simple Clock
<HTML>
<HEAD>
<TITLE>JScript Clock</TITLE>
<script Language="JScript">
<!-- Hide me from other browsers

// This code was adapted from Netscape's clock, given in
// their JScript examples page

// Global variables
var timerID = null;
var timerRunning = false;

// stop the clock

function stopclock (){
        if(timerRunning)
                clearTimeout(timerID);
        timerRunning = false;
}

// start the clock

function startclock () {
        // Make sure the clock is stopped
        stopclock();
        showtime();
}

// actually display the time
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;
}

</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.5 shows how this would appear on your page.

Figure 5.5 : The Date object can be used to construct a simple Web page clock.

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 JScript as a string even though hours is a number because the first value assigned to timeValue was the empty string (""). 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, 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 JScript 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 few or no modifications. As the comments of Listing 5.3 indicate, 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 text box 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).

Pseudo-Random Generator. Listing 5.4 shows how you can simulate a seemingly random event. 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 simulates 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 they repeatedly reload this page-since the sentence will change only slightly. This script will also be found on the CD-ROM, in the file ex53.htm.


Listing 5.4  ex53.htm-The Random Talent Generator
<HTML>
<HEAD>
<TITLE>Random Talents Generator</TITLE>
</BODY>
</HEAD>
<BODY bgcolor=#ffffff>
<script language="JScript">
<!-- 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 do not see anything above this line, you do not have a
JScript or JavaScript compatible browser.<br>

</BODY>
</HTML>

Figure 5.6 illustrates how this page would appear.

Figure 5.6: The JScript "Random Talent Generator" uses the date as a random seed.

When the user loads this page, the script creates three string arrays (verb, adj, and objec) and fills them in with the strings 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.

Because 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() enables you to replace the "<FONT SIZE=''>...</FONT> tags with just a number passed to the fontsize() method. Usually, this will be a negative or positive 1, to decrease or increase the font size by one point.

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!) again.