MSc-IT Study Material
June 2010 Edition

Computer Science Department, University of Cape Town

Some Basic JavaScript Objects

So far we have used the Window and Document objects. We now list many of the most frequently needed properties of Window and Document and all of the details of Date, which we have not yet used.

You do not have to memorise these lists. You will eventually remember what you most often use. However, it is important to spend time reading reference material because sometimes you will need some facility and will need to be aware if it exists or not. Later activities assume you can use most of the facilities described below.

Notice that some properties are described as an 'array' with square brackets. An array is a collection of items numbered from zero, as in Java, and is accessed in the same way, using a suffix containing the index number in square brackets. For instance, window.frames[2] refers to the third frame in a window. Arrays are covered in more detail in a later chapter.

First, note that variables window and document are automatically declared so that we have been able to make use of them when scripting. They refer to the current window and its document respectively. Automatic declaration, however, is not usual. For example, to use a Date object you will have to create one with a constructor, as described later.

Note that where a method requires an argument or arguments, these arguments are indicated by a phrase in angle brackets that list the arguments that are needed. For example, <string> would indicate that a string argument is needed. (Do not confuse these with HTML tags.)

Window Objects

The following table lists frequently used properties and methods that are supported by Firefox, Internet Explorer and Opera.

WindowDescription
Properties (Partial List)

defaultStatus — a string that specifies what appears in the window's status area

document — a reference to the document object contained by the window

frames[] — an array of frames in the window's document

length — the number of elements in the frames array, i.e. the number of frames

location — a reference to the Location object for the window

Math — a reference to a mathematical object that provides various mathematical functions

name — a string containing the name of the window

self — a reference the window itself

status — a reference to the window's status area

top — a reference to the top-level window containing this one, only if this one is a frame

Methods (Partial List)

alert(<string>) — produced a dialogue box containing the string and a single button labelled OK

close() — close the window

confirm(<string>) — ask a yes/no question with the string argument

moveBy(<number in x>, <number in y>) — move the window by the given number of pixels in the x (horizontal) and y (vertical) directions

moveTo(<number for x>, <number for y>) — move the window to the location given for x (horizontal) and y (vertical) directions

prompt(<string for prompt>, <string for default>) — prompt with OK and Cancel buttons using the first string as prompt and the second as default for input

resizeBy(<number in x>, <number in y>) — resize the window by the given number of pixels in the x (horizontal) and y (vertical) directions

resizeTo(<number for x>, <number for y>) — resize the window to the size given for x (horizontal) and y (vertical) directions

scrollTo(<number for x>, <number for y>) — scroll the document in the window so that the position given for the x (horizontal) and y (vertical) direction is in the tope left corner of the window

Note that because the Window object (referred to by the window variable) is the main object of the system as far as JavaScript is concerned, its name can be left out. Therefore we could have simply written confirm("Click on OK or Cancel or close box"). However, we recommend you explicitly use the window object.

There are some exceptions to this recommendation. The first is the use of the Math object ('math' being the American abbreviation for 'mathematics'). Because the window contains a Math object as a property, you can refer to it simply using Math. For example Math.floor(<number>) allows you to truncate (i.e. round down) a real number to the next smaller integer (not the closest to zero). Hence:

    document.write("Math.floor(6.7) = ", Math.floor(6.7), "<BR>")
    document.write("Math.floor(-6.7) = ", Math.floor(-6.7), "<BR>")
 

produces the following:

Document Object

The list of Document properties given below is almost complete (excluding those specific to particular browsers). Many are arrays, or are associated with other objects not yet encountered. Do not expect to use these in this unit.

DocumentDescription
Properties (Partial List)

aLinkColor — string specifying colour of active links

anchors[] — an array of Anchor objects

applets[] — an array of Java (not JavaScript) applets (one for each HTML <APPLET> tag)

bgColor — background colour of document

cookie — a string associated with document cookies

domain — specifies the Internet domain that was the source of the document

embeds[] — an array of embedded objects (one for each HTML <EMBED> tag)

fgColor — foreground colour of document text

forms[] — an array of Form objects (one for each HTML <FORM> tag)

images[] — an array of Image objects (one for each HTML <IMG> tag)

lastModified — a string specifying the date of the last change to the document as reported by its Web server

