Java Script Course
Java Script Course
ii OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
1
Introduction to JavaScript Programming
This section will provide you with the basics of what JavaScript is, and why you
should use it.
Objectives
1. JavaScript versus JAVA
3. Why JavaScript
5. About JavaScript
2 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Why Learn JavaScript
JavaScript is the only scripting language currently supported by the popular web
browsers. Netscape Navigator only supports JavaScript, whereas Microsoft Internet
Explorer supports both JavaScript and VBScript. JavaScript can also be used on
web servers for what's called server side scripting as well. The time you invest into
learning the JavaScript language will provide you with what is now considered to be
a core skill for web development.
JavaScript can extend the usefulness of your web pages beyond what you can
do with just HTML. In this course you will use it to ensure that a user is inputing
data into your forms in the correct format, to create interesting buttons with
mouse rollover effects, and to create pop-up windows. When combined with
Cascading Style Sheets, you can create what are called Dynamic HTML pages.
By learning JavaScript your needs and imagination will lead you to extend your
HTML pages.
About JavaScript
JavaScript is an interpreted programming language that can be embedded into an
HTML web page. Interpreted means that the entire web page is downloaded to the
browser and the JavaScript code is executed when an event is triggered. When
the code is executed it is interpreted one line at a time. There are a number of
events that will trigger the execution of a JavaScript, like a click on a form button,
or the completion of a web page loading.
The different versions follow somewhat browser development, and the older
browsers do not support newer versions of JavaScript.
3. (True or False) JAVA and JavaScript were created by the same company.
4 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Summary
Objectives
1. Placing JavaScript in an HTML page
2. Case-sensitivity
3. Semicolons
4. Whitespace
5. Brackets
6. Comments
8. Reserved Words
6 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Inserting Client Side JavaScript into an HTML Page
JavaScript is added to an HTML page using the SCRIPT tag. The script tags
should be placed inside the head tag of the document. If an older browser looks at
a page containing script tags it will ignore them, as older browsers are written to
ignore tags they can't interpret.
JavaScript code should also be placed inside an HTML Comment tag set.
When used with JavaScripts the ending comment tag will also start with two
slashes // which is the JavaScript code for comment. This tells the JavaScript
interpreter to ignore that statement.
This is a standard way for adding JavaScript to your HTML pages so that it works
properly for browsers that are JavaScript enabled and those that do not support
JavaScript.
<HTML>
<HEAD>
<TITLE>Web Page containing JavaScript</TITLE>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
<BODY>
(HTML document goes here)
</BODY>
</HTML>
We may also put in a single line of code attached to an event. Events will be
explained later. The general syntax for this structure is:
Writing in any language follows rules and conventions. For example, the English
language requires that each sentence must contain a subject and verb to be
legitimate. You must also capitalize the first letter of a sentence, and end each
sentence with punctuation such as a period or question mark. This is the syntax, or
grammar of the English language. Each programming language has a similar set of
rules commonly referred to as the syntax.
Case-sensitivity:
Semicolons:
White Space:
JavaScript, like HTML, ignores spaces, tabs, and newlines that appear in
statements. JavaScript does, however recognize spaces, tabs, and
newlines that are part of a string. We will talk more about strings later in the
course.
All of these examples will produce the same results. It is a good idea to put
some spacing in your code to make it easier to read. It is not good
programming practice to stretch statements over several lines.
8 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Strings and Quotes:
The double quotation mark can be found within strings that start, and end
with (are delimited by) single quotes ('He said, "JavaScript is an
interesting language." ').
The single quotation mark can be used within a string delimited by double
quotation marks. This syntax will be used quite often through out the book.
For example:
In the example above we have line of HTML code that uses double quotes to
delimit the tag's attributes. So to create a popup window that displays the
string "You Clicked me" we need to enclose the string within single quotes.
This is done so that the entire JavaScript statement is interpreted and the
HTML syntax also remains valid.
For example we want the word “You” to appear on one line and the word
“Clicked” on a new line and “me” on a third line. The string would look like
this:
'You\nClicked\nme'.
The \n represents a carriage return and a line feed. These are the two
operations that take place when you use the return on a typewriter. The
results would look like this:
You
Clicked
me
\b backspace
\f form feed
\n new line
\r carriage return (no linefeed)
\t tab
\' single quote (apostrophe)
\" double quote
The last two are important and can be used like this: 'You
The \ tells the interpreter that in this case it should print the single quote
and not interpret it as a delimiter.
All brackets you open must be closed! This includes ( ), [ ], and { }. i.e.
winpop = window.open('ex1.htm','popup','scrollbars=yes');
if ( x[0] == 10 ) {
x[0] = 0;
x[1] = 0;
}
The square brackets [ ] are part of a special data structure called arrays.
Arrays will be covered later in the course.
10 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Comments:
You can create a comment using the double forward slashes, like this: //
this is a comment
Or for multiple line comments you can open the comment with a forward
slash and an asterisk “/*”, and close it with an asterisk followed by a forward
slash “*/” like this:
In the next chapter you will be introduced to variables and functions. As the
programmer you get to choose and assign the names. The names of the
variables and functions must follow these simple rules.
x
add_two_num
x13
_whatever
$money_string
We recommend that you use descriptive names for your variables and
your functions and that you adopt a standard way of naming things. The two
formats that are common are; using the underscore to replace spaces, or
capitalizing the first letter of complete words after the first word in the name.
For example:
add_two_num
addTwoNumbers
12 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Reserved Words
if _ z_0_ == 0 _ _
x = 2;
_
14 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Summary
2. JavaScript is case-sensitive
6. How and why you should put comments in your program code
7. What names you can use for variables and function names
Objectives
1. Declaring Variables
2. Using Operators
16 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Declaring Your Variables
var x;
var y;
var sum;
You can also declare multiple variables with the same var keyword.
var x, y, sum;
To take it one step further you can combine variable declaration with initialization.
var x = 1, y = 3, sum = 0;
If you don't specify an initial value for a variable when you declare it, the initial
value is a special JavaScript undefined value.
Types of Variables
A big difference between JavaScript and other languages like JAVA and C is that
JavaScript is untyped. This means that a JavaScript variable can hold a value of any
data type, and its data type does not have to be set when declaring the variable.
This allows you to change the data type of a variable during the
execution of your program, for example:
var x = 10;
x = "ten";
In this example the variable x is first assigned the integer value of 10, and then
the string value of the word ten.
var x = 1, y = 3, sum = 0;
sum = x + y;
This small chunk of JavaScript code will declare the variables x, y and sum and
assign the number 1 to x, 3 to y and 0 to sum. The second line of the script will
add x to y and assign it to sum. The value of the sum variable will be 4.
Other operators are used to compare things, i.e. "==" equality, ">" greater than.
For example,
var x = 1, y = 3, sum = 0;
if ( sum == 0 ) {
sum = x + y;
}
This bit of code first checks to see if sum is equal to zero, and if so then it adds x
and y together and assigns the result to sum. The "if" statement is an example of a
control structure which we will examine shortly.
18 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
JavaScript Operators
Computational
These are probably the most common operators. They are used for
common mathematical operations.
Unary negation ( - )
Increment ( ++ )
Decrement ( -- )
Multiplication ( * )
Division ( / )
Modulo arithmetic ( % )
Addition ( + )
Subtraction ( - )
Logical
These operators are very commonly used in conditional statements like “if”
and “switch” that you will be learning about shortly.
Logical NOT ( ! )
Less than ( < )
Greater than ( > )
Less than or equal to ( <= )
Greater than or equal to ( >= )
Equality ( == )
Inequality ( != )
Logical AND ( && )
Logical OR ( || )
Conditional (trinary) ( ?: )
Comma ( , )
Bitwise
You have probably heard that computers work with bits and bytes. These
operators do work with bits or zeros and ones. These operators are very
rarely used.
Bitwise NOT ( ~ )
Bitwise Shift Left ( << )
Bitwise Shift Right ( >> )
Unsigned Shift Right ( >>> )
Bitwise AND ( & )
Bitwise XOR ( ^ )
Bitwise OR ( | )
Assignment ( = )
Compound assignment operators
Addition (+=)
Subtraction (-=)
Multiplication (*=)
Division (/=)
Modulo Arithmetic (%=)
Left Shift (<<=)
Right Shift (>>=)
Unsigned Right Shift (>>>=)
Bitwise And (&=)
Bitwise Or (|=)
Bitwise Xor (^=)
20 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Control Structures (Loops and Branches)
Branches
if
The "if" statement is a fundamental control statement. It allows your program to
perform a test, and act based on the results of that test. For example:
if ( (x == 1) && (y == 3) ) {
sum = y - x;
}
In this statement the value of the x variable is compared to 1 to see if it is equal, and
the value of the y variable is compared with 3 to see if it is equal. The use of the
"&&”, which is the “and” operator, adds an additional logical condition that says that
the first comparison must be true and the second comparison must be true for the
overall result of the test to be true. If the test results in an overall true condition then
the statements that follow the if statement will be executed. If the test results are
false nothing will occur.
An additional clause you can add to the "if" statement is the "else", an example:
if (sum == 0) {
sum = x + y;
}
else {
subtotal = sum;
}
This statement is read as: if sum equals 0 then sum equals x plus y, or else
subtotal equals sum.
The switch statement is handy when a variable may take on a number of values
and you want to test for some of those values. The use of “switch” is shorter and
easier to read than a number of "if" statements.
switch(n) {
case 1: //start here if n equals 1. //
place code here
break;
22 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Loops
A loop is a programming structure that forces the statements contained within its
delimiters to execute over and over again until a condition is met at which point the
loop ends.
while
While a condition is true, execute one or more statements. “While loops” are
especially useful when you do not know how many times you have to loop, but
you know you should stop when you meet the condition.
var x = 1;
while ( x <= 10 ) { // loop until x is greater than 10
until x is greaterthan 10
for
“For loops” are useful when you know exactly how many times you want the loop to
execute.
var x;
for ( x = 1; x <= 10; x++ ) { // loop while x is <= 10
Built-in:
The built in functions are there to perform a number of actions that programmers
expect to be part of a programming language. Some of the built in functions include:
parseFloat(string value), parseInt(string value), isNaN(value), etc.. We will use
these functions later in the course.
Programmer Created:
Functions that you create start with the command “function” and are followed by the
name for the function. For example:
} // end of function
Usually the name is an indicator of the action the function is going to provide such as
“checkForm”. The name is followed by a set of parenthesis and inside the
parenthesis there can be a number of arguments. Arguments are the variable names
that will be used for values (data) being passed to the function.
24 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
All functions have the ability to pass back a value through the return statement.
Another way of saying this is you can pass data into a function using its
arguments, and get the results out with a returned value. Functions can only return
one value. In the example below the sum of two numbers is returned by the
add_two_num() function.
function add_two_num( a, b) {
var sum = a + b;
return sum;
} // end of function add_two_num
function mainProgram() {
var x = 5, y = 3, total = 0;
total = add_two_num( x , y );
alert(total); // display the value of total
}
1. The function mainProgram declares variables and assigns their initial values
as follows - “x” equal to 5, “y” equal to 3 and “total” equal to 0
2. Then it calls the add_two_num function and passes in the values of x and y.
3. In the add_two_num function the values are added together and stored in a
variable named sum.
4. The value of sum is returned back to the mainProgram function and stored in
the variable named total.
5. The value of total is then displayed to user in an alert box.
Variables declared in a function are only available while within that function’s
braces { }. These are commonly referred to as local variables. Another type of
variable is a global variable. Global variables are available to all functions, and
should be used with caution, as it is easy to assign the wrong value to a global
variable. In the above example globalVar is a global variable because it is
declared outside of all of the functions.
5. Create an if structure that will make sure the value of the p variable is greater
than or equal to 99, and if so set the total equal to the value of p.
6. Create a function that will multiply two numbers together and return the result.
26 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Summary
Objectives
1. Objects
4. Arrays
5. Events
i. onClick
ii. onSubmit
iii. onMouseOver
iv. onMouseOut
v. onFocus
vi. onChange
vii. onBlur
viii. onLoad
ix. onUnload
28 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Objects
var x = StringVar.length;
StringVar = StringVar.toUpperCase();
If this code is executed StringVar is a new variable with the value of "This is a string
of characters.". The x variable is set to the length of the StringVar, in this case 31.
Length is a property of the string object. If you count the characters (letters, spaces,
and punctuation) between the quotes you will see that it adds up to 31. The
toUpperCase() method converts all of the alpha characters in the string to upper
case i.e. "THIS IS A STRING OF CHARACTERS.".
JavaScript has the following objects built into the language: String, Math, Date and
Array. The string object has a number of methods for manipulating strings as
demonstrated above with the toUpperCase() method. The math object is a collection
of methods and properties for performing mathematical operations like: min(), max(),
sin(), cos(), etc.. The date object is a collection of methods for working with dates
and time. The array object allows programmers to create collections of data. Arrays
will be discussed shortly.
o = new Object();
Since objects are made up of methods (functions) and parameters (variables), the
newly created object "o" in this case has all of the same methods and parameters
of the original Object. The parameters will all be set to their default value. Arrays
will be covered shortly.
The browser provides us with a series of objects. The browser window that the
page is displayed in is known as the window object. The HTML page displayed by
your browser is known as the document object. The document object is probably
the most commonly used object in client-side JavaScript.
The HTML elements that you add to a page also extend the object hierarchy. An
example is the FORM element and the elements that reside inside the form. This
means that you can reference these objects, as illustrated in the HTML page
below:
window.document.forms[0]
Refers to the first form in the document. Forms are implemented as arrays in
the DOM. If there is more than one form on page the numbers will start at
zero and go up.
window.document.Form1
Refers to the form by name Form1
window.document.Form1.FirstName.value
Refers to the value typed into the textbox named FirstName by the client, in
the form named Form1
<HTML>
<HEAD>
<TITLE>Simple Form</TITLE>
</HEAD>
<BODY>
<FORM NAME="Form1">
Name: <INPUT TYPE="TEXT" NAME="FirstName"><BR>
<INPUT TYPE="Button" VALUE="Submit Info" >
</FORM>
<FORM NAME="Form2">
Name: <INPUT TYPE="TEXT" NAME="LastName"><BR>
<INPUT TYPE="Button" VALUE="Submit Info" >
</FORM>
</BODY>
</HTML>
30 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Objects located in the current document, in the current window can drop the
reference to those two objects. For example:
forms[0]
refers to the first form within this document
Form1
refers to the form named Form1 in this document
Form1.FullName.value
refers to the value typed, in the browser by the client, into the textbox
named FullName, in the form named Form1, in this document
We recommend that you use the NAME attribute of any HTML tag that you are
going to script, as in the above example the form is named Form1. This practice
will simplify object naming for you.
plugins[]
array of Plugin Objects
navigator
Navigator Object mimeTypes[]
array of MimeType objects
frames[]
array of Window objects elements[]
The Current
array of HTML Form
Window element objects:
history
History Object links[]
array of Link objects
images[]
array of Image objects
document
Document Object applets[]
array of applets
embeds[]
array of embedded objects
32 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Arrays
Each position in the array is assigned an index number beginning with 0 for the first
position, 1 for the second position, and so on. This allows any position within the
array, or “element” of the array, to be referenced by its index number.
The index of the array is indicated by the number contained within the square
brackets. An array is implemented as an object in JavaScript and can be created
using the “new” statement.
Events are the triggers that call (start) one of your functions. Your client-side
JavaScript programs will not execute (run / be interpreted) unless started by an
event. An event could be an action such as clicking on a button or placing your
mouse over an image. We will use the onClick event for starting our form
validation scripts, and the onMouseOver event for creating graphic images that
change when you place your cursor over them.
onClick( )
A click event occurs when a button, checkbox, radio button, reset button, or
submit button is clicked. This event is regularly used with a button to start
script execution.
In the above example when you click on the button "Click Me" it will execute
the JavaScript statement "window.alert('You Clicked me');". You can call
any function or method this way.
onSubmit( )
A submit event occurs when the user submits a form. This event is
regularly used with a form and a submit button to start the form validation
script.
<FORM action="http://www.xnu.com/formtest.asp"
onSubmit="return checkform();">
In the above example when the user clicks on the submit button, it will
execute the function "checkform()". If the form passes all the validation tests,
a true value is returned and the data will be passed to the "formtest.asp" CGI
program. If the form contents do not pass the validation tests, it will not send
the data to the "formtest.asp" CGI program.
Note: We will be using these events in our discussion of Alerts, Prompts, and
Confirmations; as well as, for Form Validation.
34 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
onMouseOver( )
An onMouseOver event occurs when the user positions their mouse over a
hyperlink, or a linked region of a client-side image map.
<a href="http://synergy.simplenet.com/simpsons/"
onMouseOver="window.status='The best Simpsons Webpage on the
NET!'; return true;">Click for information on the Simpsons.</A>
In the above example an HTML link to a web site is created using the
anchor tag. The onMouseOver() event is added to the anchor tag, and in
this case the script will put a message in the status line of the browser
window. Take a look at the results below.
onMouseOut( )
An onMouseOut event occurs when the user moves their mouse off of a
hyperlink, or a linked region of a client-side image map.
<a href="http://synergy.simplenet.com/simpsons/"
onMouseOut="window.status='The best Simpsons Webpage on the NET!';
return true;">Click for information on the Simpsons.</A>
This example is the similar to the one above, except when the mouse is
over the link, the hyperlink URL is shown in the status line, and when the
mouse is moved off the hyperlink the message is displayed.
Note: We will be using these events in the Chapter on using Mouse Roll-overs.
In this example when the user clicks on the month box or tabs into it a
message is displayed in the status line of the browser that indicates what
the user should type in.
onChange( )
The change event happens when the user leaves a password, text, textarea
or FileUpload field in an HTML form, and its value has changed.
onBlur( )
The blur event triggers when the user leaves a password, text, textarea or
FileUpload field in an HTML form.
Note: It is usually a good idea to use either onChange or onBlur, and not both at
the same time as they will appear to conflict with one another.
36 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
onLoad( )
The load event triggers when the browser finishes loading a document or all
the frame pages within a <FRAMESET>.
In this example after the page has completed loading into the browser the
alert message below is popped up.
onUnload( )
The unload event occurs when you move to a new document. For example
if you use the back button, or click on a link to another page the unload
event will occur.
This example will popup the following message when someone moves off of
the current page.
Note: It is possible to specify multiple events on a single HTML tag. For example,
<a href="http://synergy.simplenet.com/simpsons/"
onMouseOver="mouse1.src='gifs/mouse_over.gif'; "
onMouseOut="mouse1.src='gifs/mouse_out.gif'; ">
38 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Review Questions
2. The four objects that are built into the JavaScript language are:
i.
ii.
iii.
iv.
4. (True or False) Events are key to beginning the execution of your scripts.
5. Which event would you use to start a script after a page has been fully loaded
by the browser?
a. onClick()
b. onSubmit()
c. onLoad()
d. onMouseOver()
e. onload()
7. Name four (4) objects within the "document object" of the DOM.
8. What is an array?
40 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
5
Alerts, Prompts, and Confirms
Objectives
1. Creating Alerts
2. Creating Prompts
3. Creating Confirms
window.alert("Hello Gary!");
The above line of code would produce the following popup window.
window.prompt( message, default) The “message” is again plain text that will
be displayed in the dialog box popped up over the window, and the default is
a string that is displayed as the default input. When default is set to "", nothing
will be in the prompt box. The prompt window will have an input field for the
user to enter information and an “OK” button and a “Cancel” button. This
method will return the value that the user types in.
42 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
window.confirm( question ) The question is another plain text string. It
should be a question that you want answered by the user.
If the user clicks on the OK button the method will return a Boolean value of
true. If however the user clicks on the cancel button the method will return a
Boolean value of false. These return values can be stored in a variable like
ageTest and used with branching logic.
for this section will demonstrate using all three window methods.
<HTML>
<HEAD>
<TITLE>Simple Form</TITLE>
</HEAD>
<BODY>
<FORM NAME="Form1">
Name: <INPUT TYPE="TEXT" NAME="Name"><BR>
<INPUT TYPE="Button" VALUE="Submit Info">
</FORM>
</BODY>
</HTML>
At this point the form will do nothing when the “Submit Info” button is pressed.
What we will first do is use the onClick event on the button to popup an alert
message that says Hello "The name typed in" followed by an exclamation mark.
To make this button function we need to add the onClick event to our HTML
page.
44 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
<INPUT TYPE="Button" VALUE="Submit Info"
onClick="window.alert('Hello ' + document.Form1.Name.value + '!');">
This says when the user clicks on the button, the browser will create an alert (the
popup). Alert is a method of the window object. In this case the string 'Hello ' will be
concatenated with the data typed in by the user in the textbox and
concatenated with the exclamation mark. Single quotes are used to delimit the
strings in this example because the HTML code requires the double quotation marks
as delimiters of the attribute onClick. Remember our discussion of syntax; the
JavaScript statement must end with a semicolon.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
function do_stuff() {
var flag=false, fullName;
// If the user does not confirm that their name is correct the user if //
the user is given a chance to re-enter it.
if (flag == false) {
fullName = prompt('Please re-enter your name','');
}
}
// Display a custom message to the user
alert(fullName + ', welcome to our website!');
}
</BODY>
</HTML>
46 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Review Questions
1. What are the predefined, popup style, dialogue boxes we can use with
JavaScript?
2. Which type of dialogue box would you use if you want the user to enter
some information?
3. What is concatenation?
48 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
6
Creating Effective Forms
Objectives
1. Creating a FORM with an Active Cursor
4. Creating a function
6. Testing
When a web page, containing a FORM element, loads in the browser there is no
default condition that places the cursor inside the first input element. If the user just
starts to type, nothing happens because the cursor is not active, anywhere in the
document in the browser.
Many authors that create forms for use on the web would like to have the cursor
placed and active in the first input field. It would mean that a person browsing
wouldn’t have to click in the field before entering data; they could simply begin to
type.
FORM elements of the type text, password, textarea and file upload support, not
only events such as onClick and onBlur but they also support the methods of
“focus” and “blur”. This means that you can tell the cursor to be placed in the
input field or that it can’t be placed in specified fields. If you combine this feature
with the page’s onLoad event you can place the cursor in a designated field
when the page loads.
<HTML>
<HEAD>
<TITLE>Simple Form</TITLE>
</HEAD>
<BODY onLoad=”document.CardForm.HoldersName.focus()”>
</BODY>
</HTML>
50 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Using Form Checking
Form validation is accomplished by using JavaScript to preprocess the
information the user types into a form before the data is sent to a CGI based server
application. This practice is more efficient than allowing incorrectly formatted data to
be sent to the server. If the information is incorrectly formatted you can alert the
user with a pop-up and force them to correct the mistake. Form validation is one of
the most common uses of JavaScript.
<HTML>
<HEAD>
<TITLE>Simple Form</TITLE>
</HEAD>
<BODY onLoad=”document.CardForm.HoldersName.focus()”>
</BODY>
</HTML>
Lets start by adding our required script tags and comments; as well as, creating a
new function called checkform.
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
function checkform() {
}
//end hiding of JavaScript code -->
</SCRIPT>
The function checkform() does not currently have any instructions to execute. We
will add these shortly. In order to call this function we will add the following onSubmit
event to the FORM HTML tag.
onSubmit="return checkform();"
Now when someone clicks on the Submit Info button it will first execute the
checkform() function before sending the information to the web server for
processing. Note the we are using the “return” property, associated with the
“checkform” function, which looks for a value of true or false from the associated
function. If checkform() returns a value of true, then the form contents will be
submitted to the CGI script, on the server, for processing. If checkform() returns a
value of false the contents will not be submitted and some other action may be
initiated such as an alert.
52 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
The next piece of code we will add is a string variable named "message" that will
hold the contents of the error message to be displayed to the user as an alert. We
will also add an "if" structure that will test for the length of the error message. If the
"message" variable's length is greater than zero then an alert message should be
displayed, if it is zero then the information is correct and should be sent to the server
for processing.
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
function checkform() {
var message = "";
if ( message.length > 0 ) {
alert( message );
return false;
}
else {
return true;
}
Now that we have this structure in place we can create our first real test of our
form. Lets check to see if the length of the card holder's name is greater than
zero.
if (document.CardForm.HoldersName.value.length == 0) {
message = message + "Please enter the name on the credit card!\n";
}
This statement appears complex at first, but lets step through it to see how it
works. The “if” is testing the value typed into the HoldersName field of our HTML
FORM named CardForm that is in the document. This accurately references the
object’s value, the .length will return the length of the number of characters in the
string. If the length is equal to zero we know that the user has typed nothing in,
and we should create an error message. Creating the error message is the
purpose of the next line. The error message we want to display is "Please enter
the name on the credit card!" The \n at the end of the line will cause a carriage
return and a linefeed so that the next error message will display on a new line
inside the same alert box. We know that we will be testing each field for a correct
value so we may have a different error message associated with each test. We
add the current value of the message variable using the (+) concatenation
operator and store the result back in the message variable using the (=)
assignment operator.
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
function checkform() {
var message = ""; // create error message string variable, with nothing in it
if (document.CardForm.HoldersName.value.length == 0) {
message = message + "Please enter the name on the credit card!\n";
}
if (document.CardForm.CardMonth.value.length < 2) {
message = message + "Please type in both digits of the expiry month!\n";
}
if (document.CardForm.CardYear.value.length < 2) {
message = message + "Please type in both digits of the expiry year!\n";
}
Note: You will notice that we have added comments to some of the code. This is
great for remembering what something is doing down the road. Commenting also
makes it easier for others to understand your code.
54 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
if (document.CardForm.CardMonth.value.length < 2) {
// test to make sure two characters where entered
message = message + "Please type in both digits of the expiry month!\n";
}
else if (isNaN(document.CardForm.CardMonth.value)) {
// test for numeric digits only
message = message + "The Month value needs to be between 1
and 12\n";
}
else if (document.CardForm.CardMonth.value < 1 ||
document.CardForm.CardMonth.value > 12 ) {
// test the values to make sure they are not less than 1 or
// greater than 12
message = message + "The Month value needs to be
between 1 and 12\n";
}
The above code segment is built upon our length test. Now that we know we have
two characters we must check to see that they are numeric. Once that has been
determined we need to check to make sure the numeric values are within the range
we are interested in.
We use a new function in the code segment; isNaN(), which means " is Not a
Number". “isNaN() will return a value of true if the string being evaluated is not a
number, or it will return a value of false if the string being evaluated is made up of
only numeric digits.
We use the operators < "less than", > "greater than", and || "or". So the last
expression is read as follows; “if the value is less than one or greater than 12
then display an error message.”
Once you have added this code to your web page, you can test all of the
conditions with the following inputs: blank, aa, 1, -1, 13, and 06.
Then we add similar lines to setup the test for a valid year. Use 99, 98, 00 for test
values. As you can tell, your script is not year 2000 compliant.
Add the necessary lines to test for 16 digits in the card number. Test with the
following inputs: 123456789abcdefg, 123456789, 1234567890123456.
function checkform() {
var message = ""; // create error message string variable, with nothing in it
</HEAD>
56 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
<BODY onLoad="document.CardForm.HoldersName.focus()">
</BODY>
</HTML>
1. What event was used to place the cursor in the first field of our FORM?
2. What did we test to see if the user had entered any information into
any of the fields?
4. How do we get the next error message to appear on the next line
down?
58 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Summary
4. Create a function
5. Add checks
Objectives
1. The image object
2. Mouse-over
4. Pre-loading images
60 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Image Object
When you add the HTML tag <IMG> to your web page you are creating an image
object. For example:
<IMG SRC="gifs/mouse_out.gif">
document.images['imagename'].property = newvalue;
border
This value can only be read, and is the width of the border around
the image specified in pixels by the BORDER attribute.
complete
This value can only be read, and is a Boolean value that will let you
know if the image has completed downloading (true) or not (false).
height
This is a read only value that specifies the height in pixels of image set
by the HEIGHT attribute.
hspace
This is a read-only value, and refers to the space on the right and
left of the image specified in pixels by the HSPACE attribute.
lowsrc
This is a read/write string that specifies a URL of an alternate image.
The image should be suitable for display at low resolutions; it is
specified by the LOWSRC attribute.
name
This is a read-only value, specified by the NAME attribute. As you
will see it is a good idea to name your images.
src
This is a read/write string that specifies a URL of the image.
Since we can read and write to the src property, we can change the image that is
displayed in the browser. This is what allows us to create mouse roll-over,
sometimes called hover buttons, when used in combination with the <A> element in
creating links.
Mouse-over
In the mouse rollover script that we will create, we will be changing the src
property of the appropriate image object when the onMouseOver and
onMouseOut events are triggered. We will start with a very basic and simple
implementation and then add to it to make it more flexible and powerful.
To create the effect we need two graphic images that are generally the same with a
little bit of difference for example mouse_out.gif and mouse_over.gif, both located in
the \gifs subdirectory of your student files.
The following HTML page codes with the addition of the JavaScript events will
change the image when the user positions their mouse over the image and
change it back again when they move their mouse off the image. The image is
originally set to the mouse off image using the <IMG> tag.
<HTML>
<HEAD>
<TITLE>Mouse Over and Mouse Out</TITLE>
</HEAD>
<BODY>
<a href="http://synergy.simplenet.com/simpsons/"
onMouseOver="mouse1.src='gifs/mouse_over.gif'; "
onMouseOut="mouse1.src='gifs/mouse_out.gif'; ">
<IMG name="mouse1" src="gifs/mouse_out.gif" border=0></A>
</BODY>
</HTML>
62 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Creating Flexible Functions
To improve our mouse over script we want to start by creating two function. One
that will be called when the mouse is on the image, and one that is called when the
mouse is off the image.
<HTML>
<HEAD>
<TITLE>Web Page containing JavaScript</TITLE>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
function MouseOn() {
document.images['mouse1'].src = "mouse_over.gif";
}
function MouseOff() {
document.images['mouse1'].src = "mouse_out.gif";
}
<BODY>
<a href="http://synergy.simplenet.com/simpsons/"
onMouseOver="MouseOn(); "
onMouseOut="MouseOff(); ">
<IMG name="mouse1" src="gifs/mouse_out.gif" border=0></A>
</BODY>
</HTML>
As you can see in the above code we have added two functions that do the same
thing as the inline script did in the previous example, and we have changed the
event triggers to call our new functions. This provides us with the flexibility to apply
our function to different images.
<HTML>
<HEAD>
<TITLE>Web Page containing JavaScript</TITLE>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
function MouseOn(imageName) {
document.images[imageName].src = "gifs/mouse_over.gif";
}
function MouseOff(imageName) {
document.images[imageName].src = "gifs/mouse_out.gif";
}
<BODY>
<a href="http://synergy.simplenet.com/simpsons/"
onMouseOver="MouseOn('mouse1'); "
onMouseOut="MouseOff('mouse1'); ">
<IMG name="mouse1" src="gifs/mouse_out.gif" border=0></A>
<BR>
<a href="http://synergy.simplenet.com/simpsons/"
onMouseOver="MouseOn('mouse2'); "
onMouseOut="MouseOff('mouse2'); ">
<IMG name="mouse2" src="gifs/mouse_out.gif" border=0></A>
</BODY>
</HTML>
In this example we pass the value "mouse1" or "mouse2" to our functions. This
value in turn gets stored in the variable "imageName". Next we want to focus our
attention on the string that is equated to the image name. The string
"gifs/mouse_out.gif" is not very flexible. We need to express that as:
The line above will create the correct string value for each set of images to
change.
64 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
At this point we will need four (4) graphic images; mouse1_over.gif,
mouse1_out.gif, mouse2_out.gif and mouse2_over.gif.
<HTML>
<HEAD>
<TITLE>Web Page containing JavaScript</TITLE>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
function MouseOn(imageName) {
document.images[imageName].src = "gifs/" + imageName +
"_over.gif";
}
function MouseOff(imageName) {
document.images[imageName].src = "gifs/" + imageName +
"_out.gif";
}
<BODY>
<a href="http://synergy.simplenet.com/simpsons/"
onMouseOver="MouseOn('mouse1'); "
onMouseOut="MouseOff('mouse1'); ">
<IMG name="mouse1" src="gifs/mouse1_out.gif" border=0></A>
<BR>
<a href="http://synergy.simplenet.com/simpsons/"
onMouseOver="MouseOn('mouse2'); "
onMouseOut="MouseOff('mouse2'); ">
<IMG name="mouse2" src="gifs/mouse2_out.gif" border=0></A>
</BODY>
</HTML>
Although the above example will work and create the flexibility that we require, it is
not optimized. When the browser loads this page it only loads the two mouse out
images. When the user positions the mouse over the image for the first time the
browser must download the mouse over image. This can be slow and your effect
will not display properly. The solution is to pre-load all of our images into the
browser's cache so that they can be accessed quickly.
In our previous example we only had two image objects mouse1, and mouse2
respectively. We are going to create four more, and pre-load them into our
browser's cache.
We can pre-load all four of our images files in to the browser's cache by creating four
new objects mouse1_on, mouse1_off, mouse2_on, mouse2_off. These
image objects are not displayed in the browser. We will be using them to hold the
images so that we can quickly switch between them. Let's look at an example of how
to do this:
For each image file, we create a new image object, and set its src attribute to the
appropriate filename. In setting this property, the browser decides it needs to
download the image file, at which point it is stored in the cache for quick retrieval,
when it is called for display.
Our page will now contain six image objects: mouse1, mouse1_on, mouse1_off,
mouse2, mouse2_on, and mouse2_off.
To make the image change in the browser we need to make the src attribute of the
image object created by the <IMG> tag in our case mouse1 or mouse2 equal to on
objects src or the off objects src.
We can reference the two image objects created by the HTML <IMG> tag as
follows:
document.images['mouse1'] or document.images['mouse2']
66 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
We want to be able to set those images src attribute equal to one of the other
objects src attributes.
document.images['mouse1'].src = mouse1_on.src
or
document.images['mouse1'].src = mouse1_off.src
Notice in the above example, to make it work for mouse2 we would just have to
substitute mouse2 for mouse1. So for our function we will substitute the mouse1
reference with a variable called imageName.
From earlier in the course you will know that JavaScript is going to try to
concatenate (join) the string value of the imageName variable with the other
string component to form the object name mouse1_on.src or mouse1_off.src.
eval()
We place the eval function around the concatenation like so:
The order of operations that is followed this time is that the value of the
imageName variable is concatenated with the string, to form one string like
mouse1_on.src. The eval function then converts that to JavaScript code,
meaning that it converts to the reference to the object we created in our pre
loading phase and it's src parameter. This way we are making the src parameter of
one object equal to the src parameter of another image object. This effectively flips
the object in the browser.
<HTML>
<HEAD>
<TITLE>Web Page containing JavaScript</TITLE>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
function MouseOn(imageName) {
document.images[imageName].src = eval( imageName + "_on.src" );
}
function MouseOff(imageName) {
document.images[imageName].src = eval( imageName + "_off.src" );
}
<BODY>
<a href="http://synergy.simplenet.com/simpsons/"
onMouseOver="MouseOn('mouse1'); "
onMouseOut="MouseOff('mouse1'); ">
<IMG name="mouse1" src="gifs/mouse_out.gif" border=0></A>
<BR>
<a href="http://synergy.simplenet.com/simpsons/"
onMouseOver="MouseOn('mouse2'); "
onMouseOut="MouseOff('mouse2'); ">
<IMG name="mouse2" src="gifs/mouse_out.gif" border=0></A>
</BODY>
</HTML>
68 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Testing for completion and compatibility
We should add two more pieces to our script, a test to make sure the image is
completely downloaded and to make sure that the browser supports the image
object. We will start by testing for completion.
function MouseOn(imageName) {
if( eval(imageName + "_on.complete") ) {
document.images[imageName].src = eval( imageName + "_on.src" );
}
} //end function MouseOn
We want to use the image object's complete property to test to see that the image
has been completely downloaded before we try to change to it so the user will never
see a partially loaded image. Similar to the use of the eval in the previous section,
here we want to combine the value of the imageName variable with the string
"_on.complete" to create the complete image name and property, and have
JavaScript act on the object instead of the string.
Next we will test for compatibility. We can do this very simply by testing the
browser to see whether it supports the image object. Earlier browsers like
Microsoft Internet Explorer 3.0, and earlier did not support this object. To make
your code browser proof we will add this conditional statement to our code.
We need to add this to both of our functions, and to the pre-loading piece of our
code.
<SCRIPT LANGUAGE="JAVASCRIPT">
<! -- hide JavaScript code from browsers that are not JavaScript enabled
function MouseOn(imageName) {
if (document.images) { // if browser supports images
if( eval(imageName + "_on.complete") ) { //is the image completely downloaded
document.images[imageName].src = eval( imageName + "_on.src" );
}
}
} //end function MouseOn
function MouseOff(imageName) {
if (document.images) { // if browser supports images
if( eval(imageName + "_on.complete") ) { //is the image completely downloaded
document.images[imageName].src = eval( imageName + "_off.src" );
}
}
} // end function MouseOff
<BODY>
<a href="http://synergy.simplenet.com/simpsons/"
onMouseOver="MouseOn('mouse1'); "
onMouseOut="MouseOff('mouse1'); ">
<IMG name="mouse1" src="gifs/mouse_out.gif" border=0></A>
<BR>
<a href="http://synergy.simplenet.com/simpsons/"
onMouseOver="MouseOn('mouse2'); "
onMouseOut="MouseOff('mouse2'); ">
<IMG name="mouse2" src="gifs/mouse_out.gif" border=0></A>
</BODY>
</HTML>
70 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Review Questions
1. What two events are used to create the mouse roll-over effect?
2. What properties of the image object can you read and write?
6. What would you need to add to our script to get it to work with more
than two links?
72 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
8
Pop-up Windows
Objectives
1) Pop-up windows
a) window.open method
b) window.close method
Arguments:
URL
the URL of the document to be displayed in the new window.
Name
an optional string that specifies the name property that can be used
with the target attribute.
Features
is a comma-separated list of features about the window;
alwaysLowered, alwaysRaised, channelmode, dependent,
directories, fullscreen, height, hotkeys, innerHeight, innerWidth, left,
location, menubar, outerHeight, innerWidth, resizable, screenX,
screenY, scrollbars, status, toolbar, top, width, z-lock
Replace
Optional boolean argument, that states weather the page that gets
loaded gets added to the page history in the browser. This
argument was intended for use when changing the contents of a
window.
window.close()
This method allows the user to close a window.
74 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Window Features Explained
When you create a new pop-up window you will need to turn off any window
features that you do not want displayed in the window. As well, you will need to set
the size of your new window.
status (status bar): the line at the bottom of the browser that displays
information. To display a window with no status bar, set status=no.
location: shows the URL of the page you are looking at. To turn the location bar
off, location=no.
toolbar: contains the buttons you use to move through history (back, and
forward) to stop web page loading, etc. To display a window with no toolbar, set
toolbar=no
menubar: is the bar that has all of the drop down menus. To turn the menubar off,
menubar=no.
scrollbars: are the sliders on the right hand side and bottom of a window that let
you move up or down and left or right. To turn off the scrollbars, scrollbars=no.
left, and screenX: control the window's position from the left of your screen in
pixels. Left is used by Internet Explorer and screenX is used by Navigator.
top, and screenY: control the windows position from the top of your screen in
pixels. Top is used by Internet Explorer and screenY is used by Navigator.
The following feature string sets the height to 500 pixels, width to 400, and turns off
the menubar, scrollbars, status line, and the toolbars, and positions the window at
the top of the screen one hundred pixels from the left of the screen.
window.open('height=500,width=400,menubar=no,scrollbars=no,status=no,toolb
ar=no,screenX=100,screenY=0,left=100,top=0')
It is very common to see popup windows displayed with all of the features turned
off.
<HTML>
<HEAD>
<TITLE>JavaScript Popup Window</TITLE>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
function popupwin() {
This line will create a new window, and load the file Ch8-0.htm into that window.
The name of the window is set to "popup". The window will have the following
features:
- 500 pixels high
- 400 pixels wide
- no menubars
- the scrollbars
- a status line
- the toolbars
The window will also be located zero pixels from the top of the screen and 100
pixels from the left of the screen. Remember, Microsoft Internet Explorer uses
the left and top features, while Netscape Navigator uses screenX and screenY.
76 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
If you open up the file Ch8-0.htm you will notice that we used a similar structure to
create a close window button.
<HTML>
<HEAD>
<TITLE>JavaScript Popup Window</TITLE>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
function closewin() {
window.close();
}
We can modify our script to create the document that will appear in our new
window instead of displaying a pre-made document as we did previously.
The first thing we need to modify is the window.open statement so that it does
not load a particular page. We can accomplish this by replacing the file 'Ch8
0.htm' with a single double quote mark, as illustrated:
winpopup = window.open('','popup','height=500,width=400,
menubar=no,scrollbars=no,status=no,toolbar=no,
screenX=100,screenY=0,left=100,top=0');
To create the actual HTML page that will appear in our pop-up window we need to
use the document.write() method. This method allows us to write text to the
specified document. For example:
winpopup.document.write('<HTML>\n<HEAD>\n');
This line will start the creation of our HTML document in the window identified by the
winpopup window object. We will need to create the whole HTML document like
this. For example:
winpopup.document.write('<HTML>\n<HEAD>\n');
winpopup.document.write('<TITLE>This is a popup</TITLE>\n');
winpopup.document.write('</HEAD>\n');
winpopup.document.write('<BODY>\n');
winpopup.document.write('</BODY>\n</HTML>\n');
This will create an empty document in the new pop-up window. When you are
finished writing information to the new window we should let the browser know that
nothing more is coming, we can do that with the document.close() method which
would be added after the lines above. Our code should know look like this:
function popupwin() {
winpopup =
window.open('','popup','height=500,width=400,menubar=no,scrollbars=no,status=no,toolb
ar=no,screenX=100,screenY=0,left=100,top=0');
winpopup.document.write('<HTML>\n<HEAD>\n');
winpopup.document.write('<TITLE>This is a popup</TITLE>\n');
winpopup.document.write('</HEAD>\n');
winpopup.document.write('<BODY>\n');
winpopup.document.write('</BODY>\n</HTML>\n');
78 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Now that we have the window opening and displaying an empty HTML page we
should make it do something a little more creative. We want our pop-up window to
thank our customer for purchasing a product. To start we need to add a text input
field to our form.
<BODY>
<FORM NAME="FORM1">
Please enter your name: <INPUT TYPE="TEXT" NAME="YourName"><BR>
<INPUT TYPE="BUTTON" VALUE="Popup Window" ONCLICK="popupwin();">
</FORM>
</BODY>
To get "Mr. JavaScript" to display in our window we need to add the following line to
our script:
This line will combine the strings with the value typed in by the user, and should be
located in your script between the lines that write the BODY tags.
We should also give our user the ability to close this newly created pop-up
window. To accomplish this we will add the following lines after the one above.
winpopup.document.write('<FORM NAME="FORM1">\n');
winpopup.document.write('<INPUT TYPE="BUTTON" VALUE="Close Window"
ONCLICK="window.close();">\n');
winpopup.document.write('</FORM>\n');
This will create a button called "Close Window" that when clicked will close the
current browser window.
When you use popup windows there are some additional properties you may
want to control. The document object has properties that allow you to set the
document's background color and the default color for text in the document.
The background color can be changed at any time. This allows you to create
some interesting effects in your popup window. The text color can only be set
once after the body tag has been written to the document (see the completed
code). An example of using these properties is below.
80 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Complete Script
<HTML>
<HEAD>
<TITLE>JavaScript Popup Window</TITLE>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- hide JavaScript code from browsers that are not JavaScript enabled
function popupwin() {
winpopup = window.open('','popup','height=500,width=400,menubar=no,
scrollbars=no,status=no,toolbar=no,screenX=100,screenY=0,left=100,top=0');
winpopup.document.write('<HTML>\n<HEAD>\n');
winpopup.document.write('<TITLE>A Dynamic Popup Window</TITLE>\n');
winpopup.document.write('</HEAD>\n');
winpopup.document.write('<BODY>\n');
</BODY>
</HTML>
3. (True or False) You can not control the size of a popup window?
4. (True or False) It is not common to see popup windows displayed with all of
the features turned off.
82 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Summary
84 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Array(s):
An array is a collection of data that is associated with a single variable
name. Each piece of data is considered a value and is indexed
numerically within the array.
Comment(s):
Comments are often used by programmers as a means of documenting
their program logic so that when they return to update it, or someone else
needs to edit it, they can understand what the programmer was doing at
the time.
Delimiter(s):
These are the brackets, quotations etc. that surround pieces of code.
Examples of delimiters are “ ”, { }, ( ), [ ]. A start delimiter such as ( must be
accompanied by a closing delimiter such as ).
Event(s):
These are the ‘triggers’ that initiate (start) one of your functions. ClientSide
JavaScript will not run unless it is ‘called on’ by an event. Examples of
events can include, clicking on a form’s submit button or moving your cursor
over an image that is a hyperlink.
Expressions:
Expressions are a set of statements that, as a group, evaluate to a single
value. JavaScript then categorizes this resulting value as one of the five data
types: number, string, logical, function, or object.
Function(s):
Functions are an important part of programming as they enable you to
create chunks of code that perform specific tasks. In JavaScript, functions
are referred to as ‘subroutines’ or ‘procedures.’ JavaScript has several
built-in functions, but you can also create your own functions for your
programs.
Literals:
Literals are data comprised of numbers or strings used to represent fixed
values in JavaScript. They are values that do not change during the
execution of your scripts.
Method(s):
A method is a function that has been encapsulated in an object.
Object(s):
An object is a collection of variables and functions. JavaScript has four
built-in objects including String, Date, Math and Array.
Statement(s):
A statement is a complete line of JavaScript code.
Syntax:
A set of rules and guidelines used for writing in any language. Each
programming language has its own set of rules and conventions. If you do
not comply with the language’s syntax, your programs or scripts will not work
correctly - if at all.
Variable(s):
A variable is a name assigned to a location in a computer’s memory to store
data. Variables must be declared in your programs and can be identified by
the fact that they are proceeded by the keyword ‘var’. JavaScript, unlike
other programming languages, can hold different data types as variables
without declaring the type.
Local Variable(s):
These are variables that are only available within a specific function’s
braces.
Global Variable(s):
These are variables that are available to all functions. Global variables
should be used with caution, as it’s easy to assign the wrong value to a
global variable.
86 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
A
Answer Appendix
3. (True or False) JAVA and JavaScript were created by the same company.
88 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Chapter 2 - Answers
if ( z[0] == 0 ) {
x = 2;
}
10. True or False. It is a good idea to add comments to your program code.
5. Create an if structure that will make sure the value of the p variable is greater
than or equal to 99, and if so set the total equal to the value of p.
if ( p >= 99 ) {
total = p;
}
6. Create a function that will multiply two numbers together and return the result.
function multiplyTwoNum( m, n ) {
var total;
total = m * n;
return total;
}
or
90 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Chapter 4 - Answers
2. The four objects that are built into the JavaScript language are:
i. String
ii. Date
iii. Array
iv. Math
4. (True or False) Events are key to beginning the execution of your scripts.
5. Which event would you use to start a script after a page has been fully loaded
by the browser?
a. onClick()
b. onSubmit()
c. onLoad()
d. onMouseOver()
e. onload()
1. What are the predefined, popup style, dialogue boxes we can use with
JavaScript?
a. window.popup()
b. window.confirm()
c. window.prompt()
2. Which type of dialogue box would you use if you want the user to enter some
information?
window.prompt()
3. What is concatenation?
92 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Chapter 6 - Answers
1. What event was used to place the cursor in the first field of our FORM?
onFocus event is used to put the cursor in the first field of the form. It
is used in our example in conjunction with the onLoad event.
2. What did we test to see if the user had entered any information into any of the
fields?
We tested to see if the length of the string typed in by the user was
greater than one character.
The return sends a value back to the statement that invoked it. When a
function is done it can send only one value back, this is done through
the return statement.
4. How do we get the next error message to appear on the next line down?
The isNaN() (is not a number) function is used to test a string to see if
it only contains numbers.
1. What two events are used to create the mouse roll-over effect?
onMouseOver
onMouseOut
2. What properties of the image object can you read and write?
src (source)
lowsrc (low res source)
complete
So that we can quickly switch between the two image objects when
the user is moving their mouse pointer over and off the image.
6. What would you need to add to our script to get it to work with more than two
links?
The only thing you need to add to the script is some new image
objects for the additional links. The logic section does not need to
updated.
94 OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net
Chapter 8 - Answers
window.open()
window.close()
3. (True or False) You can not control the size of a popup window?
4. (True or False) It is not common to see popup windows displayed with all of
the features turned off.
Functions, eval() 67
A Functions, Flexible 63
alert 42 Functions, programmer created 24
Arrays 33 I
B if 21
Brackets 10 Image, Object 61
Branches, if 21 Images, Pre-loading 66
Branches, Switch 22 Interpreted 2
C J
Case-sensitivity 8 JavaScript vs. JAVA 2
Checking, forms 51 JavaScript, about 3
Closing windows 74 JavaScript, inserting into an HTML
Comments 11 Page 7
Compiled 2 JavaScript, Syntax 8
complete 69 L
confirm 43
Cursor, positioning 50 Loops, for 23
Loops, while 23
D
M
document.bgColor 80
document.fgColor 80 Mouse over script 70
document.write() 78 Mouse-over 62
DOM 30 N
E new 29
eval() 67 O
Events 34
Events, onBlur 36 Object, Array 33
Events, onChange 36 Objects 29
Events, onClick 34 Objects, document 78, 80
Events, onFocus 36 Objects, Image 61
Events, onLoad 37 onBlur 36
Events, onMouseOut 35, 62 onChange 36
Events, onMouseOver 35, 62 onClick 34
Events, onSubmit 34 onFocus 36
Events, onUnload 37 onLoad 37
onMouseOut 35
F onMouseOver 35
for loops 23 onSubmit 34
Form checking 51 Opening windows 74
Forms 50 Operators, a list 19
Function Names 12 Operators, new 29
Functions 24 Operators, Using 18
Functions, built-in 24
ii OLM World Class Web Hosting E-commerce and Custom Internet Solutions hosting.olm.net