MSc-IT Study Material
June 2010 Edition

Computer Science Department, University of Cape Town

Discussions and Answers

Discussion of Exercise 1

It really does not matter what you display just before and just after the welcome greeting. The following HTML and JavaScript is the same as the original but with Start text: before and That was JavaScript. after. Without the document's preamble and closing tags we have:

    Start text:<SCRIPT>
    document.write("<em>Welcome to programming with JavaScript!</em>")
    </SCRIPT>That was JavaScript.
      

This results is:

Can you explain the spacing? That is, can you see why there is no space between the ':' and the 'W', and why there is no space between the '!' and the 'T'?

The answer is that the <SCRIPT> and </SCRIPT> tags do not themselves affect the HTML stream. If they, and what they enclose, had not been there, there would be no space between the ':' and the 'T'. If you were to put the tags on separate lines, then space would have been introduced by the line breaks. Of course, you could have included spaces or other spacing tags in the argument to write — like <BR>.

Discussion of Exercise 2

Instead of using the write method with the greeting as parameter, use the alert method with the greeting as parameter, thus:

    <SCRIPT>
    window.alert("Welcome to programming with JavaScript!")
    </SCRIPT>
      

This would produce a dialogue box similar to the one below.

You can see that the <em> and </em> tags have been omitted. The alert method (of the object window) does not get the browser to interpret its argument as HTML, so the tags would appear as ordinary text in the dialogue box if we had included them.

Note that different versions of JavaScript implement their facilities a little different from each other. As you can see, Microsoft Internet Explorer inserts its name in the title bar of a dialogue box. Other browsers simply insert 'JavaScript' or '[JavaScript]' instead.

Discussion of Exercise 3

Given that the window object is the one that provides for the alert facility, it is reasonable to assume that it will supply the similar facility of prompting the user. Indeed, this is the case: the method prompt is provided. It requires two arguments — a string to prompt the user with an explanation inside the dialogue box, and a second one to act as default input.

Discussion of Exercise 4

Since the variable input still refers to what data the user gave in response to the prompt on email, it can be used in a subsequent script in the same document, thus:

    <SCRIPT>
    window.alert("Email with subject '" + input + "' has been sent.")
    </SCRIPT>
      

There are several points to note about this script. First, is that there is no need to redeclare the variable input; redeclaring it would have had no effect. Second is the use of single quote marks within the double quotes that are used here to delimit strings. In fact, either can be used as delimiters, allowing you to use whatever is not a delimiter inside the string. Third as far as the JavaScript interpreter is concerned, the spaces either side of the concatenation operator (+) are irrelevant; they are there to help the human reader and are ignored by the interpreter.

Activity 1: Checking and Setting Background Colour

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <!-- Copyright (c) 2005 UCT -->
    <HTML>
    <HEAD><TITLE>Welcome message</TITLE>
    <META content="text/html; charset=windows-1252" http-equiv=Content-Type>
    <META content=0 http-equiv=expires>
    <META content="UCT" name=Author>
    <BODY>
    <SCRIPT>
    window.alert("background colour is (in Hex): " + document.bgColor)
    window.alert("changing colour to blue")
    document.bgColor = "blue"
    window.alert("background colour is (in Hex): " + document.bgColor)
    window.alert("changing colour to coral")
    document.bgColor = "FF7F50"
    window.alert("background colour is (in Hex): " + document.bgColor)
    </SCRIPT>
    </BODY>
    </HTML>
      

Activity 2:Setting a document's foreground colour

The following will change background colour and foreground colour as required and write some test text.

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <!-- Copyright (c) 2005 UCT -->
    <HTML>
    <HEAD><TITLE>Foreground colour changes</TITLE>
    <META content="text/html; charset=windows-1252" http-equiv=Content-Type>
    <META content=0 http-equiv=expires>
    <META content="UCT" name=Author>
    <BODY>
    <SCRIPT>
    document.bgColor = "blue"
    document.fgColor = "white"
    document.write("This text should be white on a blue background.")
    </SCRIPT>
    </BODY>
    </HTML>
      

This would produce the following output.

Activity 3: Using user input to set colours

The following JavaScript does what is required. In this version, default colours are included in the prompt. These are not necessary.

    var fore, back
    back = window.prompt("Background colour:","coral")
    document.bgColor = back
    fore = window.prompt("Foreground colour:","blue")
    document.fgColor = fore
    document.write("This text should be "+ fore + " on a " + back + " background.")
      

