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

JavaScript Topics

Embed Size (px)

DESCRIPTION

java script notes

Citation preview

HTML class-notes

JavaScript Notes 1. Basic JavaScript - Defining and invoking JavaScript functions2. JavaScript - Objects images rollovers - and arrays

3. JS Objects - Window document objects, innerHTML1. 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:

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 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 tag in the element of an HTML page with an associated invocation condition specified in a 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:

document.guestForm.onsubmit = checkIt 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:

We can use that syntax here too, namely:

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:

function checkIt (list-of-arguments) {}

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:

function checkIt ( )

{

1. Test and announce if name field is empty.

2. Test and announce if age is valid number.

}

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:

document.guestForm.mysubmit.onsubmit = checkIt; 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 ( ), 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 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 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 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:

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:

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:

functions & definitions 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: alert (a) 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:

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.

JSSyntaxRemarks

options > advanced > script choices turn debugger on. Netscape: Tools > web-development > JavaScript console.

2. More JavaScript: objects images rollovers - and arraysThis 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-DOMThe 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 nodeWe 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 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 idobj.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 cell "node". WorkingExample00c.html shows how to access it via:

obj.firstChild.data- read as: obj's first child's dataThe 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).heightdocument.getElementById(3).borderExample 2: rollovers, src attribute, name attribute, events on other objectsRefer 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 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 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 ( 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).value4. Change the HTML in a target element using the innerHTML property:

document.getElementById (2).innerHTML = wThe 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 - IIJSSyntaxRemarks

functionsfunction name ( ) { ... } Put in script in head of HTML.

function invocationonclick = "name( )"

onchange = "name( )"Place in element triggering the invocation.

function body { stmt1 ; stmt2 ; etc }Semi-colons separate statements.

ifif (condition) { stmt1 ; etc }

if (condition) { stmt1 ; return }Causes return from function.

if-elseif (Boolean condition) { stmt1 ; etc }

else { stmt2 ; etc }{ } are not needed if there is only one statement.

for-loopfor (i = 0; i