linkColor — string specifying colour of unvisited links

links[] — an array of Link objects (one for each hypertext link)

location — a synonym for the URL property (not the same as window.location)

plugins[] — a synonym for the embeds[] property

referrer — a string specifying the URL of the document containing the link to this one that the user followed to reach the document

title — title of the document (may not be changed)

URL — a string containing the URL of the document (may not be changed)

vlinkColor — string specifying colour of visited links

Method (Partial List)

close() — closes the document stream opened using the open() method

open() — open a stream to which document contents can be written, i.e. to which output of subsequent write() or writeln() methods will be appended

write(<at least one argument>) — appends to current output stream; takes any argument that can be converted to a string

writeln(<at least one argument>) — same as write() but adds a new line to output that usually has no effect for HTML, except if after <PRE> tag.

Date Objects

Date objects have properties and methods for handling date and time. To access dates or times a Date object must be created, typically using new Date(). Facilities are provided for both the local date and time and universal date and time (UTC) or Greenwich Mean Time (GMT). For example, the following JavaScript code creates a new Date object as part of the initialization of the variable today.

    var today = new Date()
    document.write('1 -- ', today, '<BR>')
    document.write('2 -- ', today.toGMTString(), '<BR>')
    document.write('3 -- ', today.toLocaleString(), '<BR>')
      

The following is the output that results in Internet Explorer.

Unfortunately, the form of the string representations of dates varies from browser to browser and it looks like this in Navigator:

The following table lists the attributes and methods of Date. Note that Date has no properties. Usually you can interchange the terms attribute and property. In English they mean more or less the same thing. However, in object technology an attribute is simply an idea you name because you expect it is somehow represented by the object. Often an attribute is represented in JavaScript as a property, but not in this case. You cannot directly access attributes of a date like the hour or minute; you must use accessor methods, such as the methods that begin with 'get' or 'set' below.

Date Date objects have attributes and methods for handling date and time. To access dates or times a Date object must be created, typically using new Date(). Facilities are provided for both the local date and time and universal date and time (UTC) or Greenwich Mean Time (GMT).
Date Constructors

There are four forms of constructor for Date

  1. new Date() In the first form, a Date object is created initialised to the current date and time.

  2. new Date(time in milliseconds) In the second form, the date and time given to the object created is specified by the time in milliseconds from 1 January 1970, GMT. This is usually used when the number of milliseconds has been computed using various Date methods.

  3. new Date(string in date format) In the third form an appropriately formatted string is used to set the date and time of the newly created object.

  4. new Date(year, month, day, hour, minute, second, millisecond) In the fourth form between two and seven numbers are given to specify the date and time, attribute by attribute (see under Properties).

Date Properties

There are no properties that can be get or set directly. All attributes of a Date object must be accessed via its methods. The Date attributes are:

year — a four digit number

month — an integer between 0, for January, and 11, for December

day — an integer between 1 and 31 specifying the day of the month

hour — an integer between 0, for midnight, and 23, for 11pm

minute — an integer between 0 and 59 that specifies the minute in the hour

second — an integer between 0 and 59 that specifies the second in the hour

millisecond — an integer between 0 and 999 that specified the millisecond

Date Methods

getDate() — returns the day attribute, i.e. the day of the month between 1 and 31

getDay() — returns the day of the week, 0 for Sunday, 1 for Monday, ..., 6 for Saturday

getFullYear() — returns the year attribute (getYear() is deprecated version)

getHours() — returns the hour attribute (note plural in method name)

getMilliseconds() — returns the millisecond attribute (note plural in method name)

getMinutes() — returns the minute attribute (note plural in method name)

getMonth() — returns the month attribute

getSeconds() — returns the second attribute (note plural in method name)

getTime() — returns the date as the number of milliseconds since midnight, 1 January 1970

getTimezoneOffset() — returns the time zone difference in minutes between date and GMT

getUTCDate() — returns in universal time the day attribute, i.e. the day of the month between 1 and 31

getUTCDay() — returns in universal time the day of the week, 0 for Sunday, 1 for Monday, ..., 6 for Saturday

getUTCFullYear() — returns in universal time the year attribute

getUTCHours() — returns in universal time the hour attribute (note plural in method name)

getUTCMilliseconds() — returns in universal time the millisecond attribute (note plural in method name)

