You are on page 1of 20

JavaScript Notes

1. Basic JavaScript - Defining and invoking JavaScript functions


2. JavaScript - Objects – images – rollovers - and arrays
3. JS Objects - Window – document objects, innerHTML

1. Basic JavaScript

We have already introduced the notion of inline JavaScripts triggered when a mouse
event occurs in an HTML element. Events can also trigger execution of user-defined
JavaScript functions defined in scriptlets located in the head element of an HTML file or an
external JavaScript source file. The following examples illustrate the basic ideas.
ExampleSp04Form01a.html shows how a generic HTML button element can trigger
execution of a built-in function (alert) when clicked. The second example
(exampleSp04Form 01a1.html) illustrates a user-defined JavaScript function invoked when a
submit button is clicked. The examples can be found under the link JavaScript >
JavaScript Examples > JavaScript-Basic on the web site.

Example 1: Event-driven function invocation, condition=action pairs, built-in JavaScript


functions, alert.

ExampleSp04Form01a.html is like example06a.html discussed in the HTML-class-


notes except it contains a generic button element in place of a submit button. While a submit
button triggers query data transmission to a server, a generic button, like the "click-me"
button here, conditionally triggers the action identified in its condition/action pair. In this
case, the trigger condition is the onclick event caused when the button is clicked. At that
event, a built-in JavaScript function alert("…") pops-up a window containing the message
passed as an argument by the alert and the browser then waits (or blocks) until the user clicks
the OK button in the pop-up window. This can be done repeatedly. The HTML tag for the
button is:

<input type = button name = "myButton"


value = "click-me" onclick = "alert('Stop That!')" />

The format for a condition=action pair is mouseEvent="functionName (argument) ; ..." with


multiple function calls separated by semi-colons which is the same format as used for the
inline mouse events examined previously. However, this is not the same syntax as used for
condition=action pairs in <script> tags, as illustrated in the following example. Observe no
query string data is triggered in the case of this button click unlike the case of a submit
button.

Example 2: JavaScript function definition, script tag, pseudo-code, qualified naming


conventions, value and other attributes, if statement, equality operator, isNaN
function, return statement, query data transmission, tracing, case-sensitive,
error debugging in browser.
ExampleSp04Form01a1.html) demonstrates a user-defined function defined in a
<script> tag in the <head> element of an HTML page with an associated invocation
condition specified in a <script> element in the body of the page. Thus, there is a:

a. Function definition - in script in HTML head


b. Function invocation and condition - in script in HTML body

Conditions & Actions: The body scriptlet that specifies when the function is invoked is:

<script> document.guestForm.onsubmit = checkIt </script>

with a condition=action expression enclosed in the element. The function is identified by


name only with no arguments or parentheses. The expression has the form condition=action
where the condition identifies the event (document.guestForm.onsubmit) that triggers the
function and the action identifies the function by name (checkIt). Here, the condition is that
the submit button is clicked. The triggering condition (button) is identified by a qualified
name. Qualified names identify objects on HTML pages using a hierarchical style of naming
convention typical in object-oriented languages. The qualified name is obtained by
successively concatenating the name or identifier of the outermost HTML element containing
the object – in this case the HTML document, and continuing to the nearest HTML element
containing the object. In this instance, the hierarchically qualified name derives from: the
HTML page itself (document), the name of the form containing the submit button
(guestForm), and finally the event that triggers the function - in this case the onsubmit
condition that occurs when the submit button is clicked. Notice that in this case, the button's
name mySubmit is not to be used, else an error occurs as illustrated in the Javascript
debugging example below. The above syntax differs from that used for the inline
condition=action pairs encountered previously, where we used:

<input …attribute/value pairs… onclick = "alert('Stop That!')" />

We can use that syntax here too, namely:

<input …attribute/value pairs… onsubmit ="checkIt ( )" />

Function Definition: The definition of the function (checkIt) referred to in the


condition=action pair is given in the head element of the page. The format for a function
definition is:

<script language="JavaScript"> function checkIt (list-of-arguments) {…} </script>

Remember this is a function definition or blueprint, but the function defined here is not
executed here. Indeed, it may never be executed at all if none of its triggering conditions
arise.
Pseudo-code Solution: The pseudo-code specification for the function is:

<script language = "JavaScript">


function checkIt ( )
{
1. Test and announce if name field is empty.
2. Test and announce if age is valid number.
}
</script>

JavaScript Instructions: The implementation uses the following JavaScript syntax.

