Chapter 4-Javascript
Chapter 4-Javascript
1 By.Abrahim A.
Outline
what is Client-side programming?, What is
JavaScript?, Common
scripting tasks, limitations of client-side scripting,
JavaScript and Java,
JavaScript Terminology(ObjCP, Properties,
Methods, Events, Functions,
Values, Variables, Expressions, Operators, …)
2 By.Abrahim A.
1. Introduction
In the very beginning, web pages were static without any
interaction with the user.
They just provide information to the user as it is.
Later on, JavaScript is introduced to enable dynamicity in web
pages where user has his/her own preferences or control.
8 By.Abrahim A.
Adding JavaScript
There are three ways to add JavaScript commands to your
Web Pages.
Embedding code
Inline code
External file
I. External File
If you want to run the same JavaScript on several pages, you
9 By.Abrahim A.
Adding JavaScript…
The external script cannot contain the <script></script> tags!
You can use the SRC attribute of the <SCRIPT> tag to call
JavaScript code from an external text file.
It is called by the following tag:
<SCRIPT language = "JavaScript" SRC = "filename">
</SCRIPT>
The prompt display includes a message, field for user input, and
two buttons (Ok, and Cancel).
The prompt(“”) returns string of text entered by user.
It takes two parameters:
a message providing the prompt for the response, and
a default string which is used to fill in the text field.
14 By.Abrahim A.
Input-Output in Java…
A confirm dialog box presents a message in a modal dialog box
along with Ok and Cancel buttons.
Such dialog boxes can be used to ask the user a question, usually
prior to performing undoable actions.
The dialog box returns a Boolean value of Ok=true, and
Cancel=false;
Example:
var adult = confirm(“Are you sure you are older than 18 years?”)
if(adult)
alert(“Yes”);
else
alert(“No”);
15 By.Abrahim A.
3.Working with Variables and Data
I. Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations
21 By.Abrahim A.
4. Operators and Expressions…
Operator Description
+ Perform addition of numbers
- Perform Subtraction
* Multiply numbers
/ Divide numbers
% Modulus (performs division and gets the remainder)
++ Increment
-- Decrement
22 By.Abrahim A.
4. Operators and Expressions…
Example:
<script language=“JavaScript”>
var x;
var y=5;
x = y+2; //x=7
x = y-2; //x=3
x = y*2; //x=10
x = y/2; //x=2.5
x = y%2; //x=1
x = ++y; //x=6
x = --y; //x=4
23
</script> By.Abrahim A.
4. Operators and Expressions…
II. JavaScript Assignment Operators
Assignment operators are used to perform arithmetic
operation and then assign the result to variables.
Operator Description
= assignment operator
+= Add and then assign
25 By.Abrahim A.
4. Operators and Expressions…
III. Comparison Operators
Comparison operators help you compare two or more values
Symbol Description
== Equals
=== Exactly equal to (value and type)
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
26 By.Abrahim A.
<= Less than or equal to
4. Operators and Expressions…
IV. Logical Operators
Logical operators are used to determine the logic between
variables or values.
Operator Description
&& And
|| Or
! Not
Given that x=6 and y=3, the table shows logical operators:
Example Result
(x<10 && y>1) true
(x==5 || y==5) false
27 !(x==y) true By.Abrahim A.
Operator type Individual operators
member . []
call / create instance () new
negation/increment ! ~ - + ++ -- typeof void delete
multiply/divide * / %
Operator Precedence
addition/subtraction + -
bitwise shift << >> >>>
relational < <= > >= in instanceof
equality == != === !==
bitwise-and &
bitwise-xor ^
bitwise-or |
logical-and &&
logical-or ||
Conditional ?:
assignment = += -= *= /= %= <<= >>= >>>= &= ^= |=
28 By.Abrahim A.
comma ,
Data Type Conversions
The type of data in an expression can trip up some script operations
if the expected components of the operation are not of the right data
type.
JavaScript tries its best to perform internal conversions to head off
such problems.
However, if your intentions differ from the way JavaScript treats the
values, you won’t get the results you expect.
29 By.Abrahim A.
Data Type Conversions…
But if one of those numbers is a string, JavaScript leans
toward converting the other value to a string
This turns the plus sign’s action from arithmetic addition to
concatenation of strings.
To use either of these conversion functions, pass the string value you wish
to convert as a parameter to the function.
Look at the results of two different string values when passed through the
parseInt() function:
parseInt(“42”) // result = 42
parseInt(“42.33”) // result = 42
32 By.Abrahim A.
Data Type Conversions…
The parseFloat() function returns an integer if it can
Otherwise, it returns a floating-point number as follows:
parseFloat(“42”); // result = 42
parseFloat(“42.33”); // result = 42.33
var someVal = 2;
someVal = someVal + 2;
someVal = someVal * 10;
someVal = someVal + “20”;
someVal = “Robert”;
35 By.Abrahim A.
5. Working with Conditional Statements
36 By.Abrahim A.
5. Working with Conditional Statements…
If condition
The simplest program decision is to follow a special branch or
path of the program if a certain condition is true.
37 By.Abrahim A.
5. Working with Conditional Statements…
Example:
if (myAge < 18) {
alert(“Sorry, you cannot vote.”)
}
if . . . else Condition
Not all program decisions are as simple as the one
shown above.
The program may follow one of many branches
depending on the condition.
But if processing must follow one of two special paths,
38 you need the if...else construction.
By.Abrahim A.
5. Working with Conditional Statements…
if (condition) {
statement(s) if true
}
[else if(condition){
statement(s) if true
}]
[else {
statement(s) if false
}]
39 By.Abrahim A.
5. Working with Conditional Statements…
Example:
If(mark>80)
status=”excellent”;
else if(mark>60)
status=”very good”;
else if(mark>50)
status = “fair”;
else
status =”poor”;
40 By.Abrahim A.
5. Working with Conditional Statements…
switch Statement
A switch statement allows a program to evaluate an expression and attempt
to match the expression's value to a case label.
If a match is found, the program executes the associated statement.
switch (expression) {
case label1:
statements1
[break;]
case label2:
statements2
[break;]
...
default:
statementsdefault
41 [break;] By.Abrahim A.
5. Working with Conditional Statements…
Example:
switch (fruittype) {
case "Apples":
document.write("Apples are $0.32 a pound.<br>");
break;
case "Bananas":
document.write("Bananas are $0.48 a pound.<br>");
break;
case "Mangoes":
case "Papayas":
document.write("Mangoes and papayas are $2.79 a pound.<br>");
break;
default:
document.write("Sorry, we are out of " + fruittype + ".<br>");
42 } By.Abrahim A.
Working with Loops
A loop is a set of commands that executes repeatedly until a
specified condition is met.
JavaScript supports the for, do while, and while loop
statements.
In addition, you can use the break and continue statements
within loop statements.
Another statement, for...in, executes statements repeatedly
but is used for object manipulation.
There are three loop statements in JavaScript:
for Statement
do...while Statement
while Statement
43 By.Abrahim A.
Working with Loops…
for Loops
A for loop repeats until a specified condition evaluates to false. A
for statement looks as follows:
for ([initialization]; [condition]; [increment]){
Statement(s)
}
45 By.Abrahim A.
Working with Loops…
do...while Statement
The do...while statement repeats until a specified condition
evaluates to false.
A do...while statement looks as follows:
do{
statement
}while (condition);
while Statement
A while statement executes its statements as long as a specified
condition evaluates to true.
A while statement looks as follows:
while (condition)
{
statement
47 } By.Abrahim A.
Working with Loops…
The condition test occurs before statement in the loop are executed.
If the condition returns true, statement is executed and the condition
is tested again.
If the condition returns false, execution stops and control is passed
to the statement following while.
Example: the following example loops until the value of loop counter
is 5:
for (i = 0; i < 100; i++) {
if (i== 5)
break;
}
Example: a program that adds numbers between 0 and 100 with the
exception of 60, 70, and 80
var counter = 100;
var sum = 0;
for (var i = 0; i <= counter; i++)
{
if(i==60 || i==70 || i==80)
continue;
sum = sum + i;
}
document.write(“the sum is ” + sum);
50 By.Abrahim A.
Arrays
An array is an ordered collection of data.
You can best visualize an array as a table, not much different
from a spreadsheet.
Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune,Plu
to
54 By.Abrahim A.
Arrays…
You can refer to a particular element in an array by using the
index number.
The index number starts at 0 and end at n-1 for array of n
entries.
For example, to access the fifth planet in the planets array, we
use:
document.write(planet[4]); //prints Jupiter
60 By.Abrahim A.
Arrays…
Array Object Methods
array.concat(array2)
For example:
var array1 = new Array(1,2,3)
var array2 = new Array(“a”,”b”,”c”)
var array3 = array1.concat(array2)
61 // result: array3 with values 1,2,3,”a”,”b”,”c”
By.Abrahim A.
Arrays…
array.sort([compareFunction])
This method sorts the elements of an array.
You can define a compareFunction algorithm if you don’t
want to use the default compare function.
63 By.Abrahim A.
Arrays…
Return Value Meaning
<0 value b should sort later than a
0 The order of a and b should not change
>0 Value a should sort later than b
lastIndexOf(value) Returns the last (greatest) index of an element within the array equal to
the specified value, or -1 if none is found.
pop() Removes the last element from an array and returns that element.
push(value) Adds one or more elements to the end of an array and returns the new
length of the array.
reverse() Reverses the order of the elements of an array − the first becomes the last,
and the last becomes the first.
shift() Removes the first element from an array and returns that element.
unshift(value)
65 Adds one or more elementsBy.Abrahim
to the front
A. of an array and returns the new
length of the array.
function arrayFunction() {
var grade = new Array("70", "60", "80", "90", "20");
document.write("<br> Popped: " + grade.pop());
grade.reverse();
document.write("<br>Reversed: ");
for(var i=0;i<grade.length; i++)
document.write(" " + grade[i]);
Defining Functions
A function definition consists the function keyword, followed
by:
The name of the function.
A list of arguments to the function, separated by commas.
The statements that define the function, enclosed in curly
68
braces { }. By.Abrahim A.
Functions in JavaScript…
The syntax to define function:
function functionName ( [parameter1]...[,parameterN] ) {
statement[s]
}
70 By.Abrahim A.
Functions in JavaScript…
Consider the following script segment:
function sayHiToFirst(first, second, third) {
alert(“Say hello, “ + first)
}
sayHiToFirst(“Gracie”, “George”, “Harry”)
sayHiToFirst(“Larry”, “Moe”, “Curly”)
After the function is defined in the script, the next statement calls
that very function, passing three strings as parameters.
The function definition automatically assigns the strings to variables
first, second, and third.
first evaluates to “Gracie,” second evaluates to “George,” and third
evaluates to “Harry.”
In the alert() statement, only the first value is used and the alert
71
reads By.Abrahim A.
Functions in JavaScript…
Unlike other variables that you define in your script, function
parameters do not use the var keyword to initialize them.
They are automatically initialized whenever the function is
called.
return statement.
72 By.Abrahim A.
Functions in JavaScript…
§ The example below returns the product of two numbers (a and b):
<html>
<head>
<script language=“JavaScript">
function product(op1, op2)
{
return op1*op2;
}
</script>
</head>
<body>
<script language=“JavaScript">
document.write(product(4,3));
</script>
</body>
73 By.Abrahim A.
</html>
JavaScript Objects and Events
1. Managing Events
Events are occurrences generated by the browser, such
as loading a document, or by the user, such as moving
the mouse.
They are the user and browser activities to which we
may respond dynamically with a scripting language
like JavaScript.
74 By.Abrahim A.
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
75 By.Abrahim A.
KeyUP onKeyUp A key was released
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;
document.write("The sum is " + sum);
}
function subtractor(num1, num2)
{
var difference = 0;
difference = num1 - num2;
document.write("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>
76 By.Abrahim A.
JavaScript Objects and Events…
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.
77 By.Abrahim A.
78 By.Abrahim A.
JavaScript Objects and Events…
Object Properties and Methods
All objects have properties and methods that are associated with
them.
A Property of an object is basically a predefined variable that you
can assign a value to with simple dot notation Syntax like this:
objectName.propertyName = value
79 By.Abrahim A.
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:
objectName.methodName()
String
Date
History
Document
Number
81 By.Abrahim A.
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 Math.PI
Similarly, standard mathematical functions are methods of Math.
For example, if you want to use the trigonometric function sine, you
would write:
Math.sin(1.56)
Note that all trigonometric methods of Math take arguments in
radians.
82 By.Abrahim A.
JavaScript Objects and Events…
Math.PI 3.141592653589793116 π
83 By.Abrahim A.
Method Syntax Returns
Math.abs(val) Absolute value of val
Math.acos(val) Arc cosine (in radians) of val
Math.asin(val) Arc sine (in radians) of val
Math.atan(val) Arc tangent (in radians) of val
Math.atan2(val1, val2) Angle of polar coordinates x and y
Math.ceil(val) Next integer greater than or equal to val
Math.cos(val) Cosine of val
Math.exp(val) Euler’s constant to the power of val
Math.floor(val) Next integer less than or equal to val
Math.log(val) Natural logarithm (base e) of val
Math.max(val1, val2) The greater of val1 or val2
Math.min(val1, val2) The lesser of val1 or val2
Math.pow(val1, val2) Val1 to the val2 power
Math.random() Random number between 0 and 1
Math.round(val) N+1 when val >= N.5; otherwise N
Math.sin(val) Sine (in radians) of val
Math.sqrt(val) Square root of val
84 By.Abrahim A.
Math.tan(val) Tangent (in radians) of val
JavaScript Objects and Events…
Example:
Math.round(3.5); // result: 4
Math.round(–3.5); // result: –3.
Math.pow(5, 2); // result: 25
Math.floor(1.6); //result: 1
Math.ceil(1.6); //result: 2
Math.sin(90); //result: 1
85 By.Abrahim A.
JavaScript Objects and Events…
2.2 Date Object
Most of your date and time work is done with the Date object.
86 By.Abrahim A.
Method Value Range Description
dateObj.getTime() 0-... returns Milliseconds since 1/1/70 00:00:00 GMT
dateObj.getYear() 70-... returns Specified year minus 1900
returns four-digit year for 2000+
dateObj.getFullYear() 1970-... returns four-digit year (Y2K-compliant)
dateObj.getMonth() 0-11 returns Month within the year (January = 0)
dateObj.getDate() 1-31 returns Date within the month
dateObj.getDay() 0-6 returns Day of week (Sunday = 0)
dateObj.getHours() 0-23 returns Hour of the day in 24-hour time
dateObj.getMinutes() 0-59 returns Minute of the specified hour
dateObj.getSeconds() 0-59 returns Second within the specified minute
dateObj.setTime(val) 0-... sets Milliseconds since 1/1/70 00:00:00 GMT
dateObj.setYear(val) 70-... sets Specified year minus 1900
sets four-digit year for 2000+
dateObj.setMonth(val) 0-11 sets Month within the year (January = 0)
dateObj.setDate(val) 1-31 sets Date within the month
dateObj.setDay(val) 0-6 sets Day of week (Sunday = 0)
dateObj.setHours(val) 0-23 sets Hour of the day in 24-hour time
dateObj.setMinutes(val) 0-59 sets Minute of the specified hour
dateObj.setSeconds(val)
87 0-59 sets Second within the specified
By.Abrahim A. minute
JavaScript Objects and Events…
Example: display current date and time
var today = new Date();
var date = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
document.write(“Today’s date: ”+date+”/”+month+”/”+year);
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”);
89 By.Abrahim A.
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()
90 Returns a string representing the specified
By.Abrahimobject.
A.
JavaScript Objects and Events…
Example:
var name = new String(“Konrad Zuse”);
name.concat(“ - created the first computer”);
name.substring(0,10);
name.indexOf(“Zuse”);
name.replace(“a”,”#”);
name.toUpperCase();
Output:
Konrad Zuse - created the first computer
Konrad Zuse
7
KONRAD ZUSE
Konr#d Zuse
91 By.Abrahim A.
JavaScript Objects and Events…
2.4 Document Object
Contains information on the current document.
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
92 of the <BODY> tag. By.Abrahim A.
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.
forms.length - 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.
links.length - The number of HREF links in the document.
anchors[ ] - Array of all "named" anchors between the <A NAME=""> and </A>
tags within the document.
anchors.length - 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.
embeds[] - Plugins object that represent each plug-in on the page.
93 By.Abrahim A.
JavaScript Objects and Events…
Example: changing link colors
document.linkColor = “red”;
document.alinkColor = “blue”;
document.vlinkColor = “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.
close( ) - Closes the window.
94 By.Abrahim A.
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.
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.
95 history.go(-2) By.Abrahim A.
JavaScript Objects and Events…
The following code reloads the current page:
history.go(0)
Properties Methods
Length back()
forward()
go()
history.back() – goes back to last visited page
history.forward() – goes forward just like clicking forward button on toolbar
history.go(location) – goes to the specified history location.
Example:
history.go(-1) is the same as history.back().
history.go(1) is the same as history.forward().
96 By.Abrahim A.
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.
Properties Methods
MAX_VALUE toExponential()
MIN_VALUE toFixed()
NaN toLocaleString()
NEGATIVE_INFINITY toString()
POSITIVE_INFINITY toPrecision()
valueOf()
Use the toFixed() method when you want to format a number with a
specific number of digits to the right of the decimal.
This is the method you use, for instance, to display the results of a
financial calculation.
If the number being formatted has more numbers to the right of the
decimal, the method rounds the rightmost visible digit.
Example:
var num = 123.455;
num=num.toFixed(2);
99 By.Abrahim A.
alert(num); //123.46
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
num.toPrecision(1); // result = 1e+2
num.toPrecision(2) ; // result = 1.2e+2
num.toPrecision(3) ; // result = 123
num.toPrecision(4) ; // result = 123.5
num.toPrecision(5) ; // result = 123.45
num.toPrecision(6) ; // result = 123.450
100 By.Abrahim A.
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:
window.open() - this method opens a new window. The syntax is:
Parameters:
URL is a string that points to the window you want to open.
name is a string that names the new window.
101 By.Abrahim A.
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
102 By.Abrahim A.
window.open(“btest2.html”, “testing ”, “toolbar=yes,status=yes”);
JavaScript Objects and Events…
In a more controlled way using windowfeatures:
newWin=window.open("", "New", "height=250, width=250,
toolbar=no, scrollbars=yes, menubar=no");
newWin.document.write("<TITLE>Title Goes Here</TITLE>");
newWin.document.write("<BODY BGCOLOR=pink>");
newWin.document.write("<h1>Hello!</h1>");
newWin.document.write("This text will appear in the window!");
newWin.document.write("</BODY>");
newWin.document.write("</HTML>");
newWin.document.close();
103 By.Abrahim A.
Method Description
window.alert(message) Displays an alert dialog.
window.back() Moves back one in the window history.
window.blur() Sets focus away from the window.
window.captureEvents((Event.eventType) Registers the window to capture all specified events.
window.clearInterval(intervalID) Clears a delay that’s been set for a specific function.
window.clearTimeout(timeoutID) Clears the delay set by window.setTimeout().
window.close() Closes the current window.
window.confirm(message) Displays a dialog with a message that the user needs to respond to.
window.dump(message) Writes a message to the console.
window.escape(text) Encodes a string.
window.focus() Sets focus on the current window.
window.forward() Moves the window one document forward in the history.
window.getAttention() Flashes the application icon to get user attention.
window.getSelection() Returns the selection object representing the selected item(s).
window.home() Returns the browser to the home page.
window.moveBy(pixelX, pixelY) Moves the current window by a specified amount.
window.moveTo(x, y) Moves the window to the specified coordinates.
window.open(URL,name[,features]) Opens a new window.
window.print() Prints the current document.
window.prompt(message[,default]) Returns the text entered by the user in a prompt dialog.
window.releaseEvents(Event.eventType) Releases the window from trapping events of a specific type.
window.resizeBy(pixelX, pixelY) Resizes the current window by a certain amount.
window.resizeTo(iWidth, iHeight) Dynamically resizes window.
window.scroll(x-coord, y-coord) Scrolls the window to a particular place in the document.
window.scrollBy(pixelX, pixelY) Scrolls the document in the window by the given amount.
window.scrollByLines(lines) Scrolls the document by the given number of lines.
window.scrollByPages(pages) Scrolls the current document by the specified number of pages.
window.scrollTo(x-coord, y-coord) Scrolls to a particular set of coordinates in the document.
window.setCursor(cursortype)
104 Changes the cursor. By.Abrahim A.
window.setInterval(“funcName”, delay) Set a delay for a specific function.
JavaScript Objects and Events…
Some of the properties of Window object are:
window.name - Gets/sets the name of the window.
window.location - Gets/sets the location, or current URL, of the
window object.
window.status - Gets/sets the text in the statusbar at the bottom of
the browser.
window.statusbar - Returns the statusbar object, whose visibility
can be toggled in the window.
window.toolbar - Returns the toolbar object, whose visibility can be
toggled in the window.
window.menubar - Returns the menubar object, whose visibility
can be toggled in the window.
window.length - Returns the number of frames in the window.
105 By.Abrahim A.
<html>
<head>
<title>Show Title</title>
<script language="JavaScript">
var t = setInterval("showTime()",100);
function showTime()
{
var dt = new Date();
var hr = dt.getHours();
var min = dt.getMinutes();
var sec = dt.getSeconds();
if(min < 10) //append 0 if minutes < 10
min = "0" + min;
if(sec < 10) //append 0 if seconds < 10
sec = "0" + sec;
document.display.time.value = hr + ":" + min + ":" + sec;
}
</script>
</head>
<body>
<form name="display">
<input type="text" name="time">
</form>
106 </body> By.Abrahim A.
</html>
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:
document.images[2].propertyName
document.images.imagename.propertyName
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.
107 By.Abrahim A.
JavaScript Objects and Events…
Properties…
Prototype - Lets you add properties to an Image object.
108 By.Abrahim A.
Example: image slide show using JavaScript
<html>
<head>
<script language="JavaScript">
var photonames = new Array('coffee.png', 'didessa.png',
'Ethiopia_regions.png',
‘suura.jpg', 'desert.jpg');
var tt = setInterval("slideshow()", 2000);
Var currentphoto = 0;
function slideshow()
{
currentphoto++;
if(currentphoto > photonames.length - 1)
currentphoto = 0;
document.images.photo.src = photonames[currentphoto];
}
</script>
</head>
<body>
<img src="coffee.png" id="photo" height="80%"> <br>
109
</body> By.Abrahim A.
</html>
Form Processing and Validation
It is possible to access form and form elements from
JavaScript.
You can set attributes for NAME, TARGET, ACTION,
The value property of the input text box, is both readable and
writable.
To access text input fields, you can use the syntax:
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.
Event handlers:
onFocus - executed when input focus enters the field.
onBlur - executed when input focus leaves the field.
onChange - executed when input focus A.exits the field and the field
By.Abrahim
118
value has changed since the focus event
<HTML>
<HEAD>
<TITLE>List Box Test</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function testSelect () {
var Item = document.test.list.selectedIndex;
result = document.test.list.options[Item].text;
//Or you can use the following line which does the same as the above line
result = document.test.list.value;
alert (result);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME=“test" ACTION="fruits.php" METHOD="GET">
Fruit: <SELECT NAME="list" SIZE="1">
<OPTION>none</OPTION>
<OPTION>Orange</OPTION>
<OPTION>Apple</OPTION>
<OPTION>Papaya</OPTION>
<OPTION>Banana</OPTION>
</SELECT>
<INPUT TYPE="button" NAME="button" value="Test" onClick="testSelect()">
119 </FORM> By.Abrahim A.
</BODY>