Java Script
Java Script
JavaScript
T.Shanmugapriya
Introduction
What is it?
How does it work?
What is Java?
Learning JavaScript
JavaScript Statements
JavaScript and HTML forms
What is JavaScript?
Browsers have limited functionality
Text, images, tables, frames
Site navigation
Perform calculations
Validation of input
Other technologies
javascript.internet.com
Executes on client
Fast, no connection needed once loaded
What is Java?
Totally different
A full programming language
Much harder!
A compiled language
Independent of the web
Sometimes used together
JavaScript Statements
<html>
<head><title>My Page</title></head>
<body>
<script language="JavaScript">
document.write('This is my first JavaScript
Page');
</script>
</body>
</html>
JavaScript Statements
<html>
<head><title>My Page</title></head>
<body>
<script language=JavaScript">
document.write('<h1>This is my first
JavaScript Page</h1>');
</script>
</body>
</html>
HTML written
inside JavaScript
JavaScript Statements
<html>
<head><title>My Page</title></head>
<body>
<p>
<a href="myfile.html">My Page</a>
<br />
<a href="myfile.html"
onMouseover="window.alert('Hello');">
My Page</A>
</p>
</body>
JavaScript written
An Event
</html>
inside HTML
Example Statements
<script language="JavaScript">
window.prompt('Enter your name:','');
Another event
</script>
<form>
<input type="button" Value="Press"
onClick="window.alert('Hello');">
</form>
Note quotes: " and '
JavaScript Comments
Comments can be added to explain
the JavaScript, or to make the code
more readable.
Single line comments start with //.
The following example uses single
line comments to explain the code:
Example
<script type="text/javascript">
// Write a heading
document.write("<h1>This is a heading</h1>");
// Write two paragraphs:
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another
paragraph.</p>");
</script>
JavaScript Multi-Line
Comments
Multi line comments start with /* and
end with */.
The following example uses a multi
line comment to explain the code:
Example
<script type="text/javascript">
/*
The code below will write
one heading and two paragraphs
*/
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another
paragraph.</p>");
</script>
welcome.html
(1 of 1)
welcome2.html
(1 of 1)
welcome3.html
1 of 1
welcome4.html
1 of 1
welcome5.html
(1 of 2)
23
24
</head>
25
26
<body>
27
28
</body>
29 </html>
welcome5.html
(2 of 2)
Adding Integers
Prompt user for two integers and
calculate the sum NaN (not a number)
parseInt
Converts its string argument to an
integer
Addition.html
(1 of 2)
Addition.html
(2 of 2)
Arithmetic
Many scripts perform arithmetic
calculations
Expressions in JavaScript must be written in
straight-line form
Arithmetic
Arithmetic
Step 1. y = 2 * 5 * 5 + 3 * 5 + 7;
2 * 5 is 10
(Leftmost multiplication)
Step 2. y = 10 * 5 + 3 * 5 + 7;
10 * 5 is 50
(Leftmost multiplication)
Step 3. y = 50 + 3 * 5 + 7;
3 * 5 is 15
Step 4. y = 50 + 15 + 7;
50 + 15 is 65
(Leftmost addition)
Step 5. y = 65 + 7;
65 + 7 is 72
Step 6. y = 72;
(Last addition)
(Last operationplace72intoy )
Example
x=5+5;
document.write(x);
x="5"+"5";
document.write(x);
x=5+"5";
document.write(x);
x="5"+5;
document.write(x);
Logical Operators
More logical operators
Logical AND ( && )
Logical OR ( || )
Logical NOT ( ! )
Logical Operators
Truth table for the || (logical OR) operator.
Logical Operators
Precedence and associativity
Conditional Statements
In JavaScript we have the following conditional
statements:
if statement - use this statement to execute
some code only if a specified condition is true
if...else statement - use this statement to
execute some code if the condition is true and
another code if the condition is false
if...else if....else statement - use this
statement to select one of many blocks of code to
be executed
switch statement - use this statement to select
one of many blocks of code to be executed
If Statement
Use the if statement to execute some code only if
a specified condition is true.
Syntax
if (condition)
{
codetobeexecutedifconditionistrue
}
Example
<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10
var d=new Date();
var time=d.getHours();
if (time<10)
{
document.write("<b>Good morning</b>");
}
</script>
If...else Statement
Use the if....else statement to execute some code if a
condition is true and another code if the condition is not
true.
Syntax
if (condition)
{
codetobeexecutedifconditionistrue
}
else
{
codetobeexecutedifconditionisnottrue
}
Example
<script type="text/javascript">
//If the time is less than 10, you will get a "Good morning"
greeting.
//Otherwise you will get a "Good day" greeting.
var d = new Date();
var time = d.getHours();
if (time < 10)
{
document.write("Good morning!");
}
else
{
document.write("Good day!");
}
</script>
Example
<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>");
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>");
}
else
{
document.write("<b>Hello World!</b>");
}
</script>
Example
<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date();
theDay=d.getDay();
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>
Function Definitions
Format of a function definition
function function-name( parameter-list )
{
declarationsandstatements
}
Function Definitions
Returning control
return statement
Function Definitions
Writing a function to square two
numbers
for loop from 1 to 10
by itself
Display result
22
23
of variable x.
24
25
26
function square( y )
27
28
return y * y;
29
30
// -->
31
</script>
32
33
</head><body></body>
34 </html>
Function Definitions
Function Definitions
Finding the maximum of 3
numbers
Prompt for 3 inputs
Convert to numbers
Pass to maximum
Math.max
24
25
26
27
28
29
30
31
32
33
function maximum( x, y, z )
34
35
36
37
// -->
38
</script>
39
40
</head>
41
<body>
42
43
44 </html>
Function Definitions
Function Definitions
JavaScript Loops
In JavaScript, there are two different kind
of loops:
for - loops through a block of code a
specified number of times
while - loops through a block of code
while a specified condition is true
Example
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
Example
<html>
<body>
<script type="text/javascript">
var i=0;
while (i<=5)
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
</script>
</body>
</html>
Example
<html>
<body>
<script type="text/javascript">
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
while (i<=5);
</script>
</body>
</html>
Example
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
Example
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
Example
<html>
<body>
<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
</script>
</body>
</html>
Alert Box
An alert box is often used if you want to
make sure information comes through to
the user.
When an alert box pops up, the user will
have to click "OK" to proceed.
Syntax
alert("sometext");
Example
<html>
<head>
<script type="text/javascript">
function show_alert()
{
alert("I am an alert box!");
}
</script>
</head>
<body>
<input type="button" onclick="show_alert()" value="Show
alert box" />
</body>
</html>
Confirm Box
A confirm box is often used if you want the user
to verify or accept something.
When a confirm box pops up, the user will have
to click either "OK" or "Cancel" to proceed.
If the user clicks "OK", the box returns true. If
the user clicks "Cancel", the box returns false.
Syntax
confirm("sometext");
Example
<html>
<head>
<script type="text/javascript">
function show_confirm()
{
var r=confirm("Press a button");
if (r==true)
{
alert("You pressed OK!");
}
else
{
alert("You pressed Cancel!");
}
}
</script>
</head>
<body>
<input type="button" onclick="show_confirm()" value="Show confirm box" />
</body>
</html>
Prompt Box
A prompt box is often used if you want the user
to input a value before entering a page.
When a prompt box pops up, the user will have to
click either "OK" or "Cancel" to proceed after
entering an input value.
If the user clicks "OK" the box returns the input
value. If the user clicks "Cancel" the box returns
null.
Syntax
prompt("sometext","defaultvalue");
JavaScript Functions
How to Define a Function
Syntax
function
functionname(var1,var2,...,varX)
{
somecode
}
Example
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
Example
Contd...
<body>
<form>
<input type="button" value="Click
me!" onclick="displaymessage()" />
</form>
</body>
</html>
Events
Events are actions that can be detected by
JavaScript.
Examples of events:
A mouse click
A web page or an image loading
Mousing over a hot spot on the web page
Selecting an input field in an HTML form
Submitting an HTML form
A keystroke
onSubmit
The onSubmit event is used to validate
ALL form fields before submitting it.
<form method="post" action=abc.htm"
onsubmit="return checkForm()">
Example
<html>
<head>
<script type="text/javascript">
var txt="";
function message()
{
try
{
adddlert("Welcome guest!");
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.description + "\n\n";
Example
Contd...
txt+="Click OK to continue.\n\n";
alert(txt);
}
}
</script>
</head>
<body>
<input type="button" value="View message"
onclick="message()" />
</body>
</html>
Example
<html>
<body>
<script type="text/javascript">
var x=prompt("Enter a number between 0 and 10:","");
try
{
if(x>10)
{
throw "Err1";
}
else if(x<0)
{
throw "Err2";
}
else if(isNaN(x))
{
throw "Err3";
}
}
Example
Contd...
catch(er)
{
if(er=="Err1")
{
alert("Error! The value is too high");
}
if(er=="Err2")
{
alert("Error! The value is too low");
}
if(er=="Err3")
{
alert("Error! The value is not a number");
}
}
</script>
</body>
</html>
JavaScript Objects
JavaScript is an Object Oriented
Programming (OOP) language.
An OOP language allows you to define
your own objects and make your own
variable types.
Introduction
Use JavaScript to manipulate every
element of XHTML document from a
script
Reference for several of JavaScripts
built-in objects
Demonstrates the capabilities
Math Object
Allow the programmer to perform
many common mathematical
calculations
12.3
Math Object
Description
Example
Method
abs( x )
absolute value of x
Math Object
min( x, y ) smaller value of x
and y
pow( x, y ) x raised to power y
(xy)
round( x ) rounds x to the
closest integer
trigonometric sine of
sin( x )
x (x in radians)
square root of x
sqrt( x )
Math Object
Constant
Math.E
Description
Base of a natural
logarithm (e).
Natural logarithm of 2.
Math.LN2
Natural logarithm of 10.
Math.LN10
Base 2 logarithm of e.
Math.LOG2E
Math.LOG10E Base 10 logarithm of e.
Math.PI
the ratio of a circles
circumference to its
diameter.
Math.SQRT1_2 Square root of 0.5.
Square root of 2.0.
Math.SQRT2
Fig. 12.2 Properties of the Math object.
Value
Approximately 2.718.
Approximately 0.693.
Approximately 2.302.
Approximately 1.442.
Approximately 0.434.
Approximately
3.141592653589793.
Approximately 0.707.
Approximately 1.414.
Date Object
Provides methods for date and time
manipulations
Description
getDay()
getUTCDay()
Returns a number from 0 (Sunday) to 6 (Saturday) representing the day of the week in local time or UTC,
respectively.
getFullYear()
getUTCFullYear()
getHours()
getUTCHours()
getMilliseconds()
getUTCMilliSeconds()
getMinutes()
getUTCMinutes()
getMonth()
getUTCMonth()
getSeconds()
getUTCSeconds()
getTime()
Returns a number from 0 to 59 representing the minutes for the time in local time or UTC, respectively.
getTimezoneOffset()
Returns the difference in minutes between the current time on the local computer and UTCpreviously
known as Greenwich Mean Time (GMT).
setDate( val )
setUTCDate( val )
Fig. 12.8
Methods of the Date object.
Sets the day of the month (1 to 31) in local time or UTC, respectively.
getDate()
getUTCDate()
Returns a number from 1 to 31 representing the day of the month in local time or UTC, respectively.
Returns a number from 0 to 23 representing hours since midnight in local time or UTC, respectively.
Returns a number from 0 to 999 representing the number of milliseconds in local time or UTC, respectively.
The time is stored in hours, minutes, seconds and milliseconds.
Returns a number from 0 (January) to 11 (December) representing the month in local time or UTC,
respectively.
Returns a number from 0 to 59 representing the seconds for the time in local time or UTC, respectively.
Returns the number of milliseconds between January 1, 1970 and the time in the Date object.
Description
setHours( h, m, s, ms )
setUTCHours( h, m, s, ms )
Sets the hour in local time or UTC, respectively. The second, third and fourth
arguments representing the minutes, seconds and milliseconds are optional. If
an optional argument is not specified, the current value in the Date object is
used.
setMilliSeconds( ms )
setUTCMilliseconds( ms )
setMinutes( m, s, ms )
setUTCMinutes( m, s, ms )
setMonth( m, d )
setUTCMonth( m, d )
Sets the month in local time or UTC, respectively. The second argument
representing the date is optional. If the optional argument is not specified, the
current date value in the Date object is used.
setSeconds( s, ms )
setUTCSeconds( s, ms )
Sets the second in local time or UTC, respectively. The second argument
representing the milliseconds is optional. If this argument is not specified, the
current millisecond value in the Date object is used.
setFullYear( y, m, d )
setUTCFullYear( y, m, d )
Fig. 12.8
Sets the year in local time or UTC, respectively. The second and third
arguments representing the month and the date are optional. If an optional
argument is not specified, the current value in the Date object is used.
Sets the minute in local time or UTC, respectively. The second and third
arguments representing the seconds and milliseconds are optional. If an
optional argument is not specified, the current value in the Date object is
used.
Description
toLocaleString()
Returns a string representation of the date and time in a form specific to the
computers locale. For example, September 13, 2001 at 3:42:22 PM is
represented as 09/13/01 15:47:22 in the United States and 13/09/01
15:47:22 in Europe.
toUTCString()
Returns a string representation of the date and time in the form: 19 Sep
2001 15:47:22 UTC
toString()
Returns a string representation of the date and time in a form specific to the
locale of the computer (Mon Sep 19 15:47:22 EDT 2001 in the United
States).
valueOf()
setTime( ms )
Fig. 12.8
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5
-->
7
8
9
10
11
12
DateTime.html
1 of 3
13
<!--
14
15
16
17
18
document.writeln(
"<h1>String representations and valueOf</h1>" );
document.writeln( "toString: " + current.toString() +
19
20
21
22
23
24
document.writeln(
"<h1>Get methods for local time zone</h1>" );
25
26
27
28
29
30
31
32
33
34
current.getMilliseconds() +
35
36
current.getTimezoneOffset() );
37
38
39
document.writeln(
DateTime.html
2 of 3
40
41
42
43
44
document.writeln(
"<h1>Set methods for local time zone</h1>" );
45
anotherDate.setDate( 31 );
46
anotherDate.setMonth( 11 );
47
anotherDate.setFullYear( 2001 );
48
anotherDate.setHours( 23 );
49
anotherDate.setMinutes( 59 );
50
anotherDate.setSeconds( 59 );
51
52
// -->
53
</script>
54
55
</head><body></body>
56 </html>
Method
toString()
valueOf()
Fig. 12.10
Description
Returns the string true if the value of the Boolean object is
true; otherwise, returns the string false.
Returns the value true if the Boolean object is true; otherwise,
returns false.
Boolean object methods.
Method or Property
toString( radix )
Description
Returns the string representation of the number. The optional radix
argument (a number from 2 to 36) specifies the numbers base. For
example, radix 2 results in the binary representation of the number,
8 results in the octal representation, 10 results in the decimal
representation and 16 results in the hexadecimal representation.
See Appendix E, Number Systems for a review of the binary, octal,
decimal and hexadecimal number systems.
Returns the numeric value.
valueOf()
This property represents the largest value that can be stored in a
Number.MAX_VALUE
JavaScript programapproximately 1.79E+308
This property represents the smallest value that can be stored in a
Number.MIN_VALUE
JavaScript programapproximately
2.22E308
This property represents not a numbera value returned from an
Number.NaN
arithmetic expression that does not result in a number (e.g., the
expression parseInt( "hello" ) cannot convert the string
"hello" into a number, so parseInt would return
Number.NaN. To determine whether a value is NaN, test the
result with function isNaN, which returns true if the value is
NaN; otherwise, it returns false.
This property represents a value less than
Number.NEGATIVE_INFINITY
-Number.MAX_VALUE.
This property represents a value greater than
Number.POSITIVE_INFINITY
Number.MAX_VALUE.
Fig. 12.11 Number object methods and properties.
Mathematical Constants
Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E
Mathematical Methods
Few Examples:
document.write(Math.round(4.7));
document.write(Math.random());
document.write(Math.floor(Math.random()*11));
Description
anchor()
big()
blink()
bold()
charAt()
charCodeAt()
concat()
fixed()
fontcolor()
fontsize()
fromCharCod
e
()
indexOf()
String Object
italics()
lastIndexOf()
link()
match()
replace()
search()
slice()
small()
split()
strike()
String object
sub()
substr()
substring()
sup()
toLowerCase()
toUpperCase()
toSource()
valueOf()
constructor
length
prototype
CharAt method
Index of Method
The indexOf() method returns the position of the first
occurrence of a specified string value in a string.
stringObject.indexOf(searchvalue,fromindex)
Substring method
The substring() method extracts the characters in a string
between two specified indices.
Syntax
stringObject.substring(start,stop)
we will use substring() to extract some characters from a string:
<script type="text/javascript">
var str="Hello world!";
document.write(str.substring(3));
</script>
The output of the code above will be:
lo world!
<script type="text/javascript">
var str="Hello world!";
document.write(str.substring(3,7));
</script>
The output of the code above will be:
lo w
toSource method
<script type="text/javascript">
var str="Hello world!";
document.write(str.substring(3,7));
</script>
The output of the code above will be:
lo w
The toSource() method represents the source code of an object.
object.toSource()
<script type="text/javascript">
function employee(name,jobtitle,born)
{this.name=name;
this.jobtitle=jobtitle;this.born=born;}
var fred=new employee("Fred Flintstone","Caveman",1970);
document.write(fred.toSource());
</script>
The output of the code above will be:
({name:"Fred Flintstone", jobtitle:"Caveman", born:1970})
Slice
The slice() method extracts a part of a string and returns
the extracted part in a new string.
Syntax
stringObject.slice(start,end)
Specify where to start the selection. Must be a
numberendOptional. Specify where to end the selection.
Must be a number.
In this example we will extract all characters from a string,
starting at position 6:
<script type="text/javascript">var str="Hello happy
world!";document.write(str.slice(6));</script>
The output of the code above will be:
happy world!
Search
The search() method is used to search a string
for a specified value.
Syntax
stringObject.search(searchstring)
The value to search for in a string. To perform a
case-insensitive search add an 'i' flag.
In the following example we will search for the word
"W3Schools":
<script type="text/javascript">var str="Visit
W3Schools!";document.write(str.search(/W3Scho
ols/));</script>
The output of the code above will be:
6
Replace
The replace() method is used to replace some characters with
some other characters in a string.
Syntax
stringObject.replace(findstring,newstring)
Specifies a string value to find. To perform a global search add a
'g' flag to this parameter and to perform a case-insensitive search
add an 'i' flagnewstringRequired.
Specifies the string to replace the found value from findstring.
In the following example we will replace the word Microsoft with
W3Schools:
<script type="text/javascript">var str="Visit
Microsoft!";document.write(str.replace(/Microsoft/,
"W3Schools"));</script>
The output of the code above will be:
Visit W3Schools!
Match method
<script type="text/javascript">
var str="Hello world!";
document.write(str.match("world") +
"<br />");
document.write(str.match("World") +
"<br/>");
document.write(str.match("worlld") +
"<br />");
document.write(str.match("world!"));
</script>
The output of the code above will be:
worldnullnullworld!
Split method
<script type="text/javascript">var
str="How are you doing today?";
document.write(str.split(" ") + "<br />");
document.write(str.split("") + "<br />");
document.write(str.split(" ",3));
</script>
The output of the code above will be:
How,are,you,doing,today?H,o,w, ,a,r,e,
,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?How,are,you
2)
var myCars=new
Array("Saab","Volvo","BMW"); // condensed
array
3)
var myCars=["Saab","Volvo","BMW"]; //
literal array
Access an Array
document.write(myCars[0]);
Array Object
concat()
join()
pop()
push()
reverse()
shift()
slice()
Array Object
sort()
splice()
valueOf(
)
Join method
The join() method is used to put all the elements of an
array into a string.
The elements will be separated by a specified separator.
Syntax
arrayObject.join(separator)
Specifies the separator to be used.
we will create an array, and then put all the elements in a
string:
<script type="text/javascript">var arr = new
Array(3);arr[0] = "Jani";arr[1] = "Hege";arr[2] =
"Stale";document.write(arr.join() + "<br
/>");document.write(arr.join("."));</script>
Push method
The push() method adds one or more elements to the end of an
array and returns the new length.
Syntax
arrayObject.push(newelement1,newelement2,....,newelementX)
The first element to add to the arraynewelement2Optional. The
second element to add to the arraynewelementXOptional.
Several elements may be added.
In this example we will create an array, and then change the
length of it by adding a element:
<script type="text/javascript">var arr = new Array(3);arr[0] =
"Jani";arr[1] = "Hege";arr[2] = "Stale";document.write(arr +
"<br />");document.write(arr.push("Kai Jim") + "<br
/>");document.write(arr);</script>
The output of the code above will be:
Jani,Hege,Stale
Jani,Hege,Stale,Kai Jim
Slice method
<script type="text/javascript">
var arr = new Array(3);
arr[0] = "Jani";arr[1] = "Hege";
arr[2] = "Stale";
document.write(arr + "<br />");
document.write(arr.slice(1) + "<br />");
document.write(arr);
</script>
The output of the code above will be:
Jani,Hege,Stale
Hege,Stale
Jani,Hege,Stale
Sorting
<script type="text/javascript">
var arr = new Array(6);
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";
arr[5] = "Tove";
document.write(arr + "<br />");
document.write(arr.sort());</script>
Splice method
The splice() method is used to remove and add new elements to an array.
Syntax
arrayObject.splice(index,howmany,element1,.....,elementX)
Specify where to add/remove elements.
Must be a numberhowmanyRequired
Specify how many elements should be removed. Must be a number, but
can be "0"element1Optional.
Specify a new element to add to the arrayelementXOptional. Several
elements can be added
<script type="text/javascript">
var arr = new Array(3);
arr[0] = "Jani";arr[1] = "Hege";
arr[2] = "Stale";
document.write(arr.toString());
</script>
The output of the code above will be:
Jani,Hege,Stale
JavaScript Cookies
A cookie is a variable that is stored on the visitor's computer. Each
time the same computer requests a page with a browser, it will
send the cookie too. With JavaScript, you can both create and
retrieve cookie values.
Examples of cookies:
Name cookie - The first time a visitor arrives to your web page, he
or she must fill in her/his name. The name is then stored in a
cookie. Next time the visitor arrives at your page, he or she could
get a welcome message like "Welcome John Doe!" The name is
retrieved from the stored cookie
Password cookie - The first time a visitor arrives to your web
page, he or she must fill in a password. The password is then
stored in a cookie. Next time the visitor arrives at your page, the
password is retrieved from the cookie
Date cookie - The first time a visitor arrives to your web page, the
current date is stored in a cookie. Next time the visitor arrives at
your page, he or she could get a message like "Your last visit was
on Tuesday August 11, 2005!" The date is retrieved from the
stored cookie
JavaScript Cookies
A cookie is often used to identify a user.
Create and Store a Cookie
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" :
";expires="+exdate.toUTCString());
}
Using Cookies
Cookie
Data stored on users computer to maintain
information about client during and between
browser sessions
Can be accessed through cookie property
Set expiration date through expires property
Use escape function to convert nonalphanumeric characters to hexadecimal escape
sequences
unescape function converts hexadecimal escape
sequences back to English characters
cookie.html
1 of 4
cookie.html
2 of 4
cookie.html
3 of 4
74
75
76
<body>
<p>Click Refresh (or Reload) to run the script again</p>
</body>
77 </html>
cookie.html
4 of 4
Event Modeling
Event
Description
Keyboard events
onhelp
onkeydown
onkeypress
onkeyup
Marquee events
onbounce
onfinish
onstart
Mouse events
oncontextmenu
ondblclick
ondrag
ondragend
ondragenter
ondragleave
ondragover
ondragstart
Fires when the user initiates help (i.e., by pressing the F1 key).
Fires when the user pushes down a key.
Fires when the user presses a key.
Fires when the user ends a key press.
Fires when a scrolling marquee bounces back in the other
direction.
Fires when a marquee finishes its scrolling.
Fires when a marquee begins a new loop.
Event
onmouseup
Miscellaneous events
onafterprint
onbeforeeditfocus
onbeforeprint
onbeforeunload
Description
Fires when a mouse button is released.
onabort
onblur
onchange
onclick
ondblclick
onerror
onfocus
onkeydown
onkeypress
onkeyup
onload
onmousedown
onmousemove
onmouseout
onmouseover
onmouseup
onreset
onresize
onselect
Text is selected
<form name="addressform">
Name: <input name="yourname"><br />
Phone: <input name="phone"><br />
Email: <input name="email"><br />
</form>
<form name="alertform">
Enter your name:
<input type="text" name="yourname">
<input type="button" value= "Go"
onClick="window.alert('Hello ' +
document.alertform.yourname.value);">
</form>
E-mail Validation
function validate_email(field,alerttxt)
{
with (field)
{
apos=value.indexOf("@");
dotpos=value.lastIndexOf(".");
if (apos<1||dotpos-apos<2)
{alert(alerttxt);return false;}
else {return true;}
}
}
JavaScript Animation
It is possible to use JavaScript to create
animated images.
The HTML code looks like this:
<a href="http://www.annauniv.edu"
target="_blank">
<img border="0" alt="Visit AnnaUniv!"
src="b_pink.gif" id="b1"
onmouseOver="mouseOver()"
onmouseOut="mouseOut()" /></a>
document Object
Method or Property
write( string )
Description
Writes the string to the XHTML document as
XHTML code.
Writes the string to the XHTML document as
writeln( string )
XHTML code and adds a newline character at
the end.
This property is a string containing the values
document.cookie
of all the cookies stored on the users computer
for the current document. See Section 12.9,
Using Cookies.
This property is the date and time that this
document.lastModified
document was last modified.
Fig. 12.12
Important document object methods and properties.
window Object
Provides methods for manipulating
browser window
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5
-->
-->
7
8
<head>
window.html
1 of 7
<!--
14
15
16
function createChildWindow()
17
18
19
20
21
22
23
24
25
26
27
28
if ( toolBarCheckBox.checked )
29
30
31
toolBar = "yes";
else
toolBar = "no";
32
33
34
if ( menuBarCheckBox.checked )
35
36
37
menuBar = "yes";
else
menuBar = "no";
38
window.html
2 of 7
39
40
if ( locationCheckBox.checked )
41
42
43
location = "yes";
else
location = "no";
44
45
46
if ( scrollBarsCheckBox.checked )
47
48
49
50
scrollBars = "yes";
else
scrollBars = "no";
51
52
if ( statusCheckBox.checked )
53
54
55
status = "yes";
else
status = "no";
56
57
58
if ( resizableCheckBox.checked )
59
60
61
resizable = "yes";
else
resizable = "no";
62
window.html
3 of 7
63
64
65
66
67
68
69
// disable buttons
70
closeButton.disabled = false;
71
modifyButton.disabled = false;
72
getURLButton.disabled = false;
73
setURLButton.disabled = false;
74
75
76
77
function modifyChildWindow()
78
79
if ( childWindow.closed )
80
81
else
82
83
childWindow.document.write( textForChild.value );
} // end function modifyChildWindow
84
85
86
function closeChildWindow()
87
88
89
90
91
if ( childWindow.closed )
window.html
4 of 7
92
93
closeButton.disabled = true;
94
modifyButton.disabled = true;
95
getURLButton.disabled = true;
96
setURLButton.disabled = true;
97
98
99
// copy the URL of the child window into the parent windows myChildURL
100
function getChildWindowURL()
101
102
if ( childWindow.closed )
103
104
else
105
106
myChildURL.value = childWindow.location;
} // end function getChildWindowURL
107
108
109
110
function setChildWindowURL()
111
112
window.html
5 of 7
if ( childWindow.closed )
113
114
115
childWindow.location = myChildURL.value;
116
117
//-->
118 </script>
119
120 </head>
121
122 <body>
123 <h1>Hello, This is the main window</h1>
124 <p>Please check the features to enable for the child window<br/>
125
126
127
<label>Tool Bar</label>
128
129
130
<label>Menu Bar</label>
131
132
133
<label>Address Bar</label><br/>
134
window.html
6 of 7
135
136
<label>Scroll Bars</label>
137
138
139
<label>Status Bar</label>
140
141
142
<label>Resizable</label><br/></p>
143
144 <p>Please enter the text that you would like to display
145
146
147
148
149
150
151
152
153
154
155 <p>The other window's URL is: <br/>
156
157
158
159
160
window.html
7 of 7
161
162 </body>
163 </html>
window Object
Method or Property
open( url, name, options )
Description
Creates a new window with the URL of the window set to
url, the name set to name, and the visible features set by
the string passed in as option.
Displays a dialog box asking the user for input. The text
prompt( prompt, default )
of the dialog is prompt, and the default value is set to
default.
Closes the current window and deletes its object from
close()
memory.
This method gives focus to the window (i.e., puts the
window.focus()
window in the foreground, on top of any other open
browser windows).
This property contains the document object representing
window.document
the document currently inside the window.
This property contains a boolean value that is set to true if
window.closed
the window is closed, and false if it is not.
This property contains the window object of the window
window.opener
that opened the current window, if such a window exists.
Fig. 12.14
Important window object methods and properties.
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5
-->
7
8
9
10
11
12
final.html
1 of 6
13
<!--
14
15
16
17
18
var pictures =
19
20
21
22
23
24
25
26
27
28
29
30
31
if ( hour < 12 )
32
33
else
34
35
36
final.html
2 of 6
37
38
if ( hour < 6 )
39
40
else
41
42
43
44
45
if ( document.cookie )
46
47
48
// english notation
49
50
51
52
53
54
// set name to the part of the cookie that follows the = sign
55
name = cookieTokens[ 1 ];
56
57
else
58
59
60
final.html
3 of 6
61
62
63
64
65
66
67
68
document.writeln(
69
70
71
72
73
74
75
76
77
78
".gif\" width= \" 105 \" height= \" 100 \" /> <br/>" );
79
80
81
82
83
84
function allQuotes()
85
final.html
4 of 6
86
87
88
89
" scrollBars=yes" );
90
quoteWindow.document.write( "<p>" )
91
92
// loop through all quotes and write them in the new window
93
94
95
96
97
98
99
"JavaScript:window.close()\">" +
100
101
102
103
104
function wrongPerson()
105
106
107
document.cookie= "name=null;" +
108
final.html
5 of 6
109
110
// after removing the cookie reload the page to get a new name
111
location.reload();
112
113
114
115
function openQuiz()
116
117
118
119
120
121
}
// -->
122
</script>
123
124
</head>
125
126
127
<body>
<p><a href = "JavaScript:allQuotes()">View all quotes</a></p>
128
129
<p id = "quizSpot">
130
131
132
final.html
6 of 6
133
134
135
136
137
138
139
modDate.toLocaleString() );
</script>
140
141
</body>
142 </html>
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5
-->
7
8
<head>
10 <title>Online Quiz</title>
11
12 <script type = "text/JavaScript">
13
<!--
14
function checkAnswers()
15
quiz2.html
1 of 3
16
17
if ( myQuiz.radiobutton[ 1 ].checked )
18
19
20
21
window.opener.quizSpot.innerText =
"Congratulations, your answer is correct";
else // if the answer is incorrect
window.opener.quizSpot.innerHTML = "Your answer is incorrect." +
22
" Please try again <br /> <a href= \" JavaScript:openQuiz()" +
23
24
25
window.opener.focus();
26
window.close();
27
28
//-->
29 </script>
30
31 </head>
32
33 <body>
34
35
36
37
38
39
quiz2.html
2 of 3
40
41
42
43
44
<label>Error-Prevention Tip</label>
45
46
47
<label>Performance Tip</label>
48
49
50
51
52
53
54
</p>
55
</form>
56 </body>
57 </html>
quiz2.html
3 of 3
THANK YOU