1. An if statement - if (condition) {…} - that tests if the Name field is empty. The
first if-condition is a boolean equality condition (==) that tests whether the
name field value is empty – indicated by "" corresponding to a null string.
2. The JavaScript built-in function isNaN (n) returns true if n is not a valid
number. It returns true if the field is null or a valid number.
3. A return statement (return false) which aborts the submit button's transmission
of query data to the server if false.
4. The JavaScript built-in function alert (s) which pops-up an OK window with
the string s displayed in the window.
5. The input field values accessed are captured using the qualified naming
convention - document.guestForm.nameField.value – where the final .value
attribute returns the value of the data entered in the named field.

Attribute values: You can retrieve other attribute values for a field using statements like:

alert ( document.guestForm.nameField.value )
alert ( document.guestForm.nameField.name )
alert ( document.guestForm.nameField.size )

These references announce the data value entered, the field's name, and its size, and
in general the value of any attribute named by the final .attributeName qualifier. This type of
information is useful in tracing the behavior of a script you are developing which can greatly
help in debugging. Even if attributes like size are not explicitly mentioned in an HTML tag,
its default value can be accessed. To obtain the length of an attribute, append the .length
property as in document.guestForm.nameField.name.length. A statement like:

alert (document.guestForm.mySubmit.value)

gets the value ("Send") of the "mySubmit" button. Observe that JavaScript is case-sensitive
even though HTML is not, so the button must be referred to as "mySubmit" with a capital 'S'
else the referred to object (the submit button) will not be recognized and instead an error
message indicating a null object will occur, if browser debugging is turned on.
Browser Assisted Debugging: The browser has options that allow it to be used to
detect and announce JavaScript errors. In Internet Explorer, go to Tools>Internet Options >
Advanced and look for the options about JavaScript error debugging and notification. The
default choices are to ignore such errors. In our case, we can reverse these choices as shown
in the snapshot – see Disable script debugging and Display a notification about script errors.

With these options selected, temporarily modify the examples so the script reads:

<script> document.guestForm.mysubmit.onsubmit = checkIt; </script>

where the name of the submit button has now been included. When this is dropped in the
browser, the following diagnostics window pops up.

The message indicates an error on the line (line 31) where the change was made.
Example 3: Synchronous (onLoad) versus Asynchronous (on event) JavaScripts,
JavaScript statement, embedded HTML in write's, document.lastModified,
JavaScript Date ( ), <meta> tag with refresh, access to variable properties
(type, name, value, length), Boolean operators, parameter passing,
asynchronous write's, JavaScript source files.

HTML document methods and properties:

Inline scriptlets are executed as the HTML page is loaded, as in example2.html. The
scriptlet (enclosed in <script> tags) can use any JavaScript statements. If a function is used,
the function is executed at that position in the display of the page where the scriptlet occurs
and its result is displayed there by the browser, although the original JavaScript statements
(as opposed to the results of their execution) will still appear in the source. The first alert
statement in the example stalls the display in midstream, until the OK is clicked, at which
point the JavaScript write statement (which is a method of the HTML document object) is
executed and its output is placed at this point in the display. The write statement contains a
string argument which can include HTML tags which are rendered just as if they were in the
HTML page, like the <font> tag in the example. The scriptlets can of course also include
built-in JavaScript functions or references to environmental values like the
document.lastModified here (which is a property of the HTML document object) which
returns the date/time the HTML file was last modified. The next write generates HTML
which returns the current date/time on the client using the new Date ( ) construct following
the usual Java object-oriented notation for objects. (In this case, the "constructor" for the
object is Date ( ) and the expression new Date ( ) returns a string representing the current date
and time.) The write statement also includes some HTML tags. The variation shown in
example2a.html uses a <meta> tag to refresh the page every 5 seconds, naturally with the
updated time given by Date ( ) at that point. The example3.html illustrates a simple
JavaScript syntax error (an unterminated string constant) which is detected by the browser.

Function execution: Example50a1.html illustrates the difference between


asynchronous and synchronous execution of JavaScript functions. There are a number of
points worth observing as the HTML page is progressively displayed:

1. The script in the head is loaded first since it is at the top of the HTML page. This
script contains both a function definition (for hithere) and an actual invocation of an
alert function (alert ("Hello")). The function definition does not trigger execution of
the function. However, the alert ("Hello") is executed. The execution of this alert is
synchronous – that is it occurs at a predefined point independently of any triggering
event.

2. The form contents are displayed next, but the hithere ("Goodbye") function associated
with the onclick condition for the "Press" button is only put on record. The call is not
executed until the onclick event occurs – triggering an asynchronous invocation of
hithere ("Goodbye") if and when (ever) that occurs.
3. The next scriptlet in the body synchronously calls hithere ("hello again"). This pops
up an alert window which delays the further display of the HTML page until that pop-
up is responded to by the user.

4. After the pop-up is unblocked, the JavaScript write statement in the same scriptlet is
synchronously executed.