Note the use of the variables fore and back for the foreground colour and background colour respectively. These are declared in a single var statement (you could have used two). Each is used to remember the data input via the prompt method and is subsequently used for two purposes: first, to set the associated property, and second, to form the sample text that allows you to confirm you have programmed the correct behaviour.

Supplying valid colours (e.g. green and yellow) other than any defaults you supply are sensible test cases. However, you must check what happens with not-so-sensible cases. For example, if you input both colours to be the same, you will not see the sample text. (However, if you use Select All from an appropriate browser menu, you should see the sample text.) If you input nonsense for either colour (e.g. %^RTkz) the variables will be assigned the nonsense value, but the properties will be changed to HEX 000000 which is the colour black.

Something quite different happens if you click Cancel on the prompting dialogue boxes. When Cancel is clicked the prompt method returns the special value null — essentially meaning 'no value'. If null is assigned to either of the colour properties, they are left unchanged (although the variables still have the value null). This behaviour is not easy to determine.

There is a general lesson to be learnt here: the variables you use may be set to something that does not make sense for their subsequent use and the values assigned to properties may not be the values they are given. Test thoroughly! And keep your test cases and notes of results in case you have to change your system.

Activity 4: Dealing with errors

The first thing to look at is what the script is supposed to do. The last statement in which a string is to be written into an HTML stream would suggest that some input (represented by the variable input) is to output underlined (you can recognise the <U> and </U> tags). In fact that is where the first problem is. Internet Explorer produces the following. In fact it does this before it executes the beginning of the script. (From this you can infer that the Microsoft interpreter does some checking of the entire script before interpreting any of it.)

In fact Netscape Navigator does not complain at all but allows the errors in the statement and sorts it out! The browser Opera 3.60 does not complain initially, but only displays the first string: 'You typed: '. Whatever the rights or wrongs of these approaches, the statement is hard to read and causes a problem for at least one browser, so should be corrected. The problem is that the underline tag <U> has not been enclosed in either single or double quotes. Furthermore (and no browser could complain) the input variable is inside the last string, and so is correctly interpreted as the sequence of characters i n p u t. Fixing the last line gives:

    document.write("You typed: <U>" + input + "</U>")

The errors in the last line were syntactic errors — errors to do with the form (syntax) of the script. Other errors are semantic, where you write something which JavaScript cannot make sense of, or logical, where you simply do the wrong thing for the application you are trying to develop.

Working from the top of the script: line 1 declares fore and back, and line 2 assigns the document's background colour to back. However, back is not used in the rest of the script. It could be used in another script in the same document, but it could be declared and initialised to the background colour in such as script. So, let's remove back from the variable declaration and remove the second line:

    var fore

Line 3 is a mess. It has two assignments in it. You might not think so, but this is syntactically OK. What it means is that the rightmost assignment takes place first (document.fgColor = fore) and then its result is assigned to the next variable to the left — to fore. This type of assignment can make sense, but not here, because fore has no value — it is undefined (different to null) — and so its assignment to document.fgColor attempts to make that property undefined. But it stays as it was before. To figure this out you would have needed to insert alert or write method calls before and after the multiple assignment. Not only does line 3 contain a semantic error — an inadvertent JavaScript error — it contains a logical error which is not needed for the script to fulfil its purpose. The logical error is trying to change the foreground colour, whereas it looks like fore is to be used in a subsequent prompt, so it does need to be set to the foreground colour. Hence, we simplify line 3 to be:

    fore = document.fgColor

Line 4 seems straightforward: it appears to be prompting the user for a new foreground colour, using the current foreground colour (in fore) as a default (albeit as HEX, rather than as a user-friendly name). But, newFore has not been declared. In fact, this is legal in JavaScript, but is not helpful to the human reader and so should be included in line 1. The same is true of input subsequently, so let's add it to line 1 as well:

    var fore, newFore, input

Line 5 assigns the object remembered by newFore to the document's foreground colour. However, nonsense could have been input, or Cancel may have been clicked. Either way, newFore may not represent the foreground colour. Either reset newFore to be the background colour prior to the prompt (leaving the latter as it stands). Alternatively used document.bgColor in both lines and remove newFore. Let's do the former and complete the repaired script:

    var fore, newFore, input
    fore = document.fgColor
    newFore = window.prompt("Foreground colour:",fore)
    document.fgColor = newFore
    newFore = document.fgColor
    input = window.prompt("What do you want written out underlined in colour "+newFore+'?')
    document.write("You typed: <U>" + input + "</U>")
      

As you might have realised, there is nothing wrong with enclosing the final question mark in single quotes.

Note how long this activity took. Although the script was simple, a lot of thinking was needed to work out what was wrong with it. Be aware that you may have to spend a lot of time 'debugging' scripts like this.

