JavaScript Basics and Usage Guide
JavaScript Basics and Usage Guide
Client-Side Scripting
Using JavaScript
1
The contents to be covered are:
Introduction to JavaScript
JavaScript Syntax
JavaScript operators
JavaScript Data Types
JavaScript Pop-up boxes
Alert, confirm and prompt.
Conditional and switch statements, loops and functions
Event handling
Form validation/processing
2
WHAT IS JAVASCRIPT?
JavaScript was designed to add interactivity to HTML pages
JavaScript is a scripting language i.e. lightweight programming
language
A JavaScript is usually embedded directly in HTML pages
It is an interpreted language (means that scripts execute without
preliminary compilation)
Converts code to executable format each time it runs
Converted when browser loads a web document
3
JavaScript is supported by all major browsers
3
JAVASCRIPT VS. JAVA
4
JAVASCRIPT VS. JAVA (2)
JavaScript Java
variable data types not declared variable data types must be declared
(loose typing) (strong typing)
dynamic binding (object static binding (object references must
references checked at run-time) exist at compile-time)
security: cannot write to hard security: multilevel control
disk graphics library (AWT), threads,
no graphics library, no threads, networking (sockets, RMI, etc.)
no networking 5
5
USES OF JAVASCRIPT
Gives HTML designers a programming tool
HTML authors are normally not programmers, but JavaScript is a
scripting language with a very simple syntax!
Almost anyone can put small or "snippets" of code into their HTML
pages
A JavaScript can be set to execute when something happens, like when
a page has finished loading or when a user clicks on an HTML element
Can read and write HTML elements
Can be used to validate data (e.g. form data) before it is submitted to a
6
server
6
USING JAVASCRIPT IN HTML
3. In javascript:
7
SIMPLE JAVASCRIPT PROGRAM
FileName: [Link]
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
// This is a comment in JavaScript
[Link]("<h1>Hello folks!</h1>");
</SCRIPT>
</HEAD>
<BODY>
Welcome to this class!
</BODY>
8
</HTML>
8
WRITE METHOD
[Link] directs the document object to write
the given string
Examples: Concatenate the strings and number
together and write the resulting
<script>
string out
counter = 10;
[Link]("<h1>Counter is "+counter+"</h1>");
</script>
<script>
[Link]("<IMG SRC=‘[Link]’>"); // notice the use of “ and ‘
</script>
9
HIDING JAVASCRIPT CODE (FROM OLD BROWSERS)
1. To prevent old browsers from displaying your JS code, you can do the following:
• Immediately after opening <script> tag, put a one-line HTML-style comment
without the closing characters, so that the first two lines of your script would
look like this: <script type="text/javascript" language="JavaScript"> <!--
2. At the end of your script, put the following two lines: //--> </script>
• Thus, your HTML file will contain the following fragment: <script
language="JavaScript"> <!-- Here you put your JS code. Old browsers will
treat it as an HTML comment. //--> </script>
10
10
NOSCRIPT TAG
Use the <NOSCRIPT> tag to specify alternate content for browsers that do not support JavaScript.
HTML enclosed within a <NOSCRIPT> tag is displayed by browsers that do not support
JavaScript.
The following example shows a <NOSCRIPT> tag.
<NOSCRIPT>
<B>This page uses JavaScript, so you need to get a newer version of IE or Netscape!
<BR>
<A HREF="[Link]
<IMG SRC="[Link]"></B>
If you are using Navigator 2.0 or later, and you see this message, you should enable JavaScript by
on the Advanced page of the Preferences dialog box.
</NOSCRIPT>
11
11
Adding JavaScript
• There are three ways to add JavaScript commands to your Web Pages.
I. Embedding code
II. Inline code
III. External file
I. External File
• If you want to run the same JavaScript on several pages, you can write a JavaScript in an
external file.
• Save the external JavaScript file with [Link] file extension.
12
Adding JavaScript…
16
Simple JavaScript Pop-up Boxes
alert
17
17
<!DOCTYPE html>
confirm <html>
<body>
A confirm box is often used if you want the user
<h2>JavaScript Confirm Box</h2>
to verify or accept something. When a confirm <button onclick="myFunction()">Try it</button>
box pops up, the user will have to click either <p id="demo"></p>
"OK" or "Cancel" to proceed. If the user clicks <script>
"OK", the box returns true. If the user clicks function myFunction() {
var txt;
"Cancel", the box returns false. if (confirm("Press a button!")) {
Syntax: [Link]("sometext"); txt = "You pressed OK!";
The [Link]() method can be written } else {
without the window prefix. txt = "You pressed Cancel!";
}
Example
[Link]("demo").innerHTML = txt;
if (confirm("Press a button!")) { }
txt = "You pressed OK!"; </script>
} else { </body>
txt = "You pressed Cancel!"; </html>
18
Simple JavaScript Pop-up cont….
eval
<!DOCTYPE html>
<html>
eval() is a global function in JavaScript <body>
that evaluates a specified string as <h1>Demo: eval</h1>
<script>
JavaScript code and executes it.
var result;
Itevaluates a string and
function Sum(val1, val2)
returns a value. {
Syntax: return val1 + val2;
}
eval(stringExpression)
eval( "result = Sum(5, 5);");
Example: eval(1+2*3) // gives
7 here alert(result);
</script>
</body>
</html> 19
19
prompt <!DOCTYPE html>
<html>
A prompt box is often used if you want the user <body>
to input a value before entering a page. <h2>JavaScript Prompt</h2>
<button onclick="myFunction()">Try it</button>
When a prompt box pops up, the user will have <p id="demo"></p>
<script>
to click either "OK" or "Cancel" to proceed after function myFunction() {
entering an input value. var txt;
var person = prompt("Please enter your name:", "Harry
If the user clicks "OK" the box returns the input Potter");
if (person == null || person == "") {
value. If the user clicks "Cancel" the box returns txt = "User cancelled the prompt.";
null. } else {
txt = "Hello " + person + "! How are you today?";
Syntax }
[Link]("demo").innerHTML = txt;
[Link]("sometext","defaultText"); }
The [Link]() method can be written </script>
</body>
without the window prefix. </html>
20
DATA TYPES
Numbers
1, 3.14159, -99
Logical (Boolean) values
true or false
Strings
“hello”, ‘hello’,
null
special keyword denoting null value
21
21
STRING LITERALS
A string literal is zero or more characters enclosed in double (") or
single (') quotes.
A string must be delimited by quotes of the same type; that is, either
22
22
VARIABLES
We use variables to hold values in our application.
Syntax:
var myVar; // var => local variable; Otherwise, the variable is global
23
23
VARIABLES
More Syntax
var Variablename = value;
var x = 3;
var x, y = 0;
var x = null;
24
24
VARIABLE NAMES
A JavaScript identifier or name must start with a letter or underscore
("_"); subsequent characters can also be digits (0-9). Letters include
the characters "A" through "Z" (uppercase) and the characters "a"
through "z" (lowercase).
JavaScript is case-sensitive.
Some examples of legal names are:
Last_Name
status
_name
25
25
OPERATORS
Arithmetic
+ (Addition, String Concatenation)
- (Subtraction, Unary Negation)
* (Multiplication)
/ (Division)
% (Modulus) (e.g., 7 % 3 gives 1)
++ (Preincrement, Postincrement) // increments a variable by 1
e.g., x = 1; alert(x++); alert (x) // displays 1, then 2
e.g., x = 1; alert(++x); alert (x) // displays 2, then 2
-- (Predecrement, Postdecrement) // decrements a variable by 1
e.g., x = 1; alert(x--); alert (x) // displays 1, then 0
e.g., x = 1; alert(--x); alert (x) // displays 0, then 0
26
26
OPERATORS (CONT...)
Assignment Operators
= means assignment
PI = 3.14159; // var PI is assigned 3.14159
Op= (where op is one of +, -, *, /, etc.)
x += y means x = x + y
x *= y means x = x * y
x -= y means x = x - y
x /= y means x = x / y
27
27
OPERATORS (CONT...)
Relational Operators
==, != (Equality, Inequality)
<, <=, =>, > (Arithmetic and String Comparison)
! (Logical Not)
&&, || (Logical AND, Logical OR)
?: (Conditional Selection)
e.g., x = (1 < 5)? ‘a’:’b’; // here, x gets ‘a’
28
28
OPERATOR PRECEDENCE
The precedence of operators determines the order they are applied when
evaluating an expression. You can override operator precedence by using
parentheses.
The precedence of operators, from lowest to highest is as follows: (Partial
Listing)
assignment = += -= *= /= %=
conditional ?:
logical-or ||
logical-and &&
equality == !=
relational < <= > >=
addition/subtraction + -
multiply/divide * / %
negation/increment ! ++ --
call, member () [] . 29
29
EXPRESSIONS
An expression is any valid set of literals, variables, and
operators that evaluates to a single value.
PI = 3.14159
12 + 6
2 * PI * r
x++
x -= 3
30
30
Control Structures
The kinds of statements that make decisions and loop around to
repeat themselves are called control structures.
A control structure directs the execution flow through a sequence of
script statements based on simple decisions and other factors.
JavaScript provides several kinds of control structures for different
programming situations.
Three of the most common control structures you’ll use are if
constructions, if...else constructions, and for loops.
31
31
if (condition) {
statement[s] if true
}
Example:
if (myAge < 18) {
alert(“sorry”, you are not allowed to vote.”);
}
For all instances of myAge less than 18, the nested statement inside
the curly braces runs and displays the alert to the user.
After the user closes the alert dialog box, the script continues with
whatever statement follows the entire if construction.
32
if…else construction
In the plain if construction, no special processing is performed when the condition
evaluates to false. But if processing must follow one of two special paths, you need the
if...else construction. The formal syntax definition for an if...else construction is as
follows:
Syntax
if (condition) {
statements if true
} else {
statements if false
33
}
33
Loops
A loop lets a script cycle through a sequence of statements until some condition is met
(encountered).
For example, a JavaScript data validation routine might inspect every character that you
enter in a form text field to make sure that each one is a number.
Or if you have a collection of data stored in a list, the loop can check whether an
entered value is in that list.
When that condition is met, the script can break out of the loop and continue with the
next statement after the loop construction.
The most common repeat loop construction used in JavaScript is called the for loop
The formal syntax of the for loop is as follows:
for (initial expression; condition; update expression) {
statement[s] inside loop
34
}
Functions
A user-defined or built-in set of statements that perform a specific task.
Functions are invoked by event handlers or by statements elsewhere in the
script.
A JavaScript function is executed when "something" invokes it (calls it).
It can also return a value when used with the return statement.
Syntax:
function name(param1 , param2 ..., paramN) {
statements
}
Function Invocation
The code inside the function will execute when "something" invokes (calls) the
function:
When an event occurs (when a user clicks a button)
When it is invoked (called) from JavaScript code
Automatically (self invoked)
35
35
Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute
the code after the invoking statement.
Functions often compute a return value.
The return value is "returned" back to the "caller":
Example
// Takes an endValue and returns 1+2+3+ … + endValue
function summation (endVal) {
var thesum=0;
for ( var iter = 1; iter <= endVal; iter++ )
thesum += iter;
return ( thesum ); Output:
} 15
[Link](summation(5))
36
A Simple Function
<HTML>
<HEAD>
<SCRIPT>
function compute(form)
{
[Link] = eval([Link])
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
Enter an expression:
<INPUT TYPE="text" NAME="expr" SIZE=15 >
<INPUT TYPE="button" VALUE="Calculate" ONCLICK="compute([Link])">
<BR>
Result:
<INPUT TYPE="text" NAME="result" SIZE=15 >
</FORM>
</BODY>
</HTML> 37
37
expr
Result
38
38
expr
function compute(form)
Result {
[Link] = eval([Link])
}
39
39
Array
The JavaScript array is one of the most useful data constructions you have available.
To access an item in an array, you need to know the name of the array and the index
number.
Because index values start with zero, the total number of items of the array (as
determined by the array’s length property) is always one more than the highest index
value of the array.
Data elements inside JavaScript arrays can be any data type, including objects.
40
Creating an array
An array is stored in a variable, so when you create an array, you assign the new array object to the variable.
A special keyword new preceding a call to the JavaScript function that generates arrays creates space in
memory for the array.
An optional parameter to the Array() function enables you to specify at the time of creation how many
elements of data eventually will occupy the array.
To demonstrate the array creation process, suppose, create an array that holds the student names as follows:
var studentName = new Array(4);
The first row of the studentName array is addressed as:
studentName[0]
To assign the string of value to the array, We use a simple assignment operator:
studentName[0] = “Ayele”;
studentName[1] = “Beshatu”;
studentName[2] = “Garuma”;
studentName[3] = “Burte”;
41
Accessing array data
42
Event Handling
any time.
e.g.,
43
43
EVENT HANDLERS
The following event handlers are available in JavaScript:
onAbort
• onMouseDown
onBlur
• onMouseMove
onChange • onMouseOut
onClick • onMouseOver
onDragDrop • onMouseUp
onError • onMove
onFocus • onReset
onKeyDown • onResize
onKeyPress • onSelect
onKeyUp • onSubmit
• onUnload
onLoad
44
44
Event Event Handler Description
Load onLoad Browser finishes loading a Web document
Unload onUnload Visitor requests a new document in the browser window
Mouseover onMouseOver Visitor moves the mouse over some object in the document window
Mouseout onMouseOut Visitor moves the mouse off of some object in the document window
MouseDown onMouseDown A mouse button was pressed
MouseMove onMouseMove The mouse moved
MouseUp onMouseUp The mouse button was released
Select onSelect Text has been selected.
Click onClick Visitor clicks the mouse button
Focus onFocus Visitor gives focus to or makes active a particular window or form element by clicking on
it or tabbing to it
Blur onBlur A form field lost the focus (user moved to another field)
Change onChange Visitor changes the data selected or contained in a form element
Submit onSubmit Visitor submits a form
Reset onReset Visitor resets a form
Abort onAbort An image failed to load
Change onChange The contents of a field has changed
DblClick onDblClick User double-clicked on this item
Error onError An error occurred while loading an image
Keydown onKeyDown A key was pressed
KeyPress onKeyPress A key was pressed or released
KeyUP onKeyUp A key was released
45
Example: a program that adds or subtracts two numbers when respective button is clicked
<html>
<head>
<script language="JavaScript">
function adder(num1, num2)
{
var sum = 0;
sum = num1 + num2;
[Link]("The sum is " + sum);
}
function subtractor(num1, num2)
{
var difference = 0;
difference = num1 - num2;
[Link]("The difference is " + difference);
}
</script>
</head>
<body>
<form name="event_example">
<input type="button" value="add" name="add" onClick="adder(10,30)">
<input type="button" value="subtract" name="subtract" onClick="subtractor(20,50)">
<a href=“” onclick=“adder(30,40”> Add </a>
</form>
</body>
</html>
46
EVENT HANDLERS (CONT...)
onAbort
An abort event occurs when a user aborts the loading of an image (for example
by clicking a link or clicking the Stop button)
onBlur
A blur event occurs when a select, text, or textarea field on a form loses focus.
onChange
A change event occurs when a select, text, or textarea field loses focus and its
value has been modified.
onClick
A click event occurs when an object on a form is clicked.
47
47
EVENT HANDLERS (CONT...)
onError
An error event occurs when the loading of a document or image causes an
error
onFocus
A focus event occurs when a field receives input focus by tabbing with the
keyboard or clicking with the mouse.
onKeyDown, onKeyPress, onKeyUp
A keyDown, keyPress, or keyUp event occurs when a user depresses a key,
presses or holds down a key, or releases a key, respectively
48
48
EVENT HANDLERS (CONT...)
onLoad
A load event occurs when Navigator finishes loading a window or all
frames within a <FRAMESET>.
Examples
In the following example, the onLoad event handler displays a greeting message
49
49
EVENT HANDLERS (CONT...)
onMouseOver
A mouseOver event occurs once each time the mouse pointer moves over
an object from outside that object.
Example
<A HREF="[Link]
onMouseOver="[Link]=‘A Good Place …!'; return true">
Click me</A>
Return true tells the browser not to perform its own event handling
routine of displaying the link’s URL in the status bar
50
50
EVENT HANDLERS (CONT...)
onSelect
A select event occurs when a user selects some of the text within
a text or textarea field.
onSubmit
51
51
FORM VALIDATION
FileName: [Link]
<html><head><script <body>
language="JavaScript"> <form name="first">
function test1(form) { Enter your name:<br>
if ([Link] == "")
<input type="text"
alert("Please enter a string!")
name="text1">
else {
alert("Hi "+[Link]+"!
<input type="button"
Form input ok!"); name="button1" value="Test
} Input"
} onClick="test1([Link])">
function test2(form) { <P>
if ([Link] == "" || Enter your e-mail address:<br>
[Link]('@') <input type="text"
== -1)
name="text2">
alert("No valid e-mail
address!"); <input type="button"
else alert("OK!"); name="button2" value="Test
52
} Input"
// --> onClick="test2([Link])">
52
</script></head> </body>
FORM VALIDATION (2)
FileName: [Link] <BODY>
<HTML> <P>
<HEAD> <HR><FORM NAME="myform"
<SCRIPT onSubmit="checkit()"></P>
LANGUAGE="JavaScript">
function checkit() {
<P>Enter a number between 1
var strval =
and 9: <INPUT TYPE="text"
[Link]
e; NAME="mytext" VALUE=""
SIZE="10"></P>
var intval = parseInt(strval);
if ( intval > 0 && intval < 10
){ <P><BR>
return(true); <INPUT
} else { TYPE="submit"></FORM>
alert("Input value " + <HR></P>
strval + " is out of range");
return(false);
</BODY>
}
</HTML> 53
}
</SCRIPT> 53
</HEAD>
Introduction to XML
XML(Extensible Markup Language): lets you create text documents that can hold data in a structured way.
XML Basics
XML permits document authors to create markup (i.e. a text based notation for describing data) for virtually
any type of information.
This enables document authors to create entirely new markup languages for describing any type of data, such
as mathematical formulas, software – configuration instruction, chemical molecular structures, music, news
and etc.
XML describes data in a way that both human beings and computers can understand.
54
Example:
<?xml version = “1.0”?>
<player>
<firstName>Hebron</firstName>
<lastName>Fergusen</lastName>
<score>3.00</score>
</player>
XML documents contain text that represents content (i.e. data), such as Hebron, and elements that
specify the document’s structure, such as firstName .
XML documents delimit elements with start tags and end tags. A start tag and end tag consists of
the element name in angle brackets (e.g. <player> and </player>)
55
Advantages of use XML
Simpler version of standard to Generalized Markup Language(SGML).
Easy to understand and read.
Support by large number of platforms.
Used across open standard.
Components of XML.
Declaration
Attribute
Tags
Elements
comments
57
Cont’d
Declaration: Tags:
The first line in document. Text in between < and >
Provide information to the Tags and data stored together.
parser. Data is self-descriptive and easy
Contain three name-value pairs: to understand.
Version(common)
Encoding (defaults to UTF-8)
Standalone(rare)
58
Cont’d
Elements: Attributes:
Basic building block of an XML file. Provide information about the
Text between start and end tag. elements.
Document contain one root element. Name-value pairs:
Single or double quotes to encode
Can contain nested elements.
values.
Attribute names are unique
within the same element.
59
Cont’d
Comments:
Appear anywhere in document
Start tag <!--
End tag --!>
Contents inside of comment are not parsed.
60
JavaScript Objects
3.2 Working with JavaScript Objects
• JavaScript has many built-in objects that you can use to perform different
activities.
• Every time you load a page into web browser, the JavaScript interpreter
creates certain Objects based on how the HTML is written.
• This minimal Object set is comprised of the navigator, window, document,
location, and history Objects.
• Depending on what's contained in the page, there can obviously be other
Objects that are also generated by the interpreter.
• All of these Objects exist in an Object hierarchy that can be accessed by
calling on the Object with dot notation.
• The following chart shows the structure.
61
JavaScript Objects and Events…
Object Properties and Methods
• All objects have properties and methods that are associated with them.
• All objects have the same properties, but the property values differ from objects to
objects.
• All objects have the same methods, but the methods are performed at different times.
• A Property of an object is basically a predefined variable that you can assign a value to with simple
dot notation Syntax like this:
[Link] = value
For instance, A car has properties like weight and color, and methods like start and stop:
Properties Methods
[Link]=850kg [Link]()
62
[Link]=blue [Link]()
JavaScript Objects and Events…
• A Method of an object is a predefined function that is assigned to an
Object by browser.
• You invoke a Method on an Object with the same dot notationlike this:
[Link]()
• Suppose you want to give focus to the window at some point in your
Script.
• You do that by referencing the window Object and calling the focus()
method like this:
[Link]();
63
JavaScript Objects and Events…
2. JavaScript Objects
• JavaScript has many built-in objects that you can use to perform different
activities.
• The most important objects are:
• Math
• String
• Date
• History
• Document
• Number
64
JavaScript Objects and Events…
2.1 Math Object
• The predefined Math object has properties and methods for
mathematical constants and functions.
• For example, the Math object’s PI property has the value of pi
(3.141...), which you would use in an application as [Link]
• Similarly, standard mathematical functions are methods of Math.
• These include trigonometric, logarithmic, exponential, and other
functions.
• For example, if you want to use the trigonometric function sine, you
would write:
[Link](1.56)
• Note that all trigonometric methods of Math take arguments in
radians.
65
JavaScript Objects and Events…
Property Value Description
[Link] 3.141592653589793116 π
66
Method Syntax Returns
[Link](val) Absolute value of val
[Link](val) Arc cosine (in radians) of val
[Link](val) Arc sine (in radians) of val
[Link](val) Arc tangent (in radians) of val
Math.atan2(val1, val2) Angle of polar coordinates x and y
[Link](val) Next integer greater than or equal to val
[Link](val) Cosine of val
[Link](val) Euler’s constant to the power of val
[Link](val) Next integer less than or equal to val
[Link](val) Natural logarithm (base e) of val
[Link](val1, val2) The greater of val1 or val2
[Link](val1, val2) The lesser of val1 or val2
[Link](val1, val2) Val1 to the val2 power
[Link]() Random number between 0 and 1
[Link](val) N+1 when val >= N.5; otherwise N
[Link](val) Sine (in radians) of val
[Link](val) Square root of val
[Link](val) Tangent (in radians) of val 67
JavaScript Objects and Events…
• Example:
[Link](3.5); // result: 4
[Link](–3.5); // result: –3.
[Link](5, 2); // result: 25
[Link](1.6); //result: 1
[Link](1.6); //result: 2
[Link](90); //result: 1
68
JavaScript Objects and Events…
2.2 Date Object
• Most of your date and time work is done with the Date object.
• The basic syntax for generating a new date object is as follows:
var dateObjectName = new Date([parameters])
output:
Today’s date: 4/11/2010
• You can also create a string object using the more formal syntax
that involves the new keyword and a constructor function like:
var stringVar = new String(“characters”); 72
Method Description
charAt(index) Returns the character at the specified index.
charCodeAt(index) Returns a number indicating the Unicode value of the character at the given index.
concat(string) Combines the text of two strings and returns a new string.
indexOf(string, [start]) Returns the index within the calling String object of the first occurrence of the
specified value, or -1 if not found.
lastIndexOf(string,[start]) Returns the index within the calling String object of the last occurrence of the
specified value, or -1 if not found.
localeCompare(string2) Returns a number indicating whether a reference string comes before or after or is
the same as the given string in sort order.
length Returns the length of the string.
match(regExpression) Used to match a regular expression against a string.
replace(regExpression,replacer) Used to find a match between a regular expression and a string, and to replace the
matched substring with a new substring.
search(regExpression) Executes the search for a match between a regular expression and a specified string.
slice(startIndex [,end]) Extracts a section of a string and returns a new string.
split(delimiter [,limit]) Splits a String object into an array of strings by separating the string into substrings.
substr(start [, length]) Returns the characters in a string beginning at the specified location through the
specified number of characters.
substring(start, end) Returns the characters in a string between the two indexes into a string.
toLowerCase() Returns the calling string value converted to lower case.
toUpperCase() Returns the calling string value converted to uppercase.
toString() Returns a string representing the specified object.
73
JavaScript Objects and Events…
• Example:
var name = new String(“Konrad Zuse person who crete computer for
first time”);
[Link](“ - created the first computer”);
[Link](0,10);
[Link](“Zuse”);
[Link](“a”,”#”);
[Link]();a
• Output:
Konrad Zuse - created the first computer
Konrad Zuse
7
KONRAD ZUSE
Konr#d Zuse
74
JavaScript Objects and Events…
2.4 Document Object
• Contains information on the current document.
• Document object contains properties and methods that can be
used to access the page elements.
• Properties:
• title -Current document title. If no title is defined, title contains “Untitled.”
• location -Full URL of the document.
• lastModified -A Date object-compatible string containing the date the
document was last modified.
• bgColor -Background color, expressed as a hexadecimal RGB value (for example,
#FFFFF for white). Equivalent to the BGCOLOR attribute of the <BODY> tag.
• fgColor -Foreground (text) color, expressed as a hexadecimal RGB value
compatible with HTML syntax. Equivalent to the TEXT attribute of the <BODY>
tag.
75
JavaScript Objects and Events…
• linkColor - Hyperlink color, expressed as a hexadecimal RGB value compatible with
HTML syntax. Equivalent to the LINK attribute of the <BODY> tag.
• alinkColor - Activated hyperlink color, expressed as a hexadecimal RGB value.
Equivalent to the ALINK attribute of the <BODY> tag.
• vlinkColor – visited link color, expressed as hexadecimal RGB value
• forms[ ] - Array of form objects in the document, in the order specified in the
source. Each form has its own form object.
• [Link] - The number of form objects within the document.
• links[ ] - Array objects corresponding to all HREF links in the document, in the
order specified in the source.
• [Link] - The number of HREF links in the document.
• anchors[ ] - Array of all "named" anchors between the <A NAME=""> and </A>
tags within the document.
• [Link] - The number of named anchors in the document.
• images[] - Image objects that correspond to each image on the page.
• applets[] - Java applet objects that correspond to each applet on the page.
76
• embeds[] - Plugins object that represent each plug-in on the page.
JavaScript Objects and Events…
• Example: changing link colors
[Link] = “red”;
[Link] = “blue”;
[Link] = “green”;
• Methods:
• write("string")-Writes string to the current window. string may
include HTML tags.
• writeln("string") - Performs the same as write(), but adds a
carriage return. This affects only preformatted text (inside a
<PRE> or <XMP> tag).
• clear( ) - Clears the window.
77
• close( ) - Closes the window.
JavaScript Objects and Events…
2.5 History Object
• The history object contains a list of strings representing the URLs the client
has visited.
• You can access the history values using the history array.
• This array contains an entry for each history entry in source order; each
array entry is a string containing a URL.
var fifthEntry = [Link][4];
• You can also redirect the client to any history entry by using the go
method.
• For example, the following code loads the URL that is two entries back in
the client’s history list.
[Link](-2)
78
JavaScript Objects and Events…
• The following code reloads the current page:
[Link](0)
Properties Methods
Length back()
forward()
go()
• Example:
[Link](-1) is the same as [Link]().
[Link](1) is the same as [Link](). 79
JavaScript Objects and Events…
2.6 Number Object
• The Number object contains some information and power of value to
serious programmers.
• The Number.MAX_VALUE and Number.MIN_VALUE properties belong to
the static Number object.
• They represent constants for the largest and smallest possible positive
numbers that JavaScript can work with.
• Their actual values are 1.7976931348623157 * 10308, and 5 * 10-324,
respectively.
82
JavaScript Objects and Events…
• The final method is toPrecision(), which enables you to define how many total digits to
display of a number.
• In other words, you define the precision of a number.
• This includes digits to the left and right of the decimal
• Example:
var num = 123.45
[Link](1); // result = 1e+2
[Link](2) ; // result = 1.2e+2
[Link](3) ; // result = 123
[Link](4) ; // result = 123.5
[Link](5) ; // result = 123.45
[Link](6) ; // result = 123.450
83
JavaScript Objects and Events…
3.2.7 Window Object
• At the very top of the document object hierarchy is the window object.
• It is the master container for all content you view in the Web browser.
• Methods:
• [Link]() - this method opens a new window. The syntax is:
[Link](“URL”, “name” [, “windowfeatures”]);
• Parameters:
• URL is a string that points to the window you want to open.
• name is a string that names the new window.
84
JavaScript Objects and Events…
• name is a string that names the new window.
• windowfeatures is one or more of the following in a comma-separated list:
• toolbar - toolbar is present. The value is yes or no.
• location – Location bar is present. The value is yes or no.
• directories
• status – statusbar is present. The value is yes or no.
• menubar – menubar is present. The value is yes or no.
• scrollbars – scrollbars are present. The value is yes or no.
• resizable – window is resizable. The value is yes or no.
• copyhistory
• width – width of the window
• height – height of the window
[Link](“[Link]”, “testing ”, “toolbar=yes,status=yes”);
85
JavaScript Objects and Events…
• In a more controlled way using windowfeatures:
newWin=[Link]("", "New", "height=250, width=250,
toolbar=no, scrollbars=yes, menubar=no");
[Link]("<TITLE>Title Goes Here</TITLE>");
[Link]("<BODY BGCOLOR=pink>");
[Link]("<h1>Hello!</h1>");
[Link]("This text will appear in the window!");
[Link]("</BODY>");
[Link]("</HTML>");
[Link]();
86
Method Description
[Link](message) Displays an alert dialog.
[Link]() Moves back one in the window history.
[Link]() Sets focus away from the window.
[Link](([Link]) Registers the window to capture all specified events.
[Link](intervalID) Clears a delay that’s been set for a specific function.
[Link](timeoutID) Clears the delay set by [Link]().
[Link]() Closes the current window.
[Link](message) Displays a dialog with a message that the user needs to
respond to.
[Link](message) Writes a message to the console.
[Link](text) Encodes a string.
[Link]() Sets focus on the current window.
[Link]() Moves the window one document forward in the history.
[Link]() Flashes the application icon to get user attention.
[Link]() Returns the selection object representing the selected
item(s).
[Link]() Returns the browser to the home page.
[Link](pixelX, pixelY) Moves the current window by a specified amount.
87
[Link](x, y) Moves the window to the specified coordinates.
[Link](URL,name[,features]) Opens a new window.
[Link]() Prints the current document.
[Link](message[,default]) Returns the text entered by the user in a prompt dialog.
[Link]([Link]) Releases the window from trapping events of a specific type.
89
<html>
<head>
<title>Show Title</title>
<script language="JavaScript">
var t = setInterval("showTime()",100);
function showTime()
{
var dt = new Date();
var hr = [Link]();
var min = [Link]();
var sec = [Link]();
if(min < 10) //append 0 if minutes < 10
min = "0" + min;
if(sec < 10) //append 0 if seconds < 10
sec = "0" + sec;
[Link] = hr + ":" + min + ":" + sec;
}
</script>
</head>
<body>
<form name="display">
<input type="text" name="time">
</form>
</body>
</html> 90
JavaScript Objects and Events…
3.2.7 Image Object
• The Image object reflects the attributes of an image on the current page.
• An image on the page can be referred to either via the images[] array or
by the image name, as shown here:
[Link][2].propertyName
[Link]
• Properties
• border - Reflects the BORDER attribute
• complete - Boolean value indicating whether Navigator has
completed its attempt to load the image
• height - Reflects the HEIGHT attribute.
• hspace - Reflects the HSPACE attribute.
• lowsrc - Reflects the LOWSRC attribute.
• name - Reflects the NAME attribute. 91
JavaScript Objects and Events…
• Properties…
• Prototype - Lets you add properties to an Image object.
• src - Reflects the SRC attribute (can dynamically change
the image on a page).
• vspace - Reflects the VSPACE attribute.
• width - Reflects the WIDTH attribute.
92
Example: image slide show using JavaScript
<html>
<head>
<script language="JavaScript">
photonames = new Array('[Link]', '[Link]', 'Ethiopia_regions.png',
‘[Link]', '[Link]');
var tt = setInterval("slideshow()", 2000);
currentphoto = 0;
function slideshow()
{
currentphoto++;
if(currentphoto > [Link] - 1)
currentphoto = 0;
[Link] = photonames[currentphoto];
}
</script>
</head>
<body>
<img src="[Link]" id="photo" height="80%"> <br>
</body> 93
Form Processing and Validation
• It is possible to access form and form elements from
JavaScript.
• You can set attributes for NAME, TARGET, ACTION, METHOD,
and ENCTYPE for form.
• Each of these is a property of a FORM object, accessed by all
lowercase versions of those words, as in:
[Link][0].action //forms array of the document
[Link] //references exact form by
name
Event Handlers
• onFocus - executed when input focus enters field (by tabbing in or by
clicking but not selecting in the field).
• onBlur - executed when input focus leaves the field.
• onSelect - executed when the field is input-focused by selecting some of
its text.
• onChange - executed when input focus exits the field and the value of the
field has changed from when onFocus occurred.
• Text area has the same property as text field: the value property. Using 97
<HTML>
<HEAD>
<TITLE>JavaScript Form Input</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function add()
{
var op1 = [Link];
var op2 = [Link];
var sum = op1 + op2;
[Link] = sum;
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="test" ACTION="" METHOD="GET">
First number: <INPUT TYPE="text" NAME="fnum"><br>
Second number: <INPUT TYPE="text" NAME="snum"><br>
Result: <INPUT TYPE="text" NAME="result"><br>
<INPUT TYPE="button" NAME="adder" Value="Add" onClick="add()">
</FORM>
</BODY> 98
Form Processing and
Validation…
Checkboxes and Radio Buttons
• To define radio buttons for JavaScript, provide each object with the same
name.
• JavaScript will create an array using the name you've provided; you then
reference the buttons using the array indexes.
• Use the checked property to know the state of the individual radio
buttons.
101
Form Processing and
Validation…
• options[] - This property is an object reflecting the contents of the
<OPTION> tag used when defining a select object in HTML.
• It contains the following properties:
• text - String containing the text after the <OPTION> tag. Assigning a new
value to options[index].text will either change the menu item text or add
a new item, in the case of an index higher than the current number of
items.
• Value - Reflection of the VALUE attribute. This is sent to the server when
the Submit button is pressed.
• defaultSelected - Boolean that reflects the SELECTED attribute of the
<OPTION> tag.
• selected - Boolean that indicates the current selected state of the option.
• Event handlers:
• onFocus - executed when input focus enters the field.
• onBlur - executed when input focus leaves the field.
• onChange - executed when input focus exits the field and the field value
102
has changed since the focus event
</SCRIPT>
<HTML>
<HEAD> </HEAD>
<TITLE>List Box Test</TITLE> <BODY>
<SCRIPT LANGUAGE="JavaScript"> <FORM NAME=“test" ACTION="[Link]"
function testSelect () { METHOD="GET">
var Item = Fruit: <SELECT NAME="list" SIZE="1">
[Link]; <OPTION>none</OPTION>
result = <OPTION>Orange</OPTION>
[Link][Item].text <OPTION>Apple</OPTION>
;
<OPTION>Papaya</OPTION>
//Or you can use the following line
which does the same as the above <OPTION>Banana</OPTION>
line </SELECT>
result = [Link]; <INPUT TYPE="button" NAME="button"
alert (result); value="Test" onClick="testSelect()">
} </FORM>
</BODY>
</HTML>
103
Form Processing and
Validation…
THE END
104
Thank you!!
105