5. At this point, this HTML page is completely displayed. This is now the first time at
which the "Press" button can be clicked since the page had not yet been completely
produced up until this point, and even though the "Press" button was already visible.
If the "Press" button is now clicked, the hithere function is again invoked, this time
asynchronously triggered and pops-up "Goodbye".

Example50a2.html is similar but uses a scriptlet with an onclick condition in a


qualified name reference: document.test.pressButton.onclick = hithere, as opposed to having
the condition in the HTML element, and with the notation: onclick = "hithere ('Goodbye')".
Example50a3.html illustrates qualified name references again, the length property, element
type and Boolean operators.

Completed HTML page: The example docWriteHead.html illustrates what happens if


you use a write in an asynchronously executed function – which automatically means that the
page has already been produced/completed, or else a triggering event could not have invoked
the function. The write executed at that point overwrites the existing HTML page. To see
the effect, load docWriteHead.html and check its source file once it's completed. Then click
the "Press" button: a new page appears, with the same URL, containing only the last executed
write statement. If you check its source in the browser, you will observe that it too has been
changed though the original file is unaffected.

Function Parameters: Example50a6.html illustrates parameter passing in the function


seeField (X). The parameter passed is the name (first) of the input text field – whose
properties are then accessed in seeField. Note there are no quotes around the name else the
required input field object is not passed. The function then accesses the type, name, value,
and data length of the passed field.

External JavaScript (.js) Source Files: Example50a7.html behaves identically to


Example50a6.html but illustrates the use of a JavaScript source file as an alternative to
including a function definition in the head element. The syntax to refer to the source is:

<script type="text/javascript" src = "see.js" > </script>

The effect is the same as if the actual source were included in the head. Naturally, the src
attribute is inside the tag. Notice that the syntax is different than that when JavaScript
function definitions and statements were included in the head:

<script language="JavaScript">

The external JavaScript source code has an extension .js and contains just the function
definitions, etc. It does not contain any html or script tags. If you want to use both external
source JavaScript files as well as functions defined in the head of the HTML file, you should
include both scriptlets in the head element:

<script type="text/javascript" src = "see.js" > </script>


<script language="JavaScript"> functions & definitions </script>

Example 4: conversion, parseInt, parseFloat, qualified stores, readonly protection, explicit


variable declaration, NaN results, onchange event, focus & select functions.

These examples can be found under the link JavaScript > JavaScript Examples >
JavaScript-II on the web site.

ExampleJSII01.html illustrates a number of familiar points in the context of a slightly


more complicated application: user-defined functions, onclick mouse events to trigger
function execution, and qualified access to HTML element values. New ideas illustrated
include: JS user-defined functions that call other JS user-defined functions, conversion of
user inputs from strings to integer numbers (or decimal numbers), protecting fields using the
readonly attribute, and explicit variable declarations.
The example add, subtracts, multiples or divides the numbers in the 1st two fields and
stores the result in the 3rd field. It accepts signed integer input and yields integers, except
possibly in the case of division where the result may be a decimal number. Bad input (non-
integers) causes a NaN (Not a Number) response in the result field. The result field is
readonly, which prevents the user from entering data into the field, though the results can be
stored there by the JavaScript program. The numbers are generally expected to be integers.
Decimal numbers are rounded - except in the case of division where decimal input is
accepted. To get a true decimal-calculator you would have to replace the parseInt (x)
functions in the getData ( ) function with parseFloat (x).
If the parseInt functions are omitted - so that the numbers are not converted to
integers internally - the inputs are handled as strings, although the results appear to be
somewhat unpredictable. The "+" operator applied to strings concatenates the operands. The
other operators should return the NaN result, but in this example return correct outputs as
well. Thus, oddly, the other operators first give NaN if they are applied before the "+" is
triggered. However, after the "+" is triggered for a particular input, the other operators then
correctly calculate products, etc. I am not sure why.
Each calculator button triggers a button-specific function call (to add ( ), etc). Each
of these functions then collects its own data from the input fields using the getData function
which accesses the values using the usual qualified names for the fields (such as
document.myForm.num1.value). The getData function converts the inputs to integers and
places them in the globally declared variables a and b. See below for the rules on scope of
variables. The function (such as add ( )) then calculates the result and stores it in the
readonly field result (via document.myForm.result.value = a + b)).

JavaScript Variables – Type and Scope: JavaScript variables can be numbers, Booleans,
strings, or null. Their type is dynamically determined by the interpreter from the context.
Variables can be either implicitly declared - by being used without being previously declared
in a var declaration statement – or explicitly declared in a var statement. The scope of a
variable means the statements in an HTML document where the variable's name and value
are accessible. The scope rules are simple:

Variables Declared inside a function [var x]- Local to function


