UNIT-1-Javascript Lecture Notes-2
UNIT-1-Javascript Lecture Notes-2
Part 1
JavaScript
History
JavaScript was designed to 'plug a gap' in the techniques available for creating web-pages.
HTML is relatively easy to learn, but it is static. It allows the use of links to load new pages, images, sounds,
etc., but it provides very little support for any other type of interactivity.
A user-action causes a request to be sent over the internet from the client machine to the
server.
The server runs a CGI program that generates a new page, based on the information supplied
by the client.
The new page is sent back to the client machine and is loaded in place of the previous page.
Thus every change requires communication back and forth across the internet.
Java applets
Run on the client, so there is no need to send information back and forth over the internet for every
change, but...
Provides dynamic facilities similar to those available using CGI programs and Java applets.
Netscape subsequently teamed-up with Sun Microsystems (the company that developed Java) and produced
JavaScript.
Javascript only runs on Netscape browsers (e.g., Netscape Navigator). However, Microsoft soon developed a
version of JavaScript for their Internet Explorer browser. It is called JScript. The two languages are almost
identical, although there are some minor differences.
Internet browsers such as Internet Explorer and Netscape Navigator provide a range of features that can be
controlled using a suitable program. For example, windows can be opened and closed, items can be moved
around the page, colours can be changed, information can be read or modified, etc..
However, in order to do this you need to know what items the browser contains, what operations can be carried
out on each item, and the format of the necessary commands.
In this course we will be using JavaScript/JScript to program browsers. However, there are several other
languages we could use should we wish to. Therefore, we shall try to distinguish clearly between those aspects
of internet programming which are specific to JavaScript/JScript and those which remain the same regardles of
which language we choose to use.
We'll start by looking at some of the basic features of the JavaScript language.
For example, a shopping website might use a variable called total to hold the total cost of the goods the customer
has selected. The amount stored in this variable may change as the customer adds more goods or discards earlier
choices, but the name total stays the same. Therefore we can find out the current total cost at any time by asking
the program to tell us what is currently stored in total.
For example, we might use a literal to store the VAT rate, since this doesn't change very often. The literal would
have a value of (e.g.) 0.21. We could then obtain the final cost to the customer in the following way:
Numeric Any numeric value, whether a whole number (an integer) or a number that
www.cs.ucc.ie/~gavin/javascript/02_JS1.html 2/5
1/31/2020 Javascript Lecture Notes
Note that:
When a new variable is created (or declared) its name must be preceded by the word var
We refer to the equals sign as the assignment operator because we use it to assign values to variables;
JavaScript is case-sensitive
Reserved words (i.e., words which indicate an action or operation in JavaScript) cannot be used as
variable names.
Operators
Operators are a type of command. They perform operations on variables and/or literals and produce a result.
www.cs.ucc.ie/~gavin/javascript/02_JS1.html 3/5
1/31/2020 Javascript Lecture Notes
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
(If you're not sure what a modulus operator does, here are some notes and an example)
These are known as binary operators because they require two values as input, i.e.:
4+3
7/2
15 % 4
These are known as unary operators because they require only one value as input, i.e.:
var totalStudents = 60
var examPasses = 56
var resits = totalStudents - examPasses
Note that by carrying out this operation we have created a new variable - resits.
It will be a numeric value because it has been created as a result of an operation performed on two numeric
values.
www.cs.ucc.ie/~gavin/javascript/02_JS1.html 4/5
1/31/2020 Javascript Lecture Notes
We can also combine these operators (and the assignment operator, =) in certain ways.
For example:
total += price
Similarly,
total *= quantity
You may find the descriptions helpful when trying to remember what each operator does. For example:
5*=3
www.cs.ucc.ie/~gavin/javascript/02_JS1.html 5/5
1/31/2020 Javascript Lecture Notes
Part 2
Functions in JavaScript
In JavaScript, as in other languages, we can create functions. A function is a kind of mini-program that forms
part of a larger program.
Functions:
consist of one or more statements (i.e., lines of program code that perform some operation)
are separated in some way from the rest of the program, for example, by being enclosed in curly brackets,
{.....}
are given a unique name, so that they can be called from elsewhere in the program.
Where the same operation has to be performed many times within a program.
Rather than writing the same code again and again, it can be written once as a function and used
repeatedly. For example:
request_confirmation_from_user
Rather than writing long, rambling programs in which every single operation is listed in turn, it is usually
better to divide programs up into small groups of related operations. For example:
set_variables_to_initial_values
welcome_user
obtain_user_input
perform_calculations
display_results
function name()
{
statement;
statement;
statement
www.cs.ucc.ie/~gavin/javascript/03_JS2.html 1/4
1/31/2020 Javascript Lecture Notes
Note that all the statements except the last statement must be followed by semi-colons. The last statement
doesn't need one, but if you do put a semi-colon after the last statement it won't cause any problems.
function initialiseVariables()
{
itemsSold = 0;
nettPrice = 0;
priceAfterTax = 0
}
When called, this function will set the three variables itemsSold, nettPrice and priceAfterTax to
zero.
To run this function from somewhere else in a program, we would simply call it by name, e.g.:
initialiseVariables();
Note that the name must be followed by a pair of brackets. The purpose of these will become clear later.
For example:
function sayGoodbye()
{
alert("Goodbye!")
}
function sayHello()
{
alert("Hi, there!");
sayGoodbye()
}
When the function sayHello() is called, it first displays an alert on the screen. An alert is simply box
containing some text and an 'OK' button that the user can press to make the box disappear when the text has
been read. In this case the box will contain the words "Hi, there!".
The sayHello() function then calls the function sayGoodbye(), which posts another alert saying
"Goodbye".
www.cs.ucc.ie/~gavin/javascript/03_JS2.html 2/4
1/31/2020 Javascript Lecture Notes
Note that the function sayGoodbye() is written first. Browsers interpet JavaScript code line-by-line, starting
at the top, and some browsers will report an error if they find a reference to a function before they find the
function itself. Therefore functions should be declared before the point in the program where they are used.
However, it is often necessary to supply information to a function so that it can carry out its task.
For example, if we want to create a function which adds VAT to a price, we would have to tell the function what
the price is.
To do this we would pass the price into the function as a parameter. Parameters are listed in between the
brackets that follow the function name. For example:
In this case two parameters are used, but it's possible to use more than this if necessary. The additional parameter
names would simply be added on to the list of parameters inside the brackets, separated from one another by
commas. It's also possible to use just one prameter if that's all that is needed.
function addVAT(price)
{
price *= 1.21;
alert(price)
}
This function accepts a parameter called price, multiplies it by 1.21 (i.e., adds an extra 21% to it), and then
displays the new value in an alert box.
addVAT(nettPrice)
addVAT(5)
www.cs.ucc.ie/~gavin/javascript/03_JS2.html 3/4
1/31/2020 Javascript Lecture Notes
var nettPrice = 5;
addVAT(nettPrice)
For example, we might want to add VAT to a price and then, instead of just displaying the result, pass it back to
the user or display it in a table.
function addVAT(price)
{
price *= 1.21;
return price
}
The value returned by the funtion will be stored in the variable newPrice. Therefore this funtion will have the
effect of making newPrice equal to nettPrice multiplied by 1.21.
www.cs.ucc.ie/~gavin/javascript/03_JS2.html 4/4
1/31/2020 Javascript Lecture Notes
Part 3
Comparison Operators compare two values and produce an output which is either true or false.
For example, suppose we have two variables which are both numeric (i.e., they both hold numbers):
examPasses
and
totalStudents
... and then perform a comparison to determine whether the statement is true or false.
==
(i.e., two equals signs, one after the other with no space in between).
It means 'is equal to'. Compare this with the assignment operator, =, which means 'becomes equal to'. The
assignment operator makes two things equal to one another, the comparison operator tests to see if they are
already equal to one another.
www.cs.ucc.ie/~gavin/javascript/04_JS3.html 1/10
1/31/2020 Javascript Lecture Notes
examPasses == totalStudents
!=
For example:
examPasses != totalStudents
<
and
>
For example:
www.cs.ucc.ie/~gavin/javascript/04_JS3.html 2/10
1/31/2020 Javascript Lecture Notes
Another example:
As with some of the other 0perators we have encountered, comparison operators can be combined in various
ways.
<=
means
For example:
Also:
>=
means
For example:
Thus all programming languages include statements which make 'decisions' based upon data.
Else watch_television
if (condition)
{
statement;
statement
}
else
{
statement;
statement
www.cs.ucc.ie/~gavin/javascript/04_JS3.html 4/10
1/31/2020 Javascript Lecture Notes
};
The condition is the information on which we are basing the decision. In the example above, the condition
would be whether we have more than £15. If the condition is true, the browser will carry out the statements
within the if... section; if the condition is false it will carry out the statements within the else... section.
The if... part of the statement can be used on its own if required. For example:
if (condition)
{
statement;
statement
};
If you are using both the if... and the else... parts of the statement, it is important NOT to put a semi-
colon at the end of the if... part. If you do, the else... part of the statement will never be used.
A semi-colon is normally placed at the very end of the if...else... statement, although this is not needed
if it is the last or only statement in a function.
if (score > 5)
{
alert("Congratulations!")
}
else
{
alert("Shame - better luck next time")
};
- an initial value
- a final value
- an increment
www.cs.ucc.ie/~gavin/javascript/04_JS3.html 5/10
1/31/2020 Javascript Lecture Notes
Note that:
* The loop condition is tested using a variable, x, which is initially set to the start
value (0) and then incremented until it reaches the final value (100).
* The central part of the condition, the part specifying the final value, must
remain true throughout the required range. In other words, you could not use x
= 100 in the for loop above because then the condition would only be true
when x was either 0 or 100, and not for all the values in between. Instead you
should use x <= 100 so that the condition remains true for all the values
between 0 and 100.
The first example is a simple loop in which a value is incremented from 0 to 5, and reported to the screen each
time it changes using an alert box. The code for this example is:
The second example is the same except that the value is decremented from 5 to 0 rather than incremented from 0
to 5. The code for this example is:
The start and finish values for the loop must be known before the loop starts.
However, they need not be written into the program; they can, if necessary, be obtained when the program is run.
For example:
In this example, the user is prompted to type-in two numbers which are then assigned to the variables
initialValue and finalValue. The loop then increments from initialValue to finalValue in
exactly the same way as if these values had been written directly into the program.
while (condition)
{
statement(s);
}
var x = 500000;
alert("Starting countdown...");
while (x > 0)
{
x--;
};
www.cs.ucc.ie/~gavin/javascript/04_JS3.html 7/10
1/31/2020 Javascript Lecture Notes
alert("Finished!");
In this example, x is initially set to a high value (500,000). It is then reduced by one each time through the
loop using the decrement operator (x--). So long as x is greater than zero the loop will continue to operate, but
as soon as x reaches zero the loop condition (x > 0) will cease to be true and the loop will end.
The effect of this piece of code is to create a delay which will last for as long as it takes the computer to count
down from 500,000 to 0. Before the loop begins, an 'alert' dialog-box is displayed with the message "Starting
Countdown...". When the user clicks the 'OK' button on the dialog-box the loop will begin, and as soon as it
finishes another dialog-box will be displayed saying "Finished!". The period between the first dialog box
disappearing and the second one appearing is the time it takes the computer to count down from 500,000 to 0.
The principal difference between for loops and while loops is:
with a while loop, the number of times the loop is to be executed need not be known in advance.
while loops are normally used where an operation must be carried out repeatedly until a particular situation
arises.
For example:
In this example, the variable passwordNotVerified is initially set to the Boolean value true. The user is
then prompted to enter a password, and this password is compared with the correct password stored in the
variable called password. If the password entered by the user matches the stored password, the variable
passwordNotVerified is set to false and the while loop ends. If the password entered by the user does
not match the stored password, the variable passwordNotVerified remains set to true and a warning
message is displayed, after which the loop repeats.
PS The password is CS7000 - and don't forget that the 'CS' must be capitalised.
www.cs.ucc.ie/~gavin/javascript/04_JS3.html 8/10
1/31/2020 Javascript Lecture Notes
while(passwordNotVerified)
In other words, if we don't specify true or false in a conditional statement, the JavaScript interpreter will
assume we mean true and test the variable accordingly.
This allows us to make our code a little shorter and, more importantly, to make it easier for others to understand.
The line:
while(passwordNotVerified)
is much closer to the way in which such a condition might be expressed in English than:
while(passwordNotVerified == true)
Logical Operators
We have met a number of operators that can be used when testing conditions, e.g., == , < , > , <= , >= .
Two more operators that are particularly useful with while loops are:
|| Logical OR
These operators are used to combine the results of other conditional tests.
For example:
means...
if x is greater than 0 and less than 100...
Placing the && between the two conditions means that the if statement will only be carried out if
BOTH conditions are true. If only one of the conditions is true (e.g., x is greater than 0 but also
greater than 100) the condition will return false and the if statement won't be carried out.
www.cs.ucc.ie/~gavin/javascript/04_JS3.html 9/10
1/31/2020 Javascript Lecture Notes
Similarly:
if (x == 0 || x == 1)
means...
if x is 0 or x is 1...
Placing the || between the two conditions means that the if statement will be executed if EITHER
of the conditions are true.
The ability to combine conditions in this way can be very useful when setting the conditions for while loops.
For example:
var amount = prompt ("Please enter a number between 1 and 9", "");
In this example, the variable amount is initially set to the value typed-in by the user in response to the 'prompt'
dialog-box. If the amount entered by the user is between 1 and 9, the loop condition becomes false and the
loop ends. If the amount entered by the user is less than 1 or greater than 9, the loop condition remains true
and a warning is displayed, after which the user is prompted to enter another value.
Note that if you enter a correct value immediately, the while loop never executes. The condition is false the
first time it is tested, so the loop never begins.
www.cs.ucc.ie/~gavin/javascript/04_JS3.html 10/10
1/31/2020 Javascript Lecture Notes
Part 4
An object is a set of variables, functions, etc., that are in some way related. They are grouped together and given
a name
Properties
Methods
Events
Internet browsers contain many objects. In the last few years the object structure of internet browsers has
become standardised, making programming easier. Prior to this, browsers from different manufacturers had
different object structures. Unfortunately, many such browsers are still in use.
www.cs.ucc.ie/~gavin/javascript/05_JS4.html 1/15
1/31/2020 Javascript Lecture Notes
The Document Object Model. Objects shown in green are common to both Netscape
Navigator and Internet Explorer; objects shown in yellow are found only in Internet Explorer
while objects shown in blue are found only in Netscape Navigator.
status The contents of the status bar (at the bottom of the browser window). For example:
location The location and URL of the document currently loaded into the window (as
displayed in the location bar). For example:
alert(window.location);
will display an alert containing the location and URL of this document.
www.cs.ucc.ie/~gavin/javascript/05_JS4.html 2/15
1/31/2020 Javascript Lecture Notes
length The number of frames (if any) into which the current window is divided. For
example:
alert(window.length);
will display an alert indicating the number of frames in the current window.
will place a string representing the parent window into the variable
parentWindow, then use it to report the number of frames (if any) in the parent
window.
top The top-level window, of which all other windows are sub-windows. For example:
will place a string representing the top-level window into the variable
topWindow, then use it to report the number of frames (if any) in the top-level
window.
top behaves in a very similar way to parent. Where there are only two levels of
windows, top and parent will both indicate the same window. However, if there
are more than two levels of windows, parent will indicate the parent of the
current window, which may vary depending upon which window the code is in.
However, top will always indicate the very top-level window.
alert() Displays an 'alert' dialog box, containing text entered by the page designer, and an
'OK' button. For example:
alert("Hi, there!");
confirm() Displays a 'confirm' dialog box, containing text entered by the user, an 'OK' button,
and a 'Cancel' button. Returns true or false. For example:
will display a dialog box containing the message "Delete File?" along with an 'OK'
button and a 'Cancel' button. If the user clicks on 'OK' the variable response will
contain the Boolean value true, and this will appear in the 'alert' dialog-box; If
the user clicks on 'Cancel' the variable response will contain the Boolean value
false and this will appear in the 'alert' dialog-box.
Request Confirmation Click here to see this code in operation.
prompt() Displays a message, a box into which the user can type text, an 'OK' button, and a
'Cancel' button. Returns a text string. The syntax is:
prompt(message_string, default_response_string)
For example:
will display a dialog box containing the message "Select File" along with an 'OK'
button, a 'Cancel' button, and an area into which the user can type. This area will
contain the string "file.txt", but this can be overwritten with a new name. If the user
clicks on 'OK' the variable fileName will contain the string "file.txt" or whatever
the user entered in its place, and this will be reported using an alert dialog box.
Display Prompt Click here to see this code in operation.
open() Opens a new browser window and loads either an existing page or a new document
into it. The syntax is:
For example:
will open a new window 100 pixels high by 200 pixels wide. An HTML document
called '05_JS4nw.html' will be loaded into this window.
www.cs.ucc.ie/~gavin/javascript/05_JS4.html 4/15
1/31/2020 Javascript Lecture Notes
Note that the variable newWindow is not preceded by the word var. This is
because newWindow is a global variable which was declared at the start of the
script. The reason for this is explained below.
close() Closes a window. If no window is specified, closes the current window. The syntax
is:
window_name.close()
For example:
newWindow.close()
Note that the window name (i.e., newWindow) must be declared as a global
variable if we want to open the window using one function and close it using
another function. If it had been declared as a local variable, it would be lost from
the computer's memory as soon as the first function ended, and we would not then
be able to use it to close the window.
onLoad() Message sent each time a document is loaded into a window. Can be used to trigger
actions (e.g., calling a function). Usually placed within the <body> tag, for
example:
<body onLoad="displayWelcome()">
onUnload() Message sent each time a document is closed or replaced with another document.
Can be used to trigger actions (e.g., calling a function). Usually placed within the
<body> tag, for example:
<body onUnload="displayFarewell()">
www.cs.ucc.ie/~gavin/javascript/05_JS4.html 5/15
1/31/2020 Javascript Lecture Notes
document.bgColor = "lightgreen";
document.fgColor = "blue";
will cause the colour of the text in the document to change to blue.
Change FG Color Click here to change the foreground colour of this document.
Restore FG Color Click here to change it back again.
linkColor The colour used for un-visited links (i.e., those that have not yet been clicked-upon
by the user). For example:
document.linkColor = "red";
will change the colour of all the un-visited links in a document to red.
alinkColor The colour used for an active link (i.e., the one that was clicked-upon most
recently, or is the process of being clicked). For example:
document.alinkColor = "lightred";
vlinkColor The colour used for visited links (i.e., those that have previously been clicked-upon
by the user). For example:
document.vlinkColor = "darkred";
www.cs.ucc.ie/~gavin/javascript/05_JS4.html 6/15
1/31/2020 Javascript Lecture Notes
will change the colour of all the visited links in a document to dark-red.
title The title of the document, as displayed at the top of the browser window. For
example:
will replace the existing page title with the text "This title has been changed".
(Note that some browsers do not display a title bar. On such browsers this code will
have no effect.)
forms An array containing all the forms (if any) in the document. It accepts an index
number in the following way:
forms[index-number]
write() Allows a string of text to be written to the document. Can be used to generate new
HTML code in response to user actions. For example:
document.write("<h1>Hello</h1> ");
document.write("<p>Welcome to the new page</p>");
document.write("<p>To return to the lecture
notes,");
document.write("<a href='05_JS4.html'>click here
</a></p>");
will replace the existing page display with the HTML code contained within the
brackets of the document.write() methods. This code will display the text
"Hi, there!" and "Welcome to the new page", followed by a link back to this page.
Note that all the HTML code within the brackets is enclosed within double-quotes.
Note too that the link declaration ('05_JS4.html') is enclosed within single quotes.
You can use either single or double quotes in both cases, but you must be careful
not to mix them up when placing one quoted string inside another.
Write To Document Click here to see this code in operation.
www.cs.ucc.ie/~gavin/javascript/05_JS4.html 7/15
1/31/2020 Javascript Lecture Notes
When you create a form in an HTML document using the <form> and </form> tags, you automatically create
a form object with properties, methods and events that relate to the form itself and to the individual elements
within the form (e.g., text boxes, buttons, radio-buttons, etc.). Using JavaScript, you can add behaviour to
buttons and other form elements and process the information contained in the form.
name The name of the form, as defined in the HTML <form> tag when the form is
created, for example:
<form name="myForm">
This property can be accessed using JavaScript. For example, this paragraph is part
of a form that contains the example buttons. It is the third form in the document
(the others contain the buttons for the Window and Document object examples). To
obtain the name of this form, we could use the following code:
alert(document.forms[2].name);
This code uses the document.forms property described earlier. Since this is the
third form in the document it will have the index-number 2 (remember that forms
are numbered from 0).
Thus the code above will display the name property of the example form, which is
simply "formExamples".
Get Form Name Click here to see this code in operation.
method The method used to submit the information in the form, as defined in the HTML
<form> tag when the form is created, for example:
<form method="POST">
The method property can be set either to POST or GET (see under 'forms' in any
good HTML reference book if you're not sure about the use of the POST and GET
methods).
This property can be accessed using JavaScript. For example, the present form has
its method attribute set to "POST" (even though it's not actually going to be
submitted). So the code:
alert(document.forms[2].method);
www.cs.ucc.ie/~gavin/javascript/05_JS4.html 8/15
1/31/2020 Javascript Lecture Notes
will display the method property of the example form, which is "POST".
Get Form Method Click here to see this code in operation.
action The action to be taken when the form is submitted, as defined in the HTML
<form> tag when the form is created, for example:
<form action="mailto:sales@bigco.com">
The action property specifies either the URL to which the form data should be
sent (e.g., for processing by a CGI script) or mailto: followed by an email
address to which the data should be sent (for manual processing by the recipient).
See under 'forms' in any good HTML reference book for more information on the
use of the action attribute.
This property can be accessed using JavaScript. For example, the present form has
its action attribute set to "mailto:sales@bigco.com" (even though it's not
actually going to be submitted). So the code:
alert(document.forms[2].action);
length The number of elements (text-boxes, buttons, etc.) in the form. For example:
alert(document.forms[2].length);
will display the number of elements in this form (there are 22).
Get Form Length Click here to see this code in operation.
elements An array of all the elements in the form. Individual elements are referenced by
index-number.
Elements are automatically numbered from 0, starting at the beginning of the form,
so the first element in a form will always have the index-number 0. For example:
alert(document.forms[2].elements[0].name);
will display the name of the first element in this form, which is the button labelled
"Get Form Name". It's name is "get_form_name".
Get Element Name Click here to see this code in operation.
www.cs.ucc.ie/~gavin/javascript/05_JS4.html 9/15
1/31/2020 Javascript Lecture Notes
submit() Submits the form data to the destination specified in the action attribute using
the method specified in the method attribute. As such it performs exactly the
same function as a standard 'submit' button, but it allows the programmer greater
flexibility. For example, using this method it is possible to create a special-purpose
'submit' button that has more functionality than a standard 'submit' button, perhaps
checking the data or performing some other processing before submitting the form.
onSubmit Message sent each time a form is submitted. Can be used to trigger actions (e.g.,
calling a function). Usually placed within the <form> tags, for example:
<form onSubmit="displayFarewell()">
Text-boxes and text-areas have almost identical sets of properties, methods and events, so they will be
considered together.
name The name of the text-box or text-area, as defined in the HTML <input> tag
when the form is created, for example:
The name property of a text-box or other form element can be accessed using
JavaScript in the manner shown under the section on document.length,
above.
value Whatever is typed-into a text-box by the user. For example, here is a simple text-
box:
This text-box is named textBox1. Therefore, we can obtain any text typed into it
using the following line of code:
www.cs.ucc.ie/~gavin/javascript/05_JS4.html 10/15
1/31/2020 Javascript Lecture Notes
alert(document.forms[2].textBox1.value);
Get Text-box Value Type something into the text-box, then click here to see this
code in operation.
onFocus Event signal generated when a user clicks in a text-box or text-area. For example,
here is a simple text-box:
onBlur Event signal generated when a user clicks outside a text-box or text-area having
previously clicked inside it. For example, here is a simple text-box:
name The name of the button, radio-button or checkbox, as defined in the HTML
www.cs.ucc.ie/~gavin/javascript/05_JS4.html 11/15
1/31/2020 Javascript Lecture Notes
value The value given to the button when it is created. On standard buttons the value is
displayed as a label. On radio-buttons and check-boxes the value is not displayed.
For example, here is a button:
This button is named button1 and has the value Original value,
original label. We can change the value of the button, and hence it's label,
using the following code:
checked This property - which is used with radio-buttons and check-boxes but not standard
buttons - indicates whether or not the button has been selected by the user. For
example, here is a checkbox:
if (document.forms[2].checkbox1.checked == true)
{
alert("Checked");
}
else
{
alert("Not checked");
};
Try clicking on the check-box to select and un-select it, then click here
Show Checkbox Status to see this code in operation.
www.cs.ucc.ie/~gavin/javascript/05_JS4.html 12/15
1/31/2020 Javascript Lecture Notes
focus() Give the button focus (i.e., make it the default button that will be activated if the
return key is pressed). For example, here is a button that displays an alert when
clicked:
Hello
This button is named button2 and has the value Hello. We can give it focus
using the following code:
document.forms[2].button2.focus();
Give Button Focus Click here to see this code in operation. A dotted border
should appear around the label on the button, indicating that the button now has
focus. Pressing the RETURN key should now activate the button, causing it to
display the alert just as if it had been clicked.
document.forms[2].button2.blur();
Remove Focus will remove the focus (indicated by the dotted line) from the
button above. Click here to see this code in operation.
click() Simulates the effect of clicking the button. For example, below is a button that has
the following code:
document.forms[2].button2.click();
Click Button Clicking on this button will have the same effect as clicking directly
on the button labelled 'Hello', i.e., it will display the 'Hello to you too' dialog box.
onClick Signal sent when the button is clicked. Can be used to call a function. Probably the
most frequently-used of all the button events (all the example buttons in this
document use this method).
For example:
Click Here
www.cs.ucc.ie/~gavin/javascript/05_JS4.html 13/15
1/31/2020 Javascript Lecture Notes
onFocus Signal sent when the button receives focus (i.e., when it becomes the default
button, the one that is activated by pressing the RETURN key). For example:
Click Here
The first time you click the button it will gain focus, and the alert will appear.
However, if you click again, no alert will appear because the button still has focus
as a result of the previous click. To make the alert appear again, you will have to
remove focus from the button (e.g., by clicking somewhere else on the document)
then restore it by clicking the button again.
onBlur Signal sent when the button loses focus. For example:
Click Here
Clicking the button will not cause the alert to appear because it will only give the
button focus. However, if you remove focus from the button (e.g., by clicking
somewhere else on the document) the alert will appear.
The principal difference from a programming perspective is that selection-boxes don't have a checked
property. Instead, to find out which option has been selected, you must use the SelectedIndex property.
SelectedIndex Returns an integer indicating which of a group of options has been selected by the
user. For example:
Something or other
www.cs.ucc.ie/~gavin/javascript/05_JS4.html 14/15
1/31/2020 Javascript Lecture Notes
alert(document.forms[2].selectBox1.selectedIndex);
Get Selection Click here to see this code in operation. You should find that the
value of selectedIndex (as shown in the dialog box) varies from 0 to 2
depending upon which of the three items in the selection-box is currently selected.
www.cs.ucc.ie/~gavin/javascript/05_JS4.html 15/15
1/31/2020 Javascript Lecture Notes
Part 5
Other Objects
In addition to the objects we have already encountered, there are a number of other objects that form part of the
JavaScript language. Among the more important and useful of these are the Date and Math objects.
The Date object allows us to obtain the current date and time, and to perform various timing operations.
In order to use the Date object, we must first create a new 'instance' of it. This is done in the following way:
This creates an object called myDateObject that contains information about the date, time, etc., at the instant
it was created. The information in myDateObject doesn't change as time passes, so if you want to know the
correct time a few minutes later you will have to create a new instance of the Date object.
Once you have created an instance of the Date object, you can use any of the methods below to obtain
information from it:
getFullYear() Returns the current year as a four-digit number (e.g., 2000). For example:
getMonth() Returns the current month as an integer from 0-11 (e.g., November = 10). For
example:
getDate() Returns the day of the month as an integer between 1 and 31. For example:
www.cs.ucc.ie/~gavin/javascript/06_JS5.html 1/4
1/31/2020 Javascript Lecture Notes
getDay() Returns the day of the week as an integer between 0 and 6, starting from Sunday
(e.g., Tuesday = 2). For example:
getHours() Returns the hour of the day as an integer between 0 and 23. For example:
getMinutes() Returns the number of minutes since the beginning of the hour as an integer. For
example:
getSeconds() Returns the number of seconds since the start of the minute as an integer. For
example:
In order to use the Date object, it is often necessary to convert the data it produces, e.g., to obtain the names of
days and months rather than just numbers. To see an example of the Date object in use, click here.
The Date object also has methods to obtain time intervals as small as milliseconds, to convert between various
time systems, to parse dates and times in various formats into individual elements, and to perform various other
time-related operations.
www.cs.ucc.ie/~gavin/javascript/06_JS5.html 2/4
1/31/2020 Javascript Lecture Notes
The Math object allows us to perform various mathematical operations not provided by the basic operators we
have already looked at.
round(x) Returns the value of x rounded to the nearest integer. For example:
ceil(x) Returns the absolute value of x rounded up to the next integer value.
Works in a similar way to round(x), above.
floor(x) Returns the absolute value of x rounded down to the next integer value.
Works in a similar way to round(x), above.
The Math object also has methods to perform trigonmetrical operations such as sin(), cos(), tan(),
etc., and a set of properties that include values for pi and other constants.
www.cs.ucc.ie/~gavin/javascript/06_JS5.html 4/4
1/31/2020 Javascript Lecture Notes
Part 6
However, most browsers regard any string as an instance of the String object. Therefore you can declare a
string in the normal way, e.g.:
...and in so doing you will automatically create a String object, complete with its associated methods,
properties, etc..
length Returns the length of a string. For example, here is a text box:
If someone types into the box, you could find out how many
characters they typed using the following code:
var stringLength =
document.form1.textBox1.value.length
Type some text into the box, then click here to see this code in
operation. Display String Length
charAt(index)
www.cs.ucc.ie/~gavin/javascript/07_JS6.html 1/9
1/31/2020 Javascript Lecture Notes
You could find out what the third character in the text-box is using
the following code:
var thirdCharacter =
document.form1.textBox2.value.charAt(2);
(Note that the characters in a string are numbered from zero, not
one. Therefore the third character will be character number two.)
Type some text into the box, then click here to see this code in
operation. Find Third Chararacter
indexOf(character)
To find out whether the text-box contains the letter 'c', we could use
the following code:
var positionOfC =
document.form1.textBox3.value.indexOf("c");
Type some text into the box, then click here to see this code in
operation. Find position of C
Again, bear in mind that the characters in the string are numbered
from zero, not one, so the index will be one less than the character's
actual position. Also note that if there is no 'c' in the string, the value
returned will be -1.
www.cs.ucc.ie/~gavin/javascript/07_JS6.html 2/9
1/31/2020 Javascript Lecture Notes
substring() Returns the portion of a string between two specified positions. The
syntax is:
substring(start_position, end_position)
var extract =
document.form1.textBox4.value.substring(2,5);
Type some text into the box, then click here to see this code in
operation. Find 3-5th Characters
substr(start_position, no_of_characters)
www.cs.ucc.ie/~gavin/javascript/07_JS6.html 3/9
1/31/2020 Javascript Lecture Notes
charCodeAt() Returns the numerical (ASCII) value of the character at the specified
position.
To find the ASCII value of a single character typed into this box, we
could use the following code:
var asciiValue =
document.form1.textBox5.value.charCodeAt(0);
Type a character into the box, then click here to see this code in
operation. Find ASCII Value
For example:
var asciiString =
String.fromCharCode(73,97,110);
This code will create a string containing the ASCII characters whose
numerical valies are 73, 97 and 110. Click here to see this code in
operation. Convert ASCII Values
toString(number)
www.cs.ucc.ie/~gavin/javascript/07_JS6.html 4/9
1/31/2020 Javascript Lecture Notes
In addition to the methods shown above, the String object also provides methods to add HTML formatting to
strings. These methods include:
italics() Formats a string with <i> and </i> tags. The syntax is:
string_name.italics()
For example:
Regular Expressions
www.cs.ucc.ie/~gavin/javascript/07_JS6.html 5/9
1/31/2020 Javascript Lecture Notes
A regular expression describes a pattern of characters or character types that can be used when searching and
comparing strings.
For example, consider a web-site that allows the user to purchase goods online using a credit-card. The credit-
card number might be checked before submission to make sure that it is of the right type, e.g., that it is 16 digits
long, or consists of four groups of four digits separated by spaces or dashes.
It would be quite complicated to perform such checks using just the string-handling functions described above.
However, using regular expressions we could create a pattern that means 'four digits followed by a space or a
dash, followed by four more digits...', etc.. It is then quite simple to compare this pattern with the value entered
by the user and see if they match or not.
The special characters that can be used to create regular expressions include:
In addition, any letter or other character can be used explcitly. For example, if you place an 'a' in a regular
expression pattern it means that an 'a' is expected as a match at that point.
Using these pattern-matching characters, we could create a simple pattern that checks for a credit-card number in
the following way:
\d{4}-\d{4}-\d{4}-\d{4}
The first '\d' means 'any number'. This is followed by '{4}', which extends the pattern to mean 'any four
consecutive numbers'. After this comes a '-' which simply means that a dash character is expected at this point.
Then comes the 'any four consecutive numbers' pattern again, followed by the dash, and so on.
To create such a pattern, we would declare a regular expression object and give it the pattern as a value. This can
be done in two ways:
In the first example, the new regular expression object (RegExp) is declared explicitly.
In the second example, the pattern is declared in much the same way a string might be declared, except that
forward-slashes (/) are used at the beginning and end instead of quote-marks. The forward-slashes indicate that
this sequence of characters is being declared as a regular expression rather than as a string.
Once the regular expression has been created, we can use the test() method to compare it with a string. For
example:
alert(result);
In this example, the regular expression is assigned to a variable called myRegExp. The user is then prompted to
enter a string which is assigned to the variable inputString. The test() method is then used to compare
the two strings, with the result being passed to the variable result which is displayed in an alert() dialog-
box. If the string matches the pattern, the result will be true; if not, it will be false.
Compare Strings Click here to see this example working. Try entering various numbers into the box and see the
result. You should find that the code only returns true if you enter a number that consists of four groups of four
digits separated by dashes.
We can also compare a string with several different patterns using the Logical OR operator. For example:
\d{16}|\d{4}-\d{4}-\d{4}-\d{4}
This example is similar to the previous one except that the following characters have been added to the start of
the string:
\d{16}|
The first few characters, \d{16}, mean 'any sixteen consecutive numbers'. The | character indicates a logical
OR, meaning that the whole expression will be true if either the part before this symbol OR the part after it are
true.
In other words, a string will be regarded as a valid match if it contains 16 consecutive digits OR four groups of
four digits separated by dashes.
Compare Strings Click here to see this example working. You should find that the code returns true if you enter
a number that consists of sixteen consecutive digits or four groups of four digits separated by dashes.
This is fine if the user enters consecutive numbers or groups of numbers separated by dashes, but what if the
user enters groups of numbers separated by spaces?
It is possible test a character in a string to see if it is any one of several specified characters. This can be done in
the following way:
In this example, each of the dashes has been replaced with a pair of square brackets containing both a space and
a dash. This means that either a space or a dash will be accepted at these points in the string. Thus the complete
string will regarded as a valid match if it contains 16 consecutive digits OR four groups of four digits separated
by spaces or dashes.
Compare Strings Click here to see this example working. You should find that the code returns true if you enter
a number that consists of sixteen consecutive digits or four groups of four digits separated either by dashes or
spaces.
The examples given above indicate only a few of the possibilities offered by regular expressions.
Some of the most commonly-used pattern-matching characters are shown below. For a more complete list you
should consult a good reference book (the 'Pure JavaScript' book recommended for use with this course has quite
an extensive list).
[^..] Match any one character other than those within the brackets
[^x-y] Match any one character other than those within the range x to y
search(regExp) Searches for any occurrences of the regular expression in the string. If any are
found, it returns an integer indicating where within the string the matching
sequence begins. If no match is found it returns -1.
For example:
The textbox above is called textBox6 and it is part of a form called form2.
If someone typed a string into the box containing a two-digit number, you could
find where the number begins using the following code:
var numStart =
document.form2.textBox6.value.search(myRegExp);
Type some text into the box, then click here to see this code in operation.
Find Number
replace(regExp, Searches for any occurrences of the regular expression in the string. If any are
newString) found, it replaces them with newString.
For example:
The textbox above is called textBox7 and it is part of a form called form2.
If someone typed a string into the box containing a two-digit number, you could
replace the number with 00 using the following code:
var newString =
document.form2.textBox7.value.replace(myRegExp,
"00");
Type some text into the box, then click here to see this code in operation.
Replace Number
www.cs.ucc.ie/~gavin/javascript/07_JS6.html 9/9
1/31/2020 Javascript Lecture Notes
Part 7
Arrays
An array is a set of variables (e.g., strings or numbers) that are grouped together and given a single name.
For example, an array could be used to hold a set of strings representing the names of a group of people. It might
be called people and hold (say) four different strings, each representing the name of a person:
Items are held in an array in a particular order, usually the order in which they were added to the array. However,
one of the great advantages of arrays is that the ordering can be changed in various ways. For example, the array
above could easily be sorted so that the names are arranged in alphabetical order.
Creating Arrays
To create an array, a new Array object must be declared. This can be done in two ways:
In the second example, the array is declared in much the same way a string might be declared, except that square
brackets ([]) are used at the beginning and end instead of quote-marks. The square brackets indicate to the
JavaScript interpreter that this sequence of characters is being declared as an array.
Arrays are often used to hold data typed-in or otherwise collected from a user. Therefore, it may be necessary to
create the array first and add data to it later. An empty array may be created in the following way:
The array thus created has no elements at all, but elements can be added as necessary later.
If it is not known exactly what data will be stored in the array, but the number of items is known, it may be
appropriate to create an array of a specific size. This may be done in the following way:
The array thus created has four elements, all of which are empty. These empty elements can be filled with data
later on.
www.cs.ucc.ie/~gavin/javascript/08_JS7.html 1/8
1/31/2020 Javascript Lecture Notes
The number of elements in the array can be determined using the length property. For example:
alert(demoArray.length);
The entire contents of the array can be viewed using the valueOf() method. For example:
alert(demoArray.valueOf())
This piece of code will display an alert showing the entire contents of the array demoArray, with
the various elements separated by commas.
The value of a particular element in the array can be obtained by using its position in the array as an index. For
example
This piece of code will prompt the user to enter a number between 0 and 3 (the elements in an array
are numbered from zero, so the four elements in this array will be numbered 0, 1, 2 and 3). It will
then display the corresponding element from the array.
Choose & display Elelent Click here to see this example working.
It is also possible to change the value of an array element using its position in the array as an index. For
example:
This piece of code will prompt the user to enter their name, then place this string into element 0 of
the array, over-writing the string previously held in that element. It will then display the modified
www.cs.ucc.ie/~gavin/javascript/08_JS7.html 2/8
1/31/2020 Javascript Lecture Notes
increasing the length property adds extra (empty) elements onto the end of the array.
decreasing the length property removes some of the existing elements from the end of the array.
This piece of code first determines the number of elements in the array using the length property.
It then uses this information to identify the next element position after the end of the existing array
and places the string "Fred" into that position, thus creating a new element. Finally, it displays the
modified array using the valueOf() method described earlier.
Note that it isn't necessary to add 1 to the value of length in order to identify the next position in
the array. This is because length indicates the actual number of elements, even though the
elements are numbered from zero. For example, if an array has two elements, the value of length
will be 2; however, those two elements will be numbered 0 and 1. Therefore, if length is used as
an index, it will indicate the third element in the array, not the second one.
This piece of code first determines the number of elements in the array using the length property.
It then resets length to one less than its previous value, thus removing the last element in the
array. Finally, it displays the modified array using the valueOf() method described earlier.
www.cs.ucc.ie/~gavin/javascript/08_JS7.html 3/8
1/31/2020 Javascript Lecture Notes
There are also several methods that add and remove elements directly, some of which are listed below. However,
it should be noted that these methods only work with Netscape Navigator, so it is generally preferable to use the
methods described above since they work with most browsers.
push() Adds one or more elements onto the end of an array. For example:
This piece of code would add two new elements, "Fred" and "Lisa" onto the end of
the array. The variable lastElement would contain the value of the last element
added, in this case "Lisa".
pop() Removes the last element from the end of an array. For example:
This piece of code would remove the last element from the end of the array and
return it in the variable lastElement.
unshift() Adds one or more new elements to the beginning of an array, shifting the existing
elements up to make room. Operates in a similar fashion to push(), above.
shift() Removes the first element from the beginning of an array, shifting the existing
elements down to fill the space. Operates in a similar fashion to pop(), above.
slice(x,y) Copies the elements between positions x and y in the source array into a new
array. For example:
newArray = demoArray.slice(0,2);
alert(newArray.valueOf());
This piece of code will copy elements 0 and 1 from the array called demoArray
into a new array called newArray. It will then display the contents of newArray
using the valueOf() method described earlier.
Note that the slice starts at x but stops at the last position before y rather than at
position y itself.
Copy Slice to New Array Click here to see this example working.
concat(array) Concatenates the specified array and the array to which it is applied into a new
www.cs.ucc.ie/~gavin/javascript/08_JS7.html 4/8
1/31/2020 Javascript Lecture Notes
combinedArray = demoArray.concat(newArray);
alert(combinedArray.valueOf());
This piece of code will concatenate demoArray and the new array created in the
last example (newArray) to form another array called combinedArray. It will
then display the contents of combinedArray using the valueOf() method
described earlier.
The order of the elements in an array can be modified using the following methods:
reverse() Reverses the order of the elements within an array. For example:
demoArray.reverse();
alert(demoArray.valueOf());
This piece of code will reverse the order of the elements in the array, then display
the re-ordered array using the valueOf() method described earlier.
sort() Sorts the elements within the array. Unless otherwise specified, the elements will
be sorted alphabetically. For example:
demoArray.sort();
alert(demoArray.valueOf());
This piece of code will sort the elements of the array into alphabetical order, then
display the re-ordered array using the valueOf() method described earlier.
Although the sort() method normally sorts arrays alphabetically, it can be modified to sort in other ways.
This is done by creating a special function and passing the name of that function to the sort() method as a
parameter, e.g.:
demoArray.sort(bylength);
www.cs.ucc.ie/~gavin/javascript/08_JS7.html 5/8
1/31/2020 Javascript Lecture Notes
The sorting function must be written in such a way that it takes two elements of the array as parameters,
compares them, then returns one of the following values indicating what order they should be placed in:
0 : The two elements are the same so the ordering does not matter.
For example, here is a sorting function that sorts array elements by length:
In accordance with the rules for sorting functions, this example accepts two parameters, item1 and item2.
Each of these parameters will be an element of the array, passed to it by the sort() method.
Since the demonstration array contains strings, each element will have a length property. The length properties
of the two parameters are compared using three if statements, and either -1, 0 or 1 is returned depending upon
their relative lengths.
The sort() method will apply this function to each pair of strings in the array in turn until all have been
sorted.
Sort Array Elements by Length Click here to see this example working.
Multi-Dimensional Arrays
The arrays described so far are One-Dimensional Arrays. They are effectively just lists.
www.cs.ucc.ie/~gavin/javascript/08_JS7.html 6/8
1/31/2020 Javascript Lecture Notes
Sometimes, however, we need to store information which has more than one dimension, for example, the scores
in a game:
Sarah 18
Patrick 16
Jane 12
Tim 13
To store data of this type we use multi-dimensional arrays. In JavaScript this is done by using arrays as elements
of other arrays.
For example, the game scores could be stored in the following way:
Each person's data would be stored in a separate, two-element array (one element for the name and one
element for the score).
These four arrays (one for each person) would then be stored in a four-element array.
To identify the individual elements within a multi-dimensional array, we use two index values, one after the
other. The first refers to an element in the outer array (scores in this example), and the second refers to an
element in the inner array (person1, person2, person3 or person4 in this example). For example:
function displayMDarray()
{
for(x = 0; x <=3; x++)
{
alert(scores[x][0] + " has " + scores[x][1] + " points");
}
}
In this example, the array is accessed using pairs of values in square brackets, e.g.:
scores[x][0]
www.cs.ucc.ie/~gavin/javascript/08_JS7.html 7/8
1/31/2020 Javascript Lecture Notes
The value in the first pair of square-brackets indicates one of the four 'person' arrays. The value in the second
pair of square-brackets indicates one of the elements within that 'person' array, either the name (0) or the score
(1).
The variable called x is incremented from 0 to 3 using a for loop. Therefore, x will point to a different one of
the four 'person' arrays each time through the loop. The second value, 0 or 1, then selects either the name or
score from within that array.
View Elements of Multi-Dimensional Array Click here to see this example working.
Multi-dimensional arrays can be accessed and modified using the same methods as one-dimensional arrays.
For example, a multi-dimensional array can be sorted using the reverse() and sort() methods in just the
same way as a one-dimensional array, e.g.:
scores.sort()
Click here to sort the array, then click on the "View Elements of Multi-
Sort Elements of Multi-Dimensional Array
Dimensional Array" button to see the effects.
Note that the array is sorted by the first element of each sub-array, i.e., by names rather than scores.
www.cs.ucc.ie/~gavin/javascript/08_JS7.html 8/8
1/31/2020 Javascript Lecture Notes
Part 8
The HTML tags they recognise, and the way they respond to certain HTML tags.
Therefore, creating web pages that will display correctly on all (or even most) browsers is not easy, particularly
if the pages contain dynamic material.
However, use of a scripting language such as JavaScript allows us to create pages that will load and run correctly
on a wide range of browsers.
Using Dynamic HTML it is possible to modify various attributes of elements - usually style attributes
such as size, position, visibility, etc. - using scripts. For this to work, there has to be a means of uniquely
identifying each element within a web-page so that information can be sent to it or retrieved from it.
Some elements - such as forms and their components - are represented in the object hierarchy and can be
addressed directly. However, not all elements are represented in the object hierarchy, and it was not
considered practical to introduce new objects for each type of element. Therefore, browser manufacturers
introduced other mechanisms for addressing elements:
Microsoft added the all object to Internet Explorer. This is an array of all the elements of a web-
page, allowing the individual elements to be addressed in the following way:
document.all.myElement.style.attribute
Netscape added a mechanism whereby any element could be addressed directly, provided it had
been given a name. This allows elements to be addressed in the following way:
document.myElement.style.attribute
The World-Wide Web Consortium (W3C) subsequently agreed a standard (part of the DOM
Level 1 Standard) whereby elements are assigned a recognised name and henceforth addresed
directly by that name. For example:
myElement.style.attribute
This standard has been adopted in newer browsers (e.g., Netscape 6), but earlier browsers use one of
the proprietary systems described above.
www.cs.ucc.ie/~gavin/javascript/09_JS8.html 1/6
1/31/2020 Javascript Lecture Notes
The <div> tag is recognised by both Internet Explorer and Netscape Navigator, but they offer different
levels of support for it:
In Internet Explorer 4 & 5 and Netscape Navigator 6, divisions are dynamic (i.e., they can be
repositioned and/or have their size, visibility, etc., modified).
The <layer> tag is specific to Netscape Navigator and was supported on versions of Netscape Navigator
prior to version 6. On these browsers it offers similar functionality to that available using divisions in
Internet Explorer, including dynamic-repositioning, etc..
Event handling
For example, if the mouse is clicked whilst over a form button, the click event is received by the
button object and then passed on to objects further up the hierarchy, such as the Document object.
For example, if the mouse is clicked whilst over a form button, the click event is received by the
Document object and passed down to the button object.
(In Netscape Navigator, it is possible to 'capture' events at the Document level and thus prevent
them being sent down the hierarchy to form elements such as buttons; this can be used, for example,
to disable all the elements in a form until such time as they are required.)
Browsers also differ in the support they provide for the JavaScript language. The level of compatibility offered
by the various versions of Netscape and Internet Explorer (for JavaScript and Jscript respectively) is summarised
below:
Navigator JavaScript
Comments
version version
Explorer JScript
Comments
version version
3.0 1.0 Used a separate JScript Scripting Engine which
could be upgraded separately from the browser.
Many versions in use.
Particular problems when handling image attributes.
In addition to the differences listed above, there are many minor and not-so-minor differences in the way the
various browsers suppport and interpret HTML and JavaScript. Most of these will be listed in any good HTML
or JavaScript reference book.
This object returns properties related to the browser, such as its type, version, etc.. It also returns properties
indicating the platform on which the browser is running (Macintosh, Windows PC, Linux PC, etc.),
www.cs.ucc.ie/~gavin/javascript/09_JS8.html 3/6
1/31/2020 Javascript Lecture Notes
alert(navigator.appName);
alert(navigator.appCodeName);
alert(navigator.appVersion);
alert(navigator.platform);
Using some or all of the Navigator object properties, It is possible to determine which browser is being used and
then generate the appropriate code.
This example includes a movable bar that has to be coded differently depending upon which browser it is being
viewed under. The web-page tests to see what browser is being used, then generates appropriate code. The code
used is quite simple and may not accommodate all browsers, but it should work under most widely-used
browsers.
Have a look at the source code of the example to see how it works. Note the following points:
The page contains a script in the <head> section. The script declares two global variables and two
functions. The purpose of these is discussed below.
A piece of JavaScript code that uses the navigator object to determine what browser is being
used. If the browser is found to be Netscape Navigator, a further test is performed to find out what
version is being used. This is done using the charAt() method to obtain the first character of the
string (which is always the browser version number). Once obtained, this information is stored in
one of the global variables, browserType.
This is followed by another piece of JavaScript code that uses document.write() methods to
create a new page. The content of the page varies depending upon the browser used (as determined
by the previous piece of code): if the browser is Netscape Navigator 4, the page content is created
using a <layer> tag; if the browser is Internet Explorer or Netscape Navigator 6, the page content
is created using a <div> tag.
Following this is another piece of code that creates a form with two buttons. This code works
equally well with all the target browsers, so it can be written directly to the document without
checking the browser type.
Finally, there is a piece of code that checks the browser type again and writes either a closing
</layer> tag or a closing </div> tag to the page.
Because these pieces of code are placed in the body of the document they will be executed automatically
when the document is loaded.
Having created the page, the division or layer can be moved around using the two functions in the
<head> section of the document. These interrogate the global variable browserType to find out what
browser is in use, then use one of the following techniques to move the division or layer:
If the code is being viewed under Internet Explorer, the division can be moved by altering the value
of the pixelLeft attribute in its style.
In order to locate the division, the code uses the document.all array. Thus the pixelLeft
attribute of the division called myDivision can be identified using the following code:
document.all.myDivision.style.pixelLeft
If the code is being viewed under Netscape Navigator 4, the layer can be moved by altering the
value of its pageX attribute.
Netscape Navigator does not support the document.all array used in Internet Explorer.
However, <layer> is represented as an object in the Document Object Model. Therefore the value
of the pageX attribute of the layer called myLayer can be read or written simply by specifiying it
in terms of its place within the object hierarchy, e.g.:
www.cs.ucc.ie/~gavin/javascript/09_JS8.html 5/6
1/31/2020 Javascript Lecture Notes
document.mylayer.pageX
If the code is being viewed under Netscape Navigator 6, the division can be moved by altering the
value of the left attribute in its style.
However, unlike Internet Explorer, Netscape Navigator 6 does not support the document.all
array, nor does it provide a special object for the <div> tag as earlier versions did for the
<layer> tag.
Instead, Netscape Navigator 6 uses the getElementByID() method, in accordance with the
current World-Wide Web Consortium (W3C) standard. The getElementByID() method is
called and given the name of the division as a parameter, and the result is stored in a variable. Once
this has been done, the variable can be used to address the division and its style attributes, e.g.:
...
mydiv.style.left
One slight complication with Netscape Navigator 6 is that the left style attribute is stored with the
suffix 'px' (meaning pixels). This is also in accordance with the current W3C standard. Before any
arithmetical operations can be performed on the left attribute, the suffix must be removed. This is
done using the parseInt() method, which extracts integers from strings.
www.cs.ucc.ie/~gavin/javascript/09_JS8.html 6/6