Javascript Notes
Javascript Notes
By shahzad Arain
Shahzad.cdcu@gmail.com
www.pakdata.net
92-334-5307738
92-334-9564004
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.
Conditions & Actions: The body scriptlet that specifies when the function is invoked is:
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.
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:
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.
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".
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:
These examples can be found under the link JavaScript > JavaScript Examples >
JavaScript-II on the web site.
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:
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:
which uses the getElementById method (discussed later) to get the value entered in the field
with id=1.
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
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
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:
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
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:
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:
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:
The firstChild and data references will be discussed later when we look at the DOM further.
document.getElementById(1).height
document.getElementById(3).border
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:
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
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:
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:
Image Arrays
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:
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:
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:
Alternatively, you can declare and initialize an array using the following kind of notation
which visibly displays the nested sub-arrays:
A [i][j] .
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.
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.:
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:
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:
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) ).
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:
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.
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:
Notice: IE browser (version 6.0) does not support these sizing & placement options and just
ignores them, but Netscape does.
The reference:
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.
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".
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:
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.
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