Variables Declared outside a function [var x] - Global to entire page

Undeclared Variables - Global to entire page

For example, modify the declaration in ExampleJSII01.html to var a = 123 and include the
scriptlet: <script language="JavaScript"> alert (a) </script> in the HTML body. Then, when
the page is loaded, the variable a will be initialized to 123 and when the body is loaded, the
alert(a) will correctly pop-up 123 - because a is a global variable, that is accessible to any
JavaScript statement in the HTML page.

The values of global variables can be set in the script in the head of the HTML page.
You can also reset such a value in an inline scriptlet in an HTML tag. For example, consider
the button below which sets the value of the global variable flag declared elsewhere:

<input type="button" value="Set Flag"


onclick="javascript: flag = parsetInt(document.getElementById(1).value)" />

<input type="text" id = 1 />

which uses the getElementById method (discussed later) to get the value entered in the field
with id=1.

Example 5: onchange, focus and select methods, loosing focus

ExampleJSII02.html has minor variations on the previous example. The onchange


condition (document.myForm.num2.onchange=getData) in both input fields triggers a
function execution when it satisfies both that its value is changed and it looses focus. The
functions focus ( ) and select ( ) are cognitively useful for directing the user's attention.
The onchange event can be applied to text input fields, textareas, or menus. The
corresponding element can loose focus by the user left-clicking the mouse elsewhere, or by
other tabbing (which moves the focus to the next field). In the example, the getData function
is called on an onchange event. To clearly appreciate the behavior of the onchange event,
add a few alert's to trace the values of a and b (alert (a) ; alert (b) ) at the end of the getData
function after it has picked up the contents of its fields. The alert's are useful in tracing the
behavior of the getData function. Also test what happens when the entered data is not
changed. In that case, there is no onchange event since the data and focus must both change.
Blur the focus both with clicks and tabs and use different numbers so you can tell which field
data you are looking at.
Focus ( ) acts as a method of the field (document.myForm.num1.focus ( ) ) and
automatically directs Keyboard input to the field. You can see this by just typing without
clicking in the focused field. Observe that the input characters are entered in the focused
field – actually whether it is selected or not. The method select ( )
(document.myForm.num1.select ( ) ) highlights the selected field as well as focusing in it.
Summary of JavaScript (so far) Table-I: The following table summarizes the basic
JavaScript features introduced so far.

JS Syntax Remarks
<script <script language="JavaScript"> Function definitions </script> Head - for functions.
<script type="text/javascript" src = "see.js" > </script> Head -import javascript
(src has no script tags )

Condition=action pairs:
<input type=button name="plus" value="press" onclick = "Add( )" /> In HTML element

<script> document.mine.plus.onclick = Add </script> In Scriptlet in body


<script> document.mine.B.onchange = Add </script> onchange in field B
<script> document.mine.onsubmit = Add </script> onsubmit omits name

JavaScript functions, methods, properties:


alert ("message") pop up
isNaN(x) True if x not number
parseInt(x) Convert to integer
parseFloat(x) Convert to decimal
document.mine.num1.focus( ) KB focus to field
document.mine.num1.select( ) Highlight field
document.mine.num1.value.length Properties of object
document.mine.num1.name

JavaScript statements
function doSomeStuff ( arg1, arg2) { body of function } Function syntax
if (document.mine.nameField.value) == "" ) { ... }
return false Returns from function.
Blocks submit query.
F += s Adds or pastes s to F

Boolean and arithmetic operators:


== equality
!= inequality
&& and
|| or
"" Empty string
m% n Remainder on division
by n

Attribute Properties Syntax in HTML & JavaScript


HTML style = "font-size:15" Notice spelling.
JS style.fontSize = "15pt" Notice spelling & units

Scope Local variables are declared using var x inside a function. All other variables are global.
Debug Internet Explorer: Tools > options > advanced > script choices turn debugger on.
Netscape: Tools > web-development > JavaScript console.
2. More JavaScript: objects – images – rollovers - and arrays

This section illustrates some more advanced JavaScript capabilities. HTML elements
are objects with their properties and methods accessed using the usual object-oriented dotted
notation. The objects in an HTML document are organized in a tree-like hierarchy known as
the Document Object Model (DOM). JavaScript provides an API (Application Program
Interface) that can access and modify the elements in this model. We illustrate a few image
rollover effects based on mouse events. Then we consider how JavaScript arrays work and in
particular how 2-dimensional arrays can be constructed since they are not immediately
declarable.

Objects:

Refer to JavaScript > JavaScript Examples > JavaScript-DOM

The combination of HTML element id's and the use of the Document Object Model
ability to reference the nodes in an HTML page provides a generic way to identify and
modify HTML elements.

