MSc-IT Study Material
June 2010 Edition

Computer Science Department, University of Cape Town

JavaScript within HTML

JavaScript statements are embedded within an HTML document and are interpreted by a Web browser. Unlike programming in Java, a programmer does not programme with JavaScript by preparing source code and compiling it to produce executable code. JavaScript is directly executed by the Web browser. The most general form of JavaScript used in HTML documents is to include JavaScript statements within <SCRIPT> and </SCRIPT> tags. Each JavaScript statement is written on a separate line. If a statement is in some way incorrect, the browser (and its built-in JavaScript interpreter) may report an error, or it may stop executing the erroneous JavaScript and do nothing. Let us examine a simple HTML document that does nothing that could not be done with HTML alone. All that it does is have the document include the italicised text "Welcome to programming with JavaScript!":

Most of the document is normal HTML. There are two new tags — <SCRIPT> to indicate the start of JavaScript code, and </SCRIPT> to indicate its end. The only line of JavaScript is the one containing:

document.write("<em>Welcome to programming with JavaScript!</em>")

Notice that it is just one line. Most JavaScript statements appear on single lines, but this one has to because it contains a string that cannot be broken by an end of line.

Interpreting the above document produces the following:

What this mixture of HTML and JavaScript does is to make the browser switch from interpreting HTML to interpreting JavaScript when it encounters the </SCRIPT> tag. The line is interpreted as follows: first, it calls the write method of the document object with the argument "<em>Welcome to programming with JavaScript!</em>". The argument is a literal string containing valid HTML markup between the start and end emphasis tags (em> and </em>) that cause what they delimit to appear in italics.

Let us examine the individual parts of the expression, as in the diagram below. Note that in this case the argument is a literal string.