Activity 5: The confirm method

All you need is to try out the method three times — one for each of the ways in which you can complete interacting wit it: clicking OK, clicking Cancel, and closing its window. For example:

    var confirmation
    confirmation = window.confirm("Click on OK or Cancel or close box")
    document.write("You clicked <B>" + confirmation + "</B>")
      

With Netscape Navigator this produces the following dialogue box:

Clicking OK assigns the value true to the variable confirmation, as verified in the document, below. Clicking on Cancel or closing the window of the dialogue box, returns false. You will use true and false frequently in JavaScript, but nor in this unit!

Activity 6: Changing the window status

Here is the entire body of the document:

    <BODY>
    <A HREF = "http://www.most-expensive-sellers.com" >
    Come to out cheap on-line store
    </A>
    <SCRIPT>
    window.status = 'Sale: all USB devices at 50% discount'
    </SCRIPT>
    </BODY>
      

The following screen shots show the status text when the mouse is not over the URL, and the mouse is of over the URL.

Ideally, if we are to change the status text, we want to vary it as the user moves around the window. We will see how to that when we discuss events in the next unit.

Activity 7: Semicolons to end statements

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

Activity 8: including separate JavaScript files

The HTML file would contain all of the HTML of the earlier version, but with the <SCRIPT> tag changed:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- Copyright (c) 1999 Middlesex University -->
<HTML>
<HEAD><TITLE>Foreground colour changes</TITLE>
<META content="text/html; charset=windows-1252" http-equiv=Content-Type>
<META content=0 http-equiv=expires>
<META content="Global Campus" name=Author>
<BODY>
<SCRIPT SRC="foreColour.js">
</SCRIPT>
</BODY>
</HTML>
      

The file foreColour.js would then contain:

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

One advantage of this style is that if a user was to save the source of a Web document, the included JavaScript file is not saved.

Activity 9: Opening a new Window

The new window if placed in the foreground and old document (with the URL of the file you use) is left in the background. The variable document still refers to the original document, now in the background window, hence that document has a blue background and contains new yellow text, as below.

Answer to Review Question 1

JavaScript allows Web pages to be interactive, i.e. to part of a Web application.

Answer to Review Question 2

In the JavaScript object model, parts of an object's state are called 'properties'. A function that belongs to an object is called a method.

Answer to Review Question 3

When a user, for example, clicks on a hyperlink, the browser requests a document from a Web server. The server delivers it back to the user via his or her browser. The browser replaces the content of the current window with the newly rendered view of the document, that is, with the original document's HTML formatted. If the browser encounters JavaScript code, the instructions contained in the script are acted on by the browser.

Answer to Review Question 4

The JavaScript object window has methods alert. The alert method simply displays a string in a dialogue box and waits for the user to click OK (or close the dialogue box).

Answer to Review Question 5

An argument is a piece of information needed by a method. You supply an argument by enclosing it in parentheses, as in

document.write("<b>Delivery date: </b>")

, in which case the argument is

 "<b>Delivery date: </b>".

Answer to Review Question 6

The following JavaScript code will display the string as required:

window.alert("Form ready for your application. Please proceed.") 

Answer to Review Question 7

A variable is used to remember the result of evaluating some expression, typically to remember the result returned by a method.

A variable declared in one script in a document is available for use in all other scripts in the document.

Answer to Review Question 8

The following script would produce the required prompt.

window.prompt("WWW Guitar Auctions Inc. How much would you like to bid for guitar #2873?","$100")

However, in reality some variables would be set to specific value and then used for in a more general prompt. For example, the company name may be held by a variable, the number of the item being sold may be held by a variable, and the minimum to be bid may be held:

    var company = "WWW Guitar Auctions Inc."
    var itemNo; minimumBid = 1
    itemNo = 2873 //in reality something more complicated would set this
    minimumBid = 100 //and this
    window.prompt(company+ " How much would you like to bid for guitar #"+itemNo+"?","$"+minimumBid)

Answer to Review Question 9

You would use the following:

    theDate = new Date(662989080980) 

Answer to Review Question 10

Because no object name precedes it, this method must belong to the window object, and so could be written window.close().

Answer to Review Question 11

The script resizes the window containing the document of which the script is part. It resizes to a square (hence the variable name squareSize). The script begins by prompting the user for the size of the square and suggests a size of 300.

By the way the 'odd' situations give rise to unpredictable behaviour in the browsers. Clicking Cancel sets squareSize to null and so the browser window may become very small, or remain unchanged — depending on the browser. The same happens with a negative number.