Example 1: this notation, object-oriented notation for attributes, DOM, nodes, node's data,
firstChild of a node

We begin (WorkingExample00a.html) by illustrating a uniform way to refer to the


current HTML element using with JavaScript's this notation. The example has a two cell
table with text in each cell. Each cell responds to an onclick event using the identical
function call:
onclick = f1(this).

The notation this is an important, standard object-oriented way to refer to the current object
or HTML element. In this case, the current object would be whatever table cell <td> the
condition arises or occurs in. The function f1 has the format is:

function f1( obj ) { }.

f1 uses its argument obj (which in our case is always called as this) to identify attribute
values of the cell where the event occurred using the dotted notation characteristic of objects:

obj.id - read as: obj's id


obj.name - read as: obj's name
obj.height - read as: obj's height

the id of the cell – which could be either cell 1 or cell 2. Even though the function call is
identical in each cell and the same function statements are executed, the results will differ
depending on which cell is clicked.

What is interesting at this point is that we can now uniformly work with a whole
collection of elements and let the function called distinguish which element it is dealing with.
For example, consider WorkingExample00b.html where the function changes the attributes of
whichever cell caused the event.

Accessing the contents of a cell is more subtle and requires using DOM (Document
Object Model) notation for the cell's data. The text for the cell is considered as constituting a
child "node" of the <td> cell "node". WorkingExample00c.html shows how to access it via:

obj.firstChild.data - read as: obj's first child's data

The firstChild and data references will be discussed later when we look at the DOM further.

Nodes can also be accessed using a combination of an id attribute in an HTML


element and the getElementById method of the document object. The example
WorkingExample00c1.html illustrates how the attributes of the elements with id's (id=1, id=2,
id=3) can have their properties accessed. The following access attributes of the table (id=3)
an a cell (id=1). One of the alerts in the example returns an 'undefined', but the following
alerts return the expected values.

document.getElementById(1).height

document.getElementById(3).border

Example 2: rollovers, src attribute, name attribute, events on other objects

Refer to JavaScript > JavaScript Examples > JavaScript-II for the examples.
RoLLOver-1.html illustrates an image used as a hyperlink and combined with mouseover and
mouseout effects that alter the src for the image. The hyperlink descriptor is the us.gif image.
The hyperlink responds to an onmouseover event on the <img tag which is referred to by its
name. The condition=action pair is:

onmouseover ="document.imageName.src='earthris.gif' "

The <img tag has to have a name attribute in order for the condition to refer to it. Test the
example to see its behavior. The src attribute of the image element essentially identifies the
URL for the image.

Arrays

Example 3: readonly or constant one-dimensional arrays, initializing in list, length


property, scanning via for-loop, dynamic arrays, element access, declaring
two-dimensional arrays, initializing 2D arrays, access notation, ++ notation, ||
operator

We briefly consider how JavaScript handles arrays. Refer to JavaScript >


JavaScript Examples > JavaScript-II for the examples. One-dimensional arrays readonly
arrays are declared and initialized as in:
var A = ["s1", "s2", "s3" , "s4" ]

where the array A acts like a constant. The array elements can be accessed using a standard
notation: A[i] to refer to the ith element of the array. The array is indexed starting at 0 (not at
1). The length of the array is given by A.length.

Arrays defined with the list notation above are static or fixed – their values cannot be
changed. Dynamic arrays B are declared using the notation:

var B = new Array ( ).

The length of this array is dynamic. If an element is added beyond the current end of the
array, the array just expands to allow it. We could initialize B by, for example, copying
another array into it using the usual for-loop construct:

for (i = 0; i <A.length; i++) B[i] = A[i]

This copies the static array A into the dynamic array B.

Image Arrays

An interesting example of a built-in one-dimensional array which is automatically


generated by the browser is the document.images array - an array of Image objects associated
with the <img tags in the source document. For example, the images array for array01.html
contains six elements, corresponding to the six <img tags appearing in the document. The
last <img tag has a null src value but still has an entry in the images array. The example
allows the user to select which image to display in the missing image position. While this
array is implicitly defined by the browser, the mode of access is standard:

document.images[i].

The src attribute for an image contains the URL for the image. The src attribute must
be included (document.images[i].src) to redirect the source of the initially null image in the
example. Here, the replacement <img tag is identified by its id=1 attribute and is accessed
with the document.getElementById (1) method. The elements of the array can be
sequentially accessed using a for loop as in:

for (i = 0; i <document.images.length; i++) alert (document.images[i].src)

The loop runs from the starting index at 0 and scans the whole array.