As you might guess, all JavaScript does in this statement is to insert the argument text 'into' the document to be interpreted as HTML — hence the emphasis tags produce italics. Of course, the original document delivered by the server is not modified; nothing is actually written into the original document. What happens is that the JavaScript method inserts its argument in the stream of characters that the browser is interpreting. (Usually this will be a stream delivered by a server. You can see this in the browser's address field — in our example the file D:\MyJavaScriptFiles\test.htm was used.)

Now carry out the following exercise and once you have studied its discussion continue with the unit's content.

Exercise 1

Modify the document containing the welcome greeting so that some HTML text is outputted immediately before and immediately after the welcome greeting.

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

Arguments

Arguments are also known as parameters. An argument is information that must be included with a function or method so that it may achieve its purpose. As in Java, some methods and functions are designed to have information supplied to them, so that their effect can differ in detail. If a function or method is designed in this way, it must be supplied with the required arguments when it is called. The document method write has been designed and implemented that way. Another function that needs a string argument is the window method alert, which was briefly shown earlier in these notes. The next exercise makes use of alert.

Exercise 2

Write the JavaScript statements that will show the welcome greeting in an alert box. (Hint: remember alert is a method of windowobjects, not of document objects.)

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

document.write is an example of a function that can take an unspecified number of arguments. It must, however, have at least one. The following example uses more than one argument:

document.write("<BU>", "<LI>books</LI>", "<LI>magazines</LI>", "</BU>")

In JavaScript, as in Java, multiple arguments to a function must be separated by commas and provided in an order determined by the function. There is no simple rule to tell how many arguments a method must have or what their order should be, and this information can only be obtained from the method's definition, or from a good reference document or book.

To Do

Find a JavaScript Reference source that has information about the objects, properties and functions available to a JavaScript programmer.

Now do Review Questions 4, 5 and 6.

Accessing and Changing Property Values

In JavaScript, it is commonplace to directly access or change the value of a property. One such document property is bgColor, which represents the document's background colour. Directly accessing a property is similar to accessing a method: write the object name followed by a period (a dot) and the property name. Thus, to access a document's background colour, write document.bgColor. Note the American English spelling of 'Color', and the use of a capital 'C' inside the word. The spelling and capitalisation must be precise or a browser's JavaScript interpreter will not properly process the script.

Of course, methods can be combined with the ability to access properties. For example, the alert method of window can be used to report the document's background colour:

window.alert(document.bgColor)

This would produce a dialogue box as follows.

The box shows the hexadecimal (HEX) representation of the colour, with #FFFFFF being the HEX for white, a document's default background colour.

The content of the dialogue box can be made more comprehensible by announcing the value with another string explaining the value. One way to do this is with the string concatenation operator, +, which combines what precedes it with what follows it. So, for example, "changing " + "colour" results in the string "changing colour". Note the space at the end of the first string literal appears between the two words in the string resulting from using +. Hence you can concatenate "background colour is (in Hex): " with document.bgColor to produce more helpful output:

window.alert("background colour is (in Hex): " + document.bgColor)

To change a document's background colour, simply assign the new value to the property using the = operator. Do not confuse this symbol with equality. JavaScript belongs to a class of programming languages (just as Java) that use = as the assignment operator: it assigns the value of whatever is to its right to whatever is on its left. Another symbol is used for equality testing, as we discuss later. Hence, to set the background colour of a document to blue (HEX 0000FF), we can use:

document.bgColor = "0000FF"

JavaScript provides a set of mnemonic strings for many colours. For example:

document.bgColor = "blue"

Note that no matter what value was used to set a colour, if you access it as above the output will always be in HEX. (This is because JavaScript automatically converts between different types of data. We will see this a lot in JavaScript programming.)

Activity 1: Checking and Setting Background Colour

Write and test a document containing HTML and JavaScript that displays the background colour of the document, warns you of a change of colour is to take place, then changes it to blue (use the string "blue"). Repeat this for the orange-like colour coral, using its HEX representation "FF7F50" and confirm the change with an alert.

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

Activity 2: Setting a Document's foregrond colour

JavaScript considers the default colour of a document (i.e. the colour of its text) to be the property fgColor. Write a script to set the background colour of a document to blue and the foreground colour to white.

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

Variables

With the exception of alert dialogue boxes, so far we have used JavaScript to do nothing more than what HTML can do. We now proceed to the vital concept of programming with variables via another interactive facility — dialogue boxes that allow the user to enter data.

Exercise 3

An important principle of object-oriented programming is that any facilities provided by an object should be encapsulated within the object. Remembering which object provides the alert method, which object do you think has a method for prompting the user for input in a dialogue box.

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

The prompt method allows you to make a window display a dialogue box containing an explanation prompt and a default value for input.

For example, the statement below explains to the user that their company name cannot be found (let's assume some previous processing has determined this). It provides a suggested default of Cairo, which we assume makes sense for the Web application.

window.prompt("Cannot find your company name. Please input your location:", "Cairo")

Note that the two string arguments, each delimited by their own quotes, are separated using a comma.

The output from a document containing this JavaScript appears as in the following diagrams. Three variations are given below (from Internet Explorer, Navigator and Opera). As you can see, the dialogue boxes differ in their details (e.g. in size and button position), but are in essence the same.

So, what might be done with input obtained this way? In general, we would use it to change the state of some part of the Web application, and such a simple change of state could eventually lead to more complex behaviour. One straightforward use is to modify the HTML stream to include the input obtained by window.prompt. For example, imagine an application that generated an email message whose content is an HTML document. We could ask for the subject and then write it as a level 1 heading (i.e. using <H1> and </H1>):

document.write("<H1>Subject: "+window.prompt("Subject of email:","")+"</H1>")

This rather complicated argument to document.write needs explaining. The complication comes from needing to evaluate the prompt to determine the argument to write as a whole. When this statement is executed, the interpreter tries to concatenate the three strings:

   1. "<H1>Subject: "
   2. window.prompt("Subject of email:","")
   3. "</H1>"
      

String 1 is the first part of the heading; it includes the start tag for the level 1 heading, and the beginning of the heading — 'Subject: '. String 3 is the end tag for the level 1 heading. String 2 cannot be part of the concatenation for the write method unless it is itself evaluated; hence the following dialogue box is produced. Notice how no default for the input is provided, because the second argument is an empty string — a string with zero characters in it.

If the user types in 'Unable to book flight' and clicks OK (or presses the Enter key), then the prompt method delivers that string object as String 2 and the concatenation can be completed, resulting in the heading in the browser below:

An alternative way to programme this type of behaviour is to break it up into smaller pieces and to provide the means to remember the result of evaluating some complex expression, then using that result later in the programme in whatever way is needed. This is what variables are for: they are names that can be used to refer to an object or value for a variety of purposes. They are called variables because they can be used to refer to different objects at different times of the programme's execution. As it happens, in JavaScript a variable can refer to objects of any type, whether they be strings, numbers, or user defined objects. This is very flexible and powerful, but it means that the interpreter cannot help you by restricting the functionality of the variable to a declared purpose, as in some other languages (such as Java). The most general way to use a variable is to declare it with a special key word, var, as in:

    var input

Once a variable has been declared it can be made to refer to an object with the assignment operator, =, introduced earlier. Now the email subject prompter can be reprogrammed as follows (below, we choose the obvious variable name — input — which has nothing to do with the HTML tag or the JavaScript object):

    <SCRIPT>
    var input
    input = window.prompt("Subject of email:","")
    document.write("<H1>Subject: " + input + "</H1>")
    </SCRIPT>
      

Executing this script has the same effect as the earlier version that included the prompt as an argument to write. A user cannot tell the difference.

Exercise 4

Write another script to be included in the same document as the previous one so that the new script produces a confirmation that the email with the given subject has been sent, as in the following dialogue box.

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

JavaScript Comments

In the same way that HTML provides the means to prevent an HTML interpreter (a browser) from acting on text in a document, JavaScript also provides the means to turn its statements into comments that the JavaScript interpreter ignores. Because of its C++, C and Java heritage, JavaScript accepts comment syntax from all of these languages: anything between /* and */ is ignored, as is everything on a line following //. The former brackets a comment, which can be over several lines or within a statement. The latter is typically used when the end of a line contains a comment. For example, the above script can be commented as follows:

    *lt;SCRIPT>
    var input // this variable will be used in a later script
    input = window.prompt("Subject of email:","")
    /* We have to generate HTML according to
    company style guidelines found in
    Document 1998-EM-GD-V3.1, hence what follows. */
    document.write("<H1>Subject: " + input + "</H1>")
    </SCRIPT>
      

JavaScript is used within HTML and it is possible that older browsers are unable to run JavaScript, or that a user has disabled the JavaScript functionality of a recent browser. Therefore JavaScript also understands the opening HTML comment, but not the closing comment. This allows JavaScript code to use a mixture of HTML comments to allow the JavaScript to be ignored by browsers that cannot run JavaScript and would format it as HTML text.

The previous example could be changed so that it works in a JavaScript-enabled Web browser but has no effect on the output of a Web browser that cannot handle JavaScript. The line immediately after the <SCRIPT> tag is the start of an HTML comment, which is ignored by both language interpreters. The line before the </SCRIPT> tag is ignored by a JavaScript interpreter, but if there was none, the HTML interpreter would have been ignoring everything up to the closing HTML comment bracket.

<SCRIPT>
<!---the JavaScript can be ignored
var input // this variable will be used in a later script
input = window.prompt("Subject of email:","")
/* We have to generate HTML according to
company style guidelines found in
Document 1998-EM-GD-V3.1, hence what follows. */
document.write("<H1>Subject: " + input + "</H1>")
//--->
</SCRIPT>
      

Acivity 3: using user input to set colours

Write and test an HTML/JavaScript document to prompt the user for background colour and foreground colour and then output sample text. You should use appropriately named variables and maybe reuse them when generating the sample text. When testing, make sure you have a variety of inputs — valid and invalid colours, and cancelled inputs. Note down what happens in each case.

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

Acivity 4: dealing with errors

The following is bad JavaScript. Type (or copy) it into a suitable HTML document to explore what goes wrong when you try to interpret this in a browser. Correct each problem statement as you see necessary and write down what you did and why. (Hint: look at the use of the write method from which you can infer what the script is to do.) Also identify anything that seems unnecessary and anything you think is wrong at first sight but which might turn out to be correct. Note that different browsers (different JavaScript interpreters) will report different problems. If you have access to more than one browser you may like to see which provides most help.

Note that you are not expected to understand all the problems in the script below. What you are expected to understand is that you can 'instrument' the code with suitable write methods or alert methods (like the ones you have already used) to help you reason about what is happening (or not happening). So be prepared to temporarily add statements to the code so you can trace how it is being interpreted. And be prepared to spend quite a bit of time exploring the code.

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

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

Activity 5: The confirm method

As well as the alert and prompt methods, the window object provides a confirm method that produces a dialogue box with the buttons OK and Cancel. Like alert, it takes a string argument that is displayed in the dialogue box. Explore this method by writing HTML/JavaScript documents that use it.

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

Now do Review Questions 7, 8 and 9.