getUTCMinutes() — returns in universal time the minute attribute (note plural in method name)

getUTCMonth() — returns in universal time the month attribute

getUTCSeconds() — returns in universal time the second attribute (note plural in method name)

setDate(<number 1-31>) — sets the day attribute, i.e. the day of the month between 1 and 31

setDay(<number 0-6>) — sets the day of the week, 0 for Sunday, 1 for Monday, ..., 6 for Saturday

setFullYear(<four-digit number>) — sets the year attribute (setYear() is deprecated version)

setHours(<number 0-23>) — sets the hour attribute (note plural in method name)

setMilliseconds(<number 0-999) — sets the millisecond attribute (note plural in method name)

setMinutes(<number 0-59>) — sets the minute attribute (note plural in method name)

setMonth(<number 0-11>) — sets the month attribute

setSeconds(<number 0-59>) — sets the second attribute (note plural in method name)

setTime(<non-negative number>) — sets the date as the number of milliseconds since midnight, 1 January 1970

setUTCDate(<number 1-31>) — sets in universal time the day attribute, i.e. the day of the month between 1 and 31

setUTCDay(<number 0-6>) — sets in universal time the day of the week, 0 for Sunday, 1 for Monday, ..., 6 for Saturday

setUTCFullYear(<four-digit number>) — sets in universal time the year attribute

setUTCHours(<number 0-23>) — sets in universal time the hour attribute (note plural in method name)

setUTCMilliseconds(<number 0-999) — sets in universal time the millisecond attribute (note plural in method name)

setUTCMinutes(<number 0-59>) — sets in universal time the minute attribute (note plural in method name)

setUTCMonth(<number 0-11>) — sets in universal time the month attribute

setUTCSeconds(<number 0-59>) — sets in universal time the second attribute (note plural in method name)

toGMTString() — returns a string representation of the date using GMT, e.g. in Internet Explorer 5: "Sun, 5 Sep 1999 17:21:48 UTC"

toLocaleString() — returns a string representation of the date using local time zone, e.g. in Internet Explorer 5: "09/05/1999 18:21:48"

toString() — returns a string representation of the date, e.g. in Internet Explorer 5: "Sun Sep 5 18:21:48 UTC+0100 1999"

toUTCString() — returns a string representation of the date using universal time, e.g. in Internet Explorer 5: "Sun, 5 Sep 1999 17:21:48 UTC"

value Of() — returns the date as the number of milliseconds since midnight, 1 January 1970

Activity 6: Changing the window status

When you move the mouse pointer over a hyperlink, the status area in the bottom left of the browser window normally changes to reveal the link's URL. User often use this information to decide whether to follow the link. You could, instead, arrange for the status area to display some marketing information by setting the status property of the window object.

Write a HTML/JavaScript document that includes an ordinary anchor containing an unwelcome URL and a JavaScript script that assigns a more enticing string to the status portion (e.g. Sale: all USB devices at 50% discount).

You can find a discussion of this activity at the end of the unit.

Activity 7: Semicolons to end statements

We have been using the practice of ending JavaScript statements with line breaks. Strictly speaking, a statement is terminated by a semicolon (;). When followed by a new line, the semicolon can be omitted. The following statements take advantage of this rule.

    document.bgColor = "blue"
    document.fgColor = "white"
    document.write("This text should be white on a blue background.")
	  

Rewrite the above statements to use semicolons.

You can find a discussion of this activity at the end of the unit.

Activity 8: including separate JavaScript files

The <SCRIPT> tag may have an optional SRC attribute to specify the URL of a text file containing JavaScript statements that are to follow the tag. Rewrite the sample solution given for Activity 2 using this facility. (Hint: use a file in the same directory as the HTML file.)

Note that by convention an extension of .js is used as a suffix to the name of the JavaScript file, e.g. foreColour.js.

You can find a discussion of this activity at the end of the unit.

Activity 9: Opening a new Window

Check what happens when you open a new window with the following JavaScript. Try to predict what will happen before trying this. In particular, try to predict what object the variable document refer to.

    window.open()
    document.bgColor="blue"
    document.fgColor = "yellow"
    document.write('This is the new document')
	  

You can find a discussion of this activity at the end of the unit.

Now do Review Questions 10 and 11.