The document.images array can be accessed in two ways. One can use either an
index on 0 to 5 in this example. Alternatively, one could use a name attribute supplied via
the image tags. Thus, in array02.html the images can be accessed using document.images[i]
with i on 0 to 5 - or by using the image names "B" to "E". The name "A" has been
intentionally omitted so reference to document.images[i] with i = "A" will cause an error.
Two-dimensional Arrays

Two dimensional arrays are not explicitly available in JavaScript, but they can be
constructed out of arrays of one-dimensional arrays – which is really what a 2D array is
anyway. For example, the declaration to create a 3x4 array A is as follows:

1. var A = new Array (3)

2. for (i = 0; i <3; i++) A[i] = new Array (4)

Refer to the example 2dArrays.html. Statement 1 makes A an array with 3 cells. Statement 2
then makes each cell an array of 4 cells – which act like a row of 4 cells (indexed from 0 to
3). In effect, however, we get the a 2D array. It's like thinking of a matrix as a set of rows
where each row is itself an array. The notation "new Array (n)" creates an array object with n
rows – indexed from 0 to n-1.) Once the array has been declared we can initialize its
elements with a pair of nested loops such as:

for (i = 0; i <3; i++) { for (j=0; j <3; j++) A[i][j] = 0 }

Alternatively, you can declare and initialize an array using the following kind of notation
which visibly displays the nested sub-arrays:

var A = [ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ]

To access the 2D array elements we use the notation:

A [i][j] .

You can scan 2D-arrays using double-indexed for-loops like:

for (i=0, k = 0; i <3; i++ , k++) { alert (A[i][k] ) }


or
for (i=0, k = 2; i <3; i++ , k--) { alert (A[i][k] ) }

The first loop simply indices both i and k in tandem, thus running through the main diagonal
of the array. The second loop increments i while decrementing k, thus running through the
reverse diagonal of cells that start on the top right, rather than from the top left of the array.

Math Functions and Timers

Example 3: random numbers, Math.floor, Math.round

Random number generators are handy for automatically generating unpredictable


sequences of numbers. Refer to JavaScript > JavaScript Examples > JavaScript-II for
exampleJSII07a.html where the picture displayed is randomly selected from a list. A one-
dimensional array of images myImages is initialized in the head script:
myImages = [ "ca.gif" , "us.gif" , "earthris.gif" , "logo.gif" ]

A function pickImage () then selects an image from the list by randomly generating an index
into the array and redirecting the src attribute for an <img tag in the document. The <img tag
is identified by its id= "myPicture". The getElementById method is then used to alter the src
just like in a rollover.:

document.getElementById ("myPicture").src = myImages[i]

The function pickImage( ) is automatically called onload and is also triggered if the
pickPicture button is clicked. The random selection of the index i into the array is done by:

i = Math.round (( 4 * Math.random ( ) + .5)) - 1

This generates a random integer from 0 to 3. First, the Math function random ( ) generates a
random decimal number form 0 to 1. Then, the factor 4 scales this to lie between 0 and 4.
The +.5 pushes it between .5 and 4.5. The Math round function then changes the result into
the nearest integer from 1 to 5. (For numbers on .5 to 1.5, the rounded result is 1; etc). The
-1 moves the result to between 0 and 4 as required by the image array whose indices run from
0 to 3. Using n instead of "4" returns a result from 0 to n. Summarizing:

1. random ( ) returns random decimal on 0..1


2. Math.round ( (n * Math.random ( ) + .5)) returns random integer on 1...n
3. Math.round ((n * Math.random ( ) + .5)) - 1 returns random integer 0...n-1

The Math.floor function is also useful:

1. Math.floor(n) returns integer part of n.


2. Math.floor(n/10) returns 10's digit of n - if n is 2-digit number
3. n – 10* Math.floor(n/10) returns units digit of n - if n is 2-digit number

Timers

The function:
setTimeout("f1( )", m)

calls the function f1 after m milliseconds. It does NOT block program execution or
otherwise affect browser behavior. All it does is schedule f1 to be executed in m
milliseconds. For example, if the code were:

setTimeout("f1( )", m)
stmt1

then stmt1 would be executed before f1 was executed because the timeout does not block the
progression of the JavaScript code. Be careful if there are nested quotations – for example if
f1 is just alert ( "hello"). It is probably better to define any such string arguments to f1 as a
variable first (say x) and then use the x in the function call (say setTimeout("f1(x )", m) ).

A related method is the setInterval function illustrated in timer00.html. The effect of


the statement;

setInterval ("F2( )", 1500)

is to call the function F2 every 1500 milliseconds. Thus, in contrast to setTimer, the effect is
repeated, not just done once. To stop the repeated calls initiated by setInterval, we have to
use the clearInterval method. First, capture the result of the setInterval call with:

shutdown = setInterval ( "F2( )" , 1500)

Then stop the calls with:

clearInterval (shutdown).

as in timer01.html where the user variable shutdown is global to all the functions.

The proper use of these time-dependent functions can be subtle. The example
testSetInterval.html in C:\myjspapp\chapter01 illustrates the use of the methods. The
function f2( ) in the example initiates the periodic calls to the function f3( ). f3 monitors the
condition under which the periodic calls should be terminated and calls the method
clearInterval(shutdown) to stop the calls when the condition is satisfied. In other cases, f2
performs a timed counting computation. The example newexp11d.jsp (which is a JSP file)
illustrates the application of the periodically called f3 to call a 3rd function f1 when the
shutdown occurs.

3. Document and Window objects - properties and methods

This section illustrates some uses of the document and window objects.
Refer to JavaScript > JavaScript Examples > JavaScript-DOM docWrite00.html, etc.

Notes
1. IE browser (version 6.0) does not support all of these methods. In particular, the
named open for the window object and its sizing & placement options are ignored in IE
version 6, however, Netscape does support them.
2. If you trace behavior by stalling effects using alert, note that Netscape requires
alert("some string") as opposed to just alert( ) – or error occurs. If you do not have browser
error testing turned on, the expected effects may appear to just not be handled. To turn on
error detection in Netscape, use Tools > Web development > JavaScript console.

Window object

The example doc.Write03.html illustrates the window objects open method which
opens a file in a new window. One format is:
window.open(URL, "A")

where the first argument identifies the file to open in the new browser window and the
second argument names the window. The example doc.Write04.html illustrates the use of a
named window.

1. The first open [window.open (x, "A") ] creates the named window "A". If you
enter us.gif in the input field (without quotes), the new window contains the US
flag in a separate window. Move window "A" to another place on the screen
before OK'ing the alert( ).

2. The second open [window.open("logo.gif", "A")] opens the logo.gif file in the
same window "A" named in the first open. Notice the "A" window opens in its
current position.

3. The third open [window.open("ca.gif", "") ] opens the ca.gif file in a separate
window because no name has been assigned.

The example doc.Write05.html illustrates the window object's history object. This
object has methods that let you move back to previous windows in the browser history. For
example, history's go method [window.history.go(x)] moves back |x| windows in the browser
where x is a negative integer (not a string or a positive integer). Try it after several windows
have been loaded in sequence, then enter a number (like 3) to move the window 3 windows
back in its history – which you can then verify has happened by using the browser "forward"
arrow to move 3 windows forward to get back to the original window. Notice that the
statement x = -x in this example also converts x to an integer (from a string), though parsetInt
could be used directly.

The window.location object returns the current URL of the window – see
doc.Write06.html. The example doc.Write07.html illustrates another format for the open
method:
window.open(URL, "" , "options")

where options can include properties like the windows dimensions and position. For
example, the options:

"innerwidth= 300, outerwidth =200, screenX=10, screenY=10"

set the window dimensions and position on the screen respectively.

Notice: IE browser (version 6.0) does not support these sizing & placement options and just
ignores them, but Netscape does.

The reference:

window.open(url string, '', ' width=200, height=200, resizable=0 ')


opens the referenced url in a 200x200 window; the resizable=0 choice is used here to ensure
the window does not get resized. Observe the single quotes because this was used inside a
double-quoted string. It did work properly in IE. Other useful options include: toolbar=1
(or 0 - to control toolbar inclusion/exclusion), scrollbars = 1 (or 0), statusbar = 1 (or 0).

Document object

The document object's write method can be used to write content to the HTML page.
However, this has limited applications. In particular, the document.write method should
generally not be used in an event-driven function call because it will just overwrite the
existing html page.

However, the write method can be useful when executed synchronously as the page is
loaded. The doc.Write00.html example illustrates its use to construct the tags for a large
array. The first statement just writes out the opening tags for the table and the final statement
closes the table out. The nested loops construct the rows and cells. The i-loop makes the
opening and closing row tags, while the k-loop nested inside it makes the cells for each row.
Here the table has 10 rows with 10 cells each. Each row is given attributes as well. The id
attribute depends on the i & k. The example doc.Write01.html posts the generated id values
for a small-scale version. The example doc.Write02.html shows the effect of an
asynchronous write – the html source is effectively over-written when the button is clicked.
The file itself is not actually changed, but the source page view shows only the over-written
file with just the "Goodbye" text.

The HTML of a document can be changed in place using an objects innerHTML


property. The example docWrite09.html illustrates how HTML entered in a text area can be
placed live in a division (<div> tag) on the page. The structure of the example is
straightforward:

1. Create a division (div) and assign it an id attribute (id=2).


2. Create a textarea and assign it an id (id=1).
3. Get the contents of the textarea using the usual syntax:
w = document.getElementById(1).value
4. Change the HTML in a target element using the innerHTML property:
document.getElementById (2).innerHTML = w

The example docWrite11.html illustrates how the innerHTML can be used to


conveniently change the contents of HTML tags like cells in tables. One cell calls f1(ID) and
uses the id and getElementById combination to make the change:

document.getElementById(ID).innerHTML = "LUCK"

where the function receives the elements id. This changes the contents of the affected table
cell. The other cell calls f2(obj) and uses the object notation directly:

obj.innerHTML = "Day"
where f2(obj) gets the identify of the object via the this parameter. Another cell uses the
f3(obj) function to pass the object via this notation and then uses the firstChild notation to
access the cell's data:

p.firstChild.data = "Happy".

The example docWrite09.html illustrates an alternative method for accessing the


innerHTML of an element:

document.getElementsByTagName ("div").item(0).innerHTML = w

This uses the getElementsByTag method which requires the name of a tag type like div here
which you can access. It then returns a list of all the elements with that tag. The successive
elements can then be accessed using the item(n) method. Here we just get the first element
on the list item (0).

A useful syntax feature for constructing strings that include quotes is the back slash
escape character \. The back slash eliminates the need for shifting back and forth between
the single and double quotes notation. For example, docWrite12.html illustrates this with the
string:

s = "id = \"30\" width = \"150\" "


alert(s)

which pops-up: id = "30" width = "150". One just prefaces each double quote which is
internal to the encompassing outer double quotes with a back slash.
Summary Syntax Table - II
JS Syntax Remarks
functions function name ( ) { ... } Put in script in head of HTML.
function onclick = "name( )" Place in element triggering the
invocation onchange = "name( )" invocation.
function body { stmt1 ; stmt2 ; etc } Semi-colons separate
statements.

if if (condition) { stmt1 ; etc }


if (condition) { stmt1 ; return } Causes return from function.
if-else if (Boolean condition) { stmt1 ; etc } { } are not needed if there is
else { stmt2 ; etc } only one statement.
for-loop for (i = 0; i <N; i++) { ... }
nested for-loops for (i = 0; i <3; i++)
for (j=0; j <4; j++) { ... }

1D-array A= ["s1", "s2", "s3" , "s4" ] Indices run from 0 to 3.


A.length Number of entries.
var B = new Array ( ) Makes array to which elements
can be added sequentially.

2D-array var A = new Array (3) Creates 3 x 4 array


for (i = 0; i <3; i++) A[i] = new Array (4)
var A = [ [1,2,3,4], [5,6,7,8], [9,8,7,6] ] Alternative initialization.
A[i][j] Accesses i, j element of A

JS functions
alert alert (string argument)
parse parseInt (x) Converts to integer.
parseFloat (x) Converts to decimal.
focus document.getElementById (1). focus( ) Puts focus in element with
id=1.
select document.getElementById (1). select( ) Highlights element with id=1.
random Math.random ( ) Makes random decimal on 0 to
1
round Math.round (x ) Rounds x to nearest integer.
setTimeout setTimeout ("name ( )" , N) Calls name( ) in N msec.
setInterval m = setInterval ("name ( )" , N) Calls name( ) every N msec.
clearInterval clearInterval ( m ) Stops setInterval calls.

DOM
getElementById document.getElementById (1).value Gets value of element id=1
document.getElementById(2).innerHTML= Replaces id=2's HTML with w
w
window.open(URL, "A") Open URL in window named
A.

this <input type="button" onclick = "f1(this)" /> f1(this) identifies the HTML
function f1( p ) element where onclick occurs.
{ use: p.height or p.id or p.name or f1's code can then refer to the
p.style.background = 'teal' etc } element's (p's) properties.
Construction Notes:
HTML Validation sites xhtml, example
DOM 355…358…360-375 398…
traversal algorithm
Menu & radio
syntax & events - Wang – radio's events, vars --radio index 187
Wang – menu selected index - apps-Wang – 341 - menuactions Menu syntax
Syntax
While switch || 52a
(readonly), pass name – a5-2, this[?] ….50d good
absolute 213
visibility 222 sebesta – with onsubmit was temporary, ok with onclick
challenge: hunt's widgets
concatenation with integers: m + "" + n – prevents the no's from being added
because the "" forces string concatenation instead.
Timer 238 sebesta
Talking calculator Speech converter – limited dictionary
how to sequence media in javascript
Preloading images Dreamweaver rollovers
Sebesta 182 events 183
199 bubble exception handling model 321
239sebesta advantage of external script file
Slider - - href to script
Converter - Multiverter – with onchange ?
x = document.images.item[0]
x = document.body
x = document.title
x = document.URL
document.getElementsByTagName("div").item(0).innerHTML = w

You might also like