JavaScript
JavaScript
JavaScript 2
History
History
 First web scripting language
First web scripting language
 Developed by Netscape and Sun
Developed by Netscape and Sun
 Initiated by Netscape and called
Initiated by Netscape and called
LiveScript
LiveScript
 In parallel with this, Sun was
In parallel with this, Sun was
developing Java
developing Java
JavaScript 3
History
History
 Netscape and Sun got together and
Netscape and Sun got together and
realized that many of the
realized that many of the
specifications for Java could apply to
specifications for Java could apply to
LiveScript
LiveScript
 Result is JavaScript
Result is JavaScript
JavaScript 4
JavaScript Versus Java
JavaScript Versus Java
 JavaScript is interpreted while Java is
JavaScript is interpreted while Java is
compiled
compiled
– But server-side JavaScript is compiled
But server-side JavaScript is compiled
 JavaScript is object-based while Java is
JavaScript is object-based while Java is
object-oriented
object-oriented
– Object-based languages can utilize pre-
Object-based languages can utilize pre-
defined objects, but you are limited in
defined objects, but you are limited in
terms of creating your own objects
terms of creating your own objects
JavaScript 5
JavaScript Versus Java
JavaScript Versus Java
 JavaScript has loose data typing,
JavaScript has loose data typing,
while Java has strong data typing
while Java has strong data typing
– Loose data typing means that a variable
Loose data typing means that a variable
can hold any kind of data
can hold any kind of data
 JavaScript code is embedded in an
JavaScript code is embedded in an
HTML document while Java applets
HTML document while Java applets
are stand-alone applications that can
are stand-alone applications that can
be accessed from HTML
be accessed from HTML
JavaScript 6
JavaScript Versus Java
JavaScript Versus Java
 JavaScript has dynamic binding, while
JavaScript has dynamic binding, while
Java has static binding
Java has static binding
– Names bound at runtime
Names bound at runtime
 JavaScript can access browser objects
JavaScript can access browser objects
and functionality, while Java cannot
and functionality, while Java cannot
JavaScript 7
Client-Side JavaScript
Client-Side JavaScript
 Client-side JavaScript scripts operate
Client-side JavaScript scripts operate
on a client running Netscape
on a client running Netscape
Navigator (Microsoft Internet
Navigator (Microsoft Internet
Explorer also supports it now) and
Explorer also supports it now) and
are interpreted by Netscape
are interpreted by Netscape
Navigator
Navigator
JavaScript 8
Client-Side JavaScript
Client-Side JavaScript
 Detect whether the browser supports a
Detect whether the browser supports a
certain plug-in
certain plug-in
 Control a plug-in
Control a plug-in
 Validate user form input
Validate user form input
 Prompt a user for confirmation
Prompt a user for confirmation
 Perform post-processing of information
Perform post-processing of information
retrieved from server-side JavaScript
retrieved from server-side JavaScript
scripts
scripts
JavaScript 9
Server-Side JavaScript
Server-Side JavaScript
 JavaScript scripts that run on the
JavaScript scripts that run on the
server are called LiveWire
server are called LiveWire
applications because they use the
applications because they use the
Netscape LiveWire development
Netscape LiveWire development
environment
environment
– This is the only system that supports
This is the only system that supports
server-side JavaScript development
server-side JavaScript development
JavaScript 10
Server-Side JavaScript
Server-Side JavaScript
 Unlike CGI scripts, LiveWire
Unlike CGI scripts, LiveWire
applications are more closely
applications are more closely
integrated to the HTML pages that
integrated to the HTML pages that
control them
control them
– Can have a page that accepts credit card
Can have a page that accepts credit card
payments and gives user immediate
payments and gives user immediate
feedback
feedback on the same page
on the same page about
about
whether card was accepted
whether card was accepted
JavaScript 11
Client Scripts
Client Scripts
 To display error or information boxes
To display error or information boxes
 To validate user input
To validate user input
 To display confirmation boxes
To display confirmation boxes
 To process server data, such as
To process server data, such as
aggregate calculations
aggregate calculations
 To add programmable logic to HTML
To add programmable logic to HTML
JavaScript 12
Client Scripts
Client Scripts
 To perform functions that don’t
To perform functions that don’t
require information from the server
require information from the server
 To produce a new HTML page
To produce a new HTML page
without making a request to the
without making a request to the
server
server
JavaScript 13
Server Scripts
Server Scripts
 To maintain data shared among
To maintain data shared among
applications or clients
applications or clients
 To maintain information during client
To maintain information during client
accesses
accesses
 To access a database
To access a database
 To access server files
To access server files
 To call server C libraries
To call server C libraries
 To customize Java applets
To customize Java applets
JavaScript 14
Scripts
Scripts
 Client-side and server-side JavaScript
Client-side and server-side JavaScript
scripts are both embedded in an
scripts are both embedded in an
HTML file
HTML file
 For server-side JavaScript scripts, this
For server-side JavaScript scripts, this
HTML file is compiled with the
HTML file is compiled with the
LiveWire compiler
LiveWire compiler
– Creates a file that is in a platform-
Creates a file that is in a platform-
independent and compiled bytecode
independent and compiled bytecode
format
format
JavaScript 15
Scripts
Scripts
 Client-side JavaScript needs Netscape
Client-side JavaScript needs Netscape
Navigator and a standard HTML
Navigator and a standard HTML
server
server
 Server-side JavaScript needs the
Server-side JavaScript needs the
LiveWire compiler, the LiveWire
LiveWire compiler, the LiveWire
Application Manager, and a Netscape
Application Manager, and a Netscape
HTML server that supports the
HTML server that supports the
LiveWire server extension
LiveWire server extension
JavaScript 16
Scripts
Scripts
 Examples js1.htm, js2.htm, js3.htm
Examples js1.htm, js2.htm, js3.htm
 The
The <head>
<head> portion of an HTML page
portion of an HTML page
is the first to load, so it is best to
is the first to load, so it is best to
define the functions for a page in this
define the functions for a page in this
portion
portion
– Functions can be called in the
Functions can be called in the <body>
<body>
portion
portion
JavaScript 17
JavaScript Program Code
JavaScript Program Code
 Main body
Main body
 Event handlers
Event handlers
 Functions
Functions
JavaScript 18
Main Body
Main Body
 Main Body
Main Body
– Any code that is between
Any code that is between <script>
<script> and
and
</script>
</script> that is not a function definition
that is not a function definition
JavaScript 19
Events
Events
 Events
Events
– Mouse click
Mouse click
– Re-sizing window
Re-sizing window
JavaScript 20
Event Handlers
Event Handlers
 Event handlers
Event handlers
– Scripts that link events to JavaScript
Scripts that link events to JavaScript
functions
functions
– Embed in HTML documents as attributes
Embed in HTML documents as attributes
of HTML tags
of HTML tags
 <tag eventHandler = “JavaScript Code”>
<tag eventHandler = “JavaScript Code”>

Example js4.htm
Example js4.htm
JavaScript 21
More Events
More Events
 Top-level actions causing change in
Top-level actions causing change in
web page being displayed
web page being displayed
– Navigation
Navigation
– Interaction with an element of an HTML
Interaction with an element of an HTML
form
form
JavaScript 22
Navigation
Navigation
 Selecting a hypertext link
Selecting a hypertext link
 Moving forward or backward in the
Moving forward or backward in the
history list
history list
 Opening a new URL
Opening a new URL
 Quitting the browser
Quitting the browser
JavaScript 23
Navigation
Navigation
 In these events, some page is being
In these events, some page is being
loaded or unloaded
loaded or unloaded
– These are document-level events that
These are document-level events that
can be handled by JavaScript
can be handled by JavaScript
JavaScript 24
JavaScript Events
JavaScript Events
 button
button
– click
click
 checkbox
checkbox
– click
click
 document
document
– load
load
– unload
unload
JavaScript 25
JavaScript Events
JavaScript Events
 form
form
– submit
submit
 link
link
– click
click
– mouseover
mouseover
 radio
radio
– click
click
JavaScript 26
JavaScript Events
JavaScript Events
 selection
selection
– blur
blur
– change
change
– focus
focus
 submit
submit
– click
click
JavaScript 27
JavaScript Events
JavaScript Events
 text
text
– change
change
– focus
focus

A text field is said to have
A text field is said to have focus
focus when it is
when it is
currently accepting typed input
currently accepting typed input

Clicking anywhere inside a text item gives it focus
Clicking anywhere inside a text item gives it focus

Moving the mouse over the text field may give it
Moving the mouse over the text field may give it
focus
focus
– blur
blur

The opposite of focus
The opposite of focus
– select
select
JavaScript 28
JavaScript Events
JavaScript Events
 textarea
textarea
– blur
blur
– change
change
– focus
focus
– select
select
JavaScript 29
Functions
Functions
 Defining a function to create an object
Defining a function to create an object
function house(rms, stl, yr, gar){
function house(rms, stl, yr, gar){
this.rooms = rms;
this.rooms = rms;
this.style = stl;
this.style = stl;
this.yearBuilt = yr;
this.yearBuilt = yr;
this.hasGarage = gar;
this.hasGarage = gar;
}
}
var myhouse = new house(8, “Ranch”, 1990,
var myhouse = new house(8, “Ranch”, 1990,
true)
true)
JavaScript 30
Functions
Functions
 Every object is an array of its property
Every object is an array of its property
values and every array is an object
values and every array is an object
– 0-based indexing
0-based indexing
 Thus,
Thus,
– myhouse[0] = 8
myhouse[0] = 8
– myhouse[1] = “Ranch”
myhouse[1] = “Ranch”
– myhouse[2] = 1990
myhouse[2] = 1990
– myhouse[3] = true
myhouse[3] = true
JavaScript 31
Functions
Functions
 Every object is also an associative
Every object is also an associative
array
array
 Thus,
Thus,
– myhouse[“rooms”] = 8
myhouse[“rooms”] = 8
– myhouse[“style”] = “Ranch”
myhouse[“style”] = “Ranch”
– myhouse[“yearBuilt”] = 1990
myhouse[“yearBuilt”] = 1990
– myhouse[“hasGarage”] = true
myhouse[“hasGarage”] = true
JavaScript 32
Functions
Functions
 Can dynamically extend an object
Can dynamically extend an object
instance
instance
yourhouse = new house(12, “Tudor”, 1934,
yourhouse = new house(12, “Tudor”, 1934,
true);
true);
yourhouse.hasPorch = “false”;
yourhouse.hasPorch = “false”;
yourhouse.windows = 46;
yourhouse.windows = 46;
– Doesn’t affect other object instances nor
Doesn’t affect other object instances nor
the object itself
the object itself
JavaScript 33
Functions
Functions
 A variable-length array-of-strings
A variable-length array-of-strings
object
object
function stringarr(howMany, initStr) {
function stringarr(howMany, initStr) {
this.length = howMany;
this.length = howMany;
for (var j = 1; j <= howMany; j++) {
for (var j = 1; j <= howMany; j++) {
this[j] = initStr;
this[j] = initStr;
}
}
}
}
JavaScript 34
for..in Statement
for..in Statement
for (varName in objName) {
for (varName in objName) {
forBody
forBody
}
}
 varName
varName takes on the successive
takes on the successive
property names of the object
property names of the object
objName
objName
JavaScript 35
for..in
for..in Statement
Statement
function showAny(anyObj) {
function showAny(anyObj) {
for (var iter in anyObj) {
for (var iter in anyObj) {
document.write(“<br>Property ” +
document.write(“<br>Property ” +
iter + “ is ” + anyObj[iter]);
iter + “ is ” + anyObj[iter]);
}
}
document.write(“<br>”);
document.write(“<br>”);
}
}
JavaScript 36
Methods
Methods
function house(rms, stl, yr, garp) {
function house(rms, stl, yr, garp) {
this.length = 5;
this.length = 5;
this.rooms = rms;
this.rooms = rms;
this.style = stl;
this.style = stl;
this.yearBuilt = yr;
this.yearBuilt = yr;
this.hasGarage = gar;
this.hasGarage = gar;
this.show = mshowHouse;
this.show = mshowHouse;
}
}
JavaScript 37
Methods
Methods
function mshowHouse( ) {
function mshowHouse( ) {
var nprops = this.length;
var nprops = this.length;
for (var iter = 1; iter < nprops;
for (var iter = 1; iter < nprops; iter++) {
iter++) {
document.write(“<br>Property ” +
document.write(“<br>Property ” + iter
iter
+ “ is ” + this[iter]);
+ “ is ” + this[iter]);
}
}
document.write(“<br>”);
document.write(“<br>”);
}
}
myhouse.show( );
myhouse.show( );
JavaScript 38
Techniques for Including
Techniques for Including
JavaScript Code in HTML
JavaScript Code in HTML
 Embed script between
Embed script between <script>
<script> and
and
</script>
</script>
 Event-handler functions
Event-handler functions
 Through the
Through the javascript: URL
javascript: URL pseudo-
pseudo-
protocol
protocol
 The JavaScript HTML entity
The JavaScript HTML entity
– &lt
&lt
JavaScript 39
The
The <script>…</script>
<script>…</script> Tags
Tags
 <script>
<script>-tag may appear in head or body
-tag may appear in head or body
 The language attribute is optional
The language attribute is optional
<script language =
<script language = “JavaScript”>
“JavaScript”>
// JavaScript code
// JavaScript code
</script>
</script>
– Works for both Navigator 2.0 and Navigator
Works for both Navigator 2.0 and Navigator
3.0
3.0
– language = “JavaScript1.1”
language = “JavaScript1.1” works only for
works only for
Navigator 3.0
Navigator 3.0
JavaScript 40
The
The <script>…</script>
<script>…</script> Tags
Tags
 JavaScript is not the only language to
JavaScript is not the only language to
use the
use the <script>
<script>-tag
-tag
<script language = “VBScript”>
<script language = “VBScript”>
' VBScript code
' VBScript code
</script>
</script>
 JavaScript is the default scripting
JavaScript is the default scripting
language
language
– Can leave out the language attribute
Can leave out the language attribute
JavaScript 41
The
The <script>…</script>
<script>…</script> Tags
Tags
 An HTML document may contain more
An HTML document may contain more
than one pair of non-overlapping
than one pair of non-overlapping
<script>
<script> and
and </script>
</script>-tags
-tags
– Statements executed in order of appearance
Statements executed in order of appearance
– They constitute part of the same JavaScript
They constitute part of the same JavaScript
program, however
program, however
<script> var x = 1; </script>
<script> var x = 1; </script>
…
…
<script> document.write(x); </script>
<script> document.write(x); </script>
JavaScript 42
The
The <script>…</script>
<script>…</script> Tags
Tags
 Selectively displaying text in
Selectively displaying text in
JavaScript-ignorant browsers
JavaScript-ignorant browsers
<script language = “none”>
<script language = “none”>
Your browser doesn’t understand JavaScript.
Your browser doesn’t understand JavaScript.
This page won’t work for you.
This page won’t work for you.
</script>
</script>
JavaScript 43
The
The <script>…</script>
<script>…</script> Tags
Tags
 Selectively displaying text in JavaScript-
Selectively displaying text in JavaScript-
ignorant browsers
ignorant browsers
– Browsers that recognize the
Browsers that recognize the <script>
<script>-tag
-tag
will know there is no such language as
will know there is no such language as
none and will ignore everything between
none and will ignore everything between
the
the <script>
<script> and
and <script>
<script>-
-tags
tags
– Browsers that don’t understand the
Browsers that don’t understand the
<script>
<script> and
and </script>
</script>-
-tags will ignore them
tags will ignore them
and display the two lines in-between them
and display the two lines in-between them
JavaScript 44
The
The <script>…</script>
<script>…</script> Tags
Tags
 Including JavaScript files
Including JavaScript files
<script src = “../../javascript /prog.js”> </script>
<script src = “../../javascript /prog.js”> </script>
– Simplifies your HTML files
Simplifies your HTML files
– Can share JavaScript among different
Can share JavaScript among different
HTML files
HTML files
JavaScript 45
The
The <script>…</script>
<script>…</script> Tags
Tags
 Including JavaScript files
Including JavaScript files
– When they are used by more than one
When they are used by more than one
HTML file, this allows them to be cached
HTML file, this allows them to be cached
by the browser, allowing them to load
by the browser, allowing them to load
more quickly
more quickly

The time savings of caching outweighs the
The time savings of caching outweighs the
delay incurred by the browser opening a
delay incurred by the browser opening a
network connection to download the
network connection to download the
JavaScript file
JavaScript file
JavaScript 46
The
The <script>…</script>
<script>…</script> Tags
Tags
 Including JavaScript files
Including JavaScript files
– A JavaScript program from one machine
A JavaScript program from one machine
can use code located on other machines
can use code located on other machines
– This only works for Netscape 3.0 and
This only works for Netscape 3.0 and
higher
higher

Can include JavaScript code in-between the
Can include JavaScript code in-between the
<script>
<script> and
and </script>
</script>-tags for Netscape 2.0
-tags for Netscape 2.0
browsers, as this is ignored by Netscape 3.0
browsers, as this is ignored by Netscape 3.0
browsers if the SRC attribute is defined
browsers if the SRC attribute is defined
JavaScript 47
Event Handler Functions
Event Handler Functions
 Area
Area
– onClick( ), onMouseOver( ),
onClick( ), onMouseOver( ),
onMouseOut( )
onMouseOut( )
 Button
Button
– onClick( )
onClick( )
 Checkbox
Checkbox
– onClick( )
onClick( )
JavaScript 48
Event Handler Functions
Event Handler Functions
 FileUpload
FileUpload
– onBlur( ), onChange( ), onFocus( )
onBlur( ), onChange( ), onFocus( )
 Form
Form
– onSubmit( )
onSubmit( )
 Frame
Frame
– onLoad( ), onUnload( )
onLoad( ), onUnload( )
 Image
Image
– onAbort( ), onError( ), onLoad( )
onAbort( ), onError( ), onLoad( )
JavaScript 49
Event Handler Functions
Event Handler Functions
 Link
Link
– onClick( ), onMouseOver( ), onMouseOut( )
onClick( ), onMouseOver( ), onMouseOut( )
 Radio
Radio
– onClick( )
onClick( )
 Reset
Reset
– onClick( )
onClick( )
 Select
Select
– onChange( )
onChange( )
JavaScript 50
Event Handler Functions
Event Handler Functions
 Submit
Submit
– onClick( )
onClick( )
 Text
Text
– onBlur( ), onChange( ), onFocus( )
onBlur( ), onChange( ), onFocus( )
 Textarea
Textarea
– onBlur( ), onChange( ), onFocus( )
onBlur( ), onChange( ), onFocus( )
 Window
Window
– onBlur( ), onError( ), onFocus( ), onLoad( ),
onBlur( ), onError( ), onFocus( ), onLoad( ),
onUnload( )
onUnload( )
JavaScript 51
JavaScript in URL's
JavaScript in URL's
 javascript:function;greeting+name+
javascript:function;greeting+name+
message;
message;
– Multiple statements separated by semi-
Multiple statements separated by semi-
colons
colons
– Value of last expression evaluated
Value of last expression evaluated
becomes the document that URL refers
becomes the document that URL refers
to and this value will be formatted and
to and this value will be formatted and
displayed
displayed
JavaScript 52
JavaScript in URL's
JavaScript in URL's
 javascript:alert(“Hello World!”);
javascript:alert(“Hello World!”);
– Has side-effect but returns no value
Has side-effect but returns no value
– Browser executes the code but doesn’t
Browser executes the code but doesn’t
modify currently displayed document
modify currently displayed document
JavaScript 53
JavaScript in URL's
JavaScript in URL's
 Can use void operator to remove
Can use void operator to remove
returned value and just have side-
returned value and just have side-
effect of assignment
effect of assignment
javascript:void function( );
javascript:void function( );
 Microsoft has syntax,
Microsoft has syntax,
<a href = “script-engine:script-code”>
<a href = “script-engine:script-code”>
– Supports
Supports vbscript:
vbscript:
JavaScript 54
JavaScript Entities
JavaScript Entities
 &{JavaScript-statements};
&{JavaScript-statements};
– Can only appear within the value of
Can only appear within the value of
HTML attributes
HTML attributes
<body bgcolor = “&{favorite_color( );};”>
<body bgcolor = “&{favorite_color( );};”>
JavaScript 55
Order of Execution
Order of Execution
 Scripts
Scripts
– JavaScript statements that appear
JavaScript statements that appear
between
between <script>
<script> and
and </script>
</script>-tags are
-tags are
executed in the order they appear
executed in the order they appear
– When more than one script appears in a
When more than one script appears in a
page, they are executed in the order
page, they are executed in the order
they appear
they appear
JavaScript 56
Order of Execution
Order of Execution
 Scripts
Scripts
– JavaScript code evaluation occurs as part
JavaScript code evaluation occurs as part
of the browser’s HTML parsing process
of the browser’s HTML parsing process
 Thus, if script appears in the
Thus, if script appears in the <head>
<head> portion
portion
of an HTML document, none of the
of an HTML document, none of the <body>
<body>
of the document will have been defined yet
of the document will have been defined yet
 Thus, many JavaScript objects, such as
Thus, many JavaScript objects, such as form
form
objects, haven’t as yet been created and
objects, haven’t as yet been created and
cannot be manipulated by this code
cannot be manipulated by this code
JavaScript 57
Order of Execution
Order of Execution
 Functions
Functions
– Functions shouldn’t be executed before
Functions shouldn’t be executed before
the objects they manipulate exist
the objects they manipulate exist
– Functions should be defined before they
Functions should be defined before they
are invoked
are invoked
– Can define function to manipulate
Can define function to manipulate
objects before these objects exist
objects before these objects exist
JavaScript 58
Order of Execution
Order of Execution
 Event handlers
Event handlers
– May be invoked before a page is fully loaded
May be invoked before a page is fully loaded
and parsed
and parsed

In a slow network connection, some links can
In a slow network connection, some links can
initially appear and be clicked before page fully
initially appear and be clicked before page fully
loads
loads
– Thus, if your event handler invokes functions,
Thus, if your event handler invokes functions,
you must make sure they are defined
you must make sure they are defined

Put all function definitions in the
Put all function definitions in the <head>
<head>
JavaScript 59
Order of Execution
Order of Execution
 Event handlers
Event handlers
– Also, you must take care that event handlers
Also, you must take care that event handlers
don’t try to manipulate HTML objects that
don’t try to manipulate HTML objects that
haven’t been parsed and created
haven’t been parsed and created

Can test for existence of object to be manipulated
Can test for existence of object to be manipulated
if ((parent.frames[1]) && (parent.frames[1].document) &&
if ((parent.frames[1]) && (parent.frames[1].document) &&
(parent.frames[1].document.myform)) {
(parent.frames[1].document.myform)) {
…
…
}
}
JavaScript 60
Order of Execution
Order of Execution
 Event handlers
Event handlers
– Also, you must take care that event
Also, you must take care that event
handlers don’t try to manipulate HTML
handlers don’t try to manipulate HTML
objects that haven’t been parsed and
objects that haven’t been parsed and
created
created

Place this small script at very end of
Place this small script at very end of
document which sets a flag and have event
document which sets a flag and have event
handlers test this flag
handlers test this flag
<script>done_loading=1</script></body></html>
<script>done_loading=1</script></body></html>
JavaScript 61
Order of Execution
Order of Execution
 Event handlers
Event handlers
– onLoad( )
onLoad( ) and
and onUnload( )
onUnload( ) event handlers
event handlers

In Netscape 3.0, the
In Netscape 3.0, the onLoad( )
onLoad( ) handler is
handler is
executed when document or frameset is
executed when document or frameset is
fully loaded
fully loaded
– When using multiple frames, one doesn’t know in
When using multiple frames, one doesn’t know in
what order the
what order the onLoad( )
onLoad( ) handler will be invoked
handler will be invoked
for the various frames
for the various frames

Handler for child frames can be invoked
Handler for child frames can be invoked
before handler for parent frame
before handler for parent frame
JavaScript 62
Order of Execution
Order of Execution
 Event handlers
Event handlers
– onLoad( )
onLoad( ) and
and onUnload( )
onUnload( ) event handlers
event handlers

The
The onUnload( )
onUnload( ) handler is executed when
handler is executed when
user requests the browser to move to some
user requests the browser to move to some
other page and just before the browser
other page and just before the browser
leaves current document
leaves current document
JavaScript 63
Order of Execution
Order of Execution
 JavaScript URLs
JavaScript URLs
– This is not executed when the document
This is not executed when the document
containing the URL code is loaded
containing the URL code is loaded
– Only interpreted when the browser tries
Only interpreted when the browser tries
to load the document to which URL
to load the document to which URL
refers
refers
JavaScript 64
Order of Execution
Order of Execution
 JavaScript entities
JavaScript entities
– Executed during process of HTML
Executed during process of HTML
parsing
parsing
JavaScript 65
JavaScript Object Hierarchy
JavaScript Object Hierarchy
 The current window
The current window
– self
self,
, window
window,
, parent
parent,
, top
top (various Window
(various Window
objects)
objects)
 navigator (
navigator (navigator
navigator object)
object)
– plugins[ ]
plugins[ ] (array of
(array of plugin
plugin objects)
objects)

mimeTypes[ ]
mimeTypes[ ] (array of
(array of mimeType
mimeType objects)
objects)
var shocked = (navigator.plugins[“Shockwave”] !=
var shocked = (navigator.plugins[“Shockwave”] != null);
null);
– mimeTypes[ ]
mimeTypes[ ] (array of
(array of mimeType
mimeType objects)
objects)
var show_movie=(navigator.mimeTypes[“video/mpeg”]
var show_movie=(navigator.mimeTypes[“video/mpeg”] !=
!=
null);
null);
JavaScript 66
JavaScript Object Hierarchy
JavaScript Object Hierarchy
 frames[ ]
frames[ ] (array of
(array of window
window objects)
objects)
 location
location (
(location
location object)
object)
– location.href = “needsjava.html”;
location.href = “needsjava.html”;
 history
history (
(history
history object)
object)
– <input type=button value = “back”
<input type=button value = “back”
onClick = “history.back( );”>
onClick = “history.back( );”>
JavaScript 67
JavaScript Object Hierarchy
JavaScript Object Hierarchy
 document
document (
(document
document object)
object)
– forms[ ]
forms[ ] (array of
(array of form
form objects)
objects)

elements[ ]
elements[ ] (array of HTML form element objects)
(array of HTML form element objects)
– button
button
– checkbox
checkbox
– fileupload
fileupload (3.0)
(3.0)
– hidden
hidden
– password
password
– radio
radio
– reset
reset
JavaScript 68
JavaScript Object Hierarchy
JavaScript Object Hierarchy
 document
document (
(document
document object)
object)
– forms[ ]
forms[ ] (array of
(array of form
form objects)
objects)

elements[ ]
elements[ ] (array of HTML form element
(array of HTML form element
objects)
objects)
– select
select

options[ ]
options[ ] (array of
(array of option
option objects)
objects)
– submit
submit
– text
text
– textarea
textarea
JavaScript 69
JavaScript Object Hierarchy
JavaScript Object Hierarchy
 document
document (
(document
document object)
object)
– anchors[ ]
anchors[ ] (array of
(array of anchor
anchor objects)
objects)
– links[ ]
links[ ] (array[ ] of
(array[ ] of link
link objects)
objects)
– images[ ]
images[ ] (array of
(array of image
image objects) (3.0)
objects) (3.0)
– applets[ ]
applets[ ] (array of
(array of JavaObject
JavaObject objects)
objects)
(3.0)
(3.0)
– embeds[ ]
embeds[ ] (array of
(array of JavaObject
JavaObject objects)
objects)
(3.0)
(3.0)
JavaScript 70
JavaScript Object Hierarchy
JavaScript Object Hierarchy
 packages
packages (
(JavaPackage
JavaPackage object)
object)
– Various
Various JavaPackage
JavaPackage and
and JavaClass
JavaClass
objects (3.0)
objects (3.0)
JavaScript 71
JavaScript Objects
JavaScript Objects
 Built-in objects
Built-in objects
 HTML objects
HTML objects
 Browser objects
Browser objects
JavaScript 72
Built-in Objects
Built-in Objects
 string
string objects
objects
 date
date object
object
 math
math object
object
JavaScript 73
string
string Objects
Objects
 string
string object methods for HTML
object methods for HTML
formatting
formatting
– anchor
anchor

“
“Bill”.anchor(“anchortext”)
Bill”.anchor(“anchortext”)
– <a name = “anchortext”>Bill</a>
<a name = “anchortext”>Bill</a>
– big
big

“
“Bill”.big( )
Bill”.big( )
– <big>Bill<big>
<big>Bill<big>
JavaScript 74
string
string Objects
Objects
 string
string object methods for HTML
object methods for HTML
formatting
formatting
– blink
blink

“
“Bill”.blink( )
Bill”.blink( )
– <blink>Bill</blink>
<blink>Bill</blink>
– bold
bold

“
“Bill”.bold( )
Bill”.bold( )
– <b>Bill</b>
<b>Bill</b>
JavaScript 75
string
string Objects
Objects
 string
string object methods for HTML
object methods for HTML
formatting
formatting
– fixed
fixed

“
“Bill”.fixed( )
Bill”.fixed( )
– <tt>Bill</tt>
<tt>Bill</tt>
– fontcolor
fontcolor

“
“Bill”.fontcolor(“blue”)
Bill”.fontcolor(“blue”)
– <font color = “blue”><Bill></font>
<font color = “blue”><Bill></font>
JavaScript 76
string
string Objects
Objects
 string
string object methods for HTML
object methods for HTML
formatting
formatting
– fontsize
fontsize

“
“Bill”.fontsize(-1)
Bill”.fontsize(-1)
– <font size = -1>Bill</font>
<font size = -1>Bill</font>
– italics
italics

“
“Bill”.italics( )
Bill”.italics( )
– <i>Bill</i>
<i>Bill</i>
JavaScript 77
string
string Objects
Objects
 string
string object methods for HTML
object methods for HTML
formatting
formatting
– link
link

“
“Bill”.link(“linktext”)
Bill”.link(“linktext”)
– <a href = “linktext”>Bill</a>
<a href = “linktext”>Bill</a>
– small
small
 “
“Bill”.small( )
Bill”.small( )
– <small>Bill</small>
<small>Bill</small>
JavaScript 78
string
string Objects
Objects
 string
string object methods for HTML
object methods for HTML
formatting
formatting
– strike
strike
 “
“Bill”.strike( )
Bill”.strike( )
– <strike>Bill</strike>
<strike>Bill</strike>
– sub
sub
 “
“Bill”.sub( )
Bill”.sub( )
– <sub>Bill</sub>
<sub>Bill</sub>
JavaScript 79
string
string Objects
Objects
 string
string object methods for HTML
object methods for HTML
formatting
formatting
– sup
sup
 “
“Bill”.sup( )
Bill”.sup( )
– <sup>Bill</sup>
<sup>Bill</sup>
– toLowerCase
toLowerCase
 “
“Bill”.toLowerCase( )
Bill”.toLowerCase( )
– bill
bill
JavaScript 80
string
string Objects
Objects
 string
string object methods for HTML
object methods for HTML
formatting
formatting
– toUpperCase
toUpperCase

“
“Bill”.toUpperCase( )
Bill”.toUpperCase( )
– BILL
BILL
JavaScript 81
string
string Objects
Objects
 string
string object methods for displaying
object methods for displaying
subsets of strings
subsets of strings
– charAt
charAt

“
“Bill”.charAt(1)
Bill”.charAt(1) is “i”
is “i”
– indexOf
indexOf

“
“Bill”.indexOf(“il”)
Bill”.indexOf(“il”) is 1
is 1
JavaScript 82
string
string Objects
Objects
 string
string object methods for displaying
object methods for displaying
subsets of strings
subsets of strings
– lastIndexOf
lastIndexOf

“
“Bill”.lastIndexOf(“l”)
Bill”.lastIndexOf(“l”) is 3
is 3
– substring
substring

“
“Bill”.substring(1,2)
Bill”.substring(1,2) is “il”
is “il”
– length
length

“
“Bill”.length
Bill”.length is 4
is 4
JavaScript 83
date
date Object
Object
 See js11.htm
See js11.htm

JavaScript ppt for beginners to learn basics

  • 1.
  • 2.
    JavaScript 2 History History  Firstweb scripting language First web scripting language  Developed by Netscape and Sun Developed by Netscape and Sun  Initiated by Netscape and called Initiated by Netscape and called LiveScript LiveScript  In parallel with this, Sun was In parallel with this, Sun was developing Java developing Java
  • 3.
    JavaScript 3 History History  Netscapeand Sun got together and Netscape and Sun got together and realized that many of the realized that many of the specifications for Java could apply to specifications for Java could apply to LiveScript LiveScript  Result is JavaScript Result is JavaScript
  • 4.
    JavaScript 4 JavaScript VersusJava JavaScript Versus Java  JavaScript is interpreted while Java is JavaScript is interpreted while Java is compiled compiled – But server-side JavaScript is compiled But server-side JavaScript is compiled  JavaScript is object-based while Java is JavaScript is object-based while Java is object-oriented object-oriented – Object-based languages can utilize pre- Object-based languages can utilize pre- defined objects, but you are limited in defined objects, but you are limited in terms of creating your own objects terms of creating your own objects
  • 5.
    JavaScript 5 JavaScript VersusJava JavaScript Versus Java  JavaScript has loose data typing, JavaScript has loose data typing, while Java has strong data typing while Java has strong data typing – Loose data typing means that a variable Loose data typing means that a variable can hold any kind of data can hold any kind of data  JavaScript code is embedded in an JavaScript code is embedded in an HTML document while Java applets HTML document while Java applets are stand-alone applications that can are stand-alone applications that can be accessed from HTML be accessed from HTML
  • 6.
    JavaScript 6 JavaScript VersusJava JavaScript Versus Java  JavaScript has dynamic binding, while JavaScript has dynamic binding, while Java has static binding Java has static binding – Names bound at runtime Names bound at runtime  JavaScript can access browser objects JavaScript can access browser objects and functionality, while Java cannot and functionality, while Java cannot
  • 7.
    JavaScript 7 Client-Side JavaScript Client-SideJavaScript  Client-side JavaScript scripts operate Client-side JavaScript scripts operate on a client running Netscape on a client running Netscape Navigator (Microsoft Internet Navigator (Microsoft Internet Explorer also supports it now) and Explorer also supports it now) and are interpreted by Netscape are interpreted by Netscape Navigator Navigator
  • 8.
    JavaScript 8 Client-Side JavaScript Client-SideJavaScript  Detect whether the browser supports a Detect whether the browser supports a certain plug-in certain plug-in  Control a plug-in Control a plug-in  Validate user form input Validate user form input  Prompt a user for confirmation Prompt a user for confirmation  Perform post-processing of information Perform post-processing of information retrieved from server-side JavaScript retrieved from server-side JavaScript scripts scripts
  • 9.
    JavaScript 9 Server-Side JavaScript Server-SideJavaScript  JavaScript scripts that run on the JavaScript scripts that run on the server are called LiveWire server are called LiveWire applications because they use the applications because they use the Netscape LiveWire development Netscape LiveWire development environment environment – This is the only system that supports This is the only system that supports server-side JavaScript development server-side JavaScript development
  • 10.
    JavaScript 10 Server-Side JavaScript Server-SideJavaScript  Unlike CGI scripts, LiveWire Unlike CGI scripts, LiveWire applications are more closely applications are more closely integrated to the HTML pages that integrated to the HTML pages that control them control them – Can have a page that accepts credit card Can have a page that accepts credit card payments and gives user immediate payments and gives user immediate feedback feedback on the same page on the same page about about whether card was accepted whether card was accepted
  • 11.
    JavaScript 11 Client Scripts ClientScripts  To display error or information boxes To display error or information boxes  To validate user input To validate user input  To display confirmation boxes To display confirmation boxes  To process server data, such as To process server data, such as aggregate calculations aggregate calculations  To add programmable logic to HTML To add programmable logic to HTML
  • 12.
    JavaScript 12 Client Scripts ClientScripts  To perform functions that don’t To perform functions that don’t require information from the server require information from the server  To produce a new HTML page To produce a new HTML page without making a request to the without making a request to the server server
  • 13.
    JavaScript 13 Server Scripts ServerScripts  To maintain data shared among To maintain data shared among applications or clients applications or clients  To maintain information during client To maintain information during client accesses accesses  To access a database To access a database  To access server files To access server files  To call server C libraries To call server C libraries  To customize Java applets To customize Java applets
  • 14.
    JavaScript 14 Scripts Scripts  Client-sideand server-side JavaScript Client-side and server-side JavaScript scripts are both embedded in an scripts are both embedded in an HTML file HTML file  For server-side JavaScript scripts, this For server-side JavaScript scripts, this HTML file is compiled with the HTML file is compiled with the LiveWire compiler LiveWire compiler – Creates a file that is in a platform- Creates a file that is in a platform- independent and compiled bytecode independent and compiled bytecode format format
  • 15.
    JavaScript 15 Scripts Scripts  Client-sideJavaScript needs Netscape Client-side JavaScript needs Netscape Navigator and a standard HTML Navigator and a standard HTML server server  Server-side JavaScript needs the Server-side JavaScript needs the LiveWire compiler, the LiveWire LiveWire compiler, the LiveWire Application Manager, and a Netscape Application Manager, and a Netscape HTML server that supports the HTML server that supports the LiveWire server extension LiveWire server extension
  • 16.
    JavaScript 16 Scripts Scripts  Examplesjs1.htm, js2.htm, js3.htm Examples js1.htm, js2.htm, js3.htm  The The <head> <head> portion of an HTML page portion of an HTML page is the first to load, so it is best to is the first to load, so it is best to define the functions for a page in this define the functions for a page in this portion portion – Functions can be called in the Functions can be called in the <body> <body> portion portion
  • 17.
    JavaScript 17 JavaScript ProgramCode JavaScript Program Code  Main body Main body  Event handlers Event handlers  Functions Functions
  • 18.
    JavaScript 18 Main Body MainBody  Main Body Main Body – Any code that is between Any code that is between <script> <script> and and </script> </script> that is not a function definition that is not a function definition
  • 19.
    JavaScript 19 Events Events  Events Events –Mouse click Mouse click – Re-sizing window Re-sizing window
  • 20.
    JavaScript 20 Event Handlers EventHandlers  Event handlers Event handlers – Scripts that link events to JavaScript Scripts that link events to JavaScript functions functions – Embed in HTML documents as attributes Embed in HTML documents as attributes of HTML tags of HTML tags  <tag eventHandler = “JavaScript Code”> <tag eventHandler = “JavaScript Code”>  Example js4.htm Example js4.htm
  • 21.
    JavaScript 21 More Events MoreEvents  Top-level actions causing change in Top-level actions causing change in web page being displayed web page being displayed – Navigation Navigation – Interaction with an element of an HTML Interaction with an element of an HTML form form
  • 22.
    JavaScript 22 Navigation Navigation  Selectinga hypertext link Selecting a hypertext link  Moving forward or backward in the Moving forward or backward in the history list history list  Opening a new URL Opening a new URL  Quitting the browser Quitting the browser
  • 23.
    JavaScript 23 Navigation Navigation  Inthese events, some page is being In these events, some page is being loaded or unloaded loaded or unloaded – These are document-level events that These are document-level events that can be handled by JavaScript can be handled by JavaScript
  • 24.
    JavaScript 24 JavaScript Events JavaScriptEvents  button button – click click  checkbox checkbox – click click  document document – load load – unload unload
  • 25.
    JavaScript 25 JavaScript Events JavaScriptEvents  form form – submit submit  link link – click click – mouseover mouseover  radio radio – click click
  • 26.
    JavaScript 26 JavaScript Events JavaScriptEvents  selection selection – blur blur – change change – focus focus  submit submit – click click
  • 27.
    JavaScript 27 JavaScript Events JavaScriptEvents  text text – change change – focus focus  A text field is said to have A text field is said to have focus focus when it is when it is currently accepting typed input currently accepting typed input  Clicking anywhere inside a text item gives it focus Clicking anywhere inside a text item gives it focus  Moving the mouse over the text field may give it Moving the mouse over the text field may give it focus focus – blur blur  The opposite of focus The opposite of focus – select select
  • 28.
    JavaScript 28 JavaScript Events JavaScriptEvents  textarea textarea – blur blur – change change – focus focus – select select
  • 29.
    JavaScript 29 Functions Functions  Defininga function to create an object Defining a function to create an object function house(rms, stl, yr, gar){ function house(rms, stl, yr, gar){ this.rooms = rms; this.rooms = rms; this.style = stl; this.style = stl; this.yearBuilt = yr; this.yearBuilt = yr; this.hasGarage = gar; this.hasGarage = gar; } } var myhouse = new house(8, “Ranch”, 1990, var myhouse = new house(8, “Ranch”, 1990, true) true)
  • 30.
    JavaScript 30 Functions Functions  Everyobject is an array of its property Every object is an array of its property values and every array is an object values and every array is an object – 0-based indexing 0-based indexing  Thus, Thus, – myhouse[0] = 8 myhouse[0] = 8 – myhouse[1] = “Ranch” myhouse[1] = “Ranch” – myhouse[2] = 1990 myhouse[2] = 1990 – myhouse[3] = true myhouse[3] = true
  • 31.
    JavaScript 31 Functions Functions  Everyobject is also an associative Every object is also an associative array array  Thus, Thus, – myhouse[“rooms”] = 8 myhouse[“rooms”] = 8 – myhouse[“style”] = “Ranch” myhouse[“style”] = “Ranch” – myhouse[“yearBuilt”] = 1990 myhouse[“yearBuilt”] = 1990 – myhouse[“hasGarage”] = true myhouse[“hasGarage”] = true
  • 32.
    JavaScript 32 Functions Functions  Candynamically extend an object Can dynamically extend an object instance instance yourhouse = new house(12, “Tudor”, 1934, yourhouse = new house(12, “Tudor”, 1934, true); true); yourhouse.hasPorch = “false”; yourhouse.hasPorch = “false”; yourhouse.windows = 46; yourhouse.windows = 46; – Doesn’t affect other object instances nor Doesn’t affect other object instances nor the object itself the object itself
  • 33.
    JavaScript 33 Functions Functions  Avariable-length array-of-strings A variable-length array-of-strings object object function stringarr(howMany, initStr) { function stringarr(howMany, initStr) { this.length = howMany; this.length = howMany; for (var j = 1; j <= howMany; j++) { for (var j = 1; j <= howMany; j++) { this[j] = initStr; this[j] = initStr; } } } }
  • 34.
    JavaScript 34 for..in Statement for..inStatement for (varName in objName) { for (varName in objName) { forBody forBody } }  varName varName takes on the successive takes on the successive property names of the object property names of the object objName objName
  • 35.
    JavaScript 35 for..in for..in Statement Statement functionshowAny(anyObj) { function showAny(anyObj) { for (var iter in anyObj) { for (var iter in anyObj) { document.write(“<br>Property ” + document.write(“<br>Property ” + iter + “ is ” + anyObj[iter]); iter + “ is ” + anyObj[iter]); } } document.write(“<br>”); document.write(“<br>”); } }
  • 36.
    JavaScript 36 Methods Methods function house(rms,stl, yr, garp) { function house(rms, stl, yr, garp) { this.length = 5; this.length = 5; this.rooms = rms; this.rooms = rms; this.style = stl; this.style = stl; this.yearBuilt = yr; this.yearBuilt = yr; this.hasGarage = gar; this.hasGarage = gar; this.show = mshowHouse; this.show = mshowHouse; } }
  • 37.
    JavaScript 37 Methods Methods function mshowHouse() { function mshowHouse( ) { var nprops = this.length; var nprops = this.length; for (var iter = 1; iter < nprops; for (var iter = 1; iter < nprops; iter++) { iter++) { document.write(“<br>Property ” + document.write(“<br>Property ” + iter iter + “ is ” + this[iter]); + “ is ” + this[iter]); } } document.write(“<br>”); document.write(“<br>”); } } myhouse.show( ); myhouse.show( );
  • 38.
    JavaScript 38 Techniques forIncluding Techniques for Including JavaScript Code in HTML JavaScript Code in HTML  Embed script between Embed script between <script> <script> and and </script> </script>  Event-handler functions Event-handler functions  Through the Through the javascript: URL javascript: URL pseudo- pseudo- protocol protocol  The JavaScript HTML entity The JavaScript HTML entity – &lt &lt
  • 39.
    JavaScript 39 The The <script>…</script> <script>…</script>Tags Tags  <script> <script>-tag may appear in head or body -tag may appear in head or body  The language attribute is optional The language attribute is optional <script language = <script language = “JavaScript”> “JavaScript”> // JavaScript code // JavaScript code </script> </script> – Works for both Navigator 2.0 and Navigator Works for both Navigator 2.0 and Navigator 3.0 3.0 – language = “JavaScript1.1” language = “JavaScript1.1” works only for works only for Navigator 3.0 Navigator 3.0
  • 40.
    JavaScript 40 The The <script>…</script> <script>…</script>Tags Tags  JavaScript is not the only language to JavaScript is not the only language to use the use the <script> <script>-tag -tag <script language = “VBScript”> <script language = “VBScript”> ' VBScript code ' VBScript code </script> </script>  JavaScript is the default scripting JavaScript is the default scripting language language – Can leave out the language attribute Can leave out the language attribute
  • 41.
    JavaScript 41 The The <script>…</script> <script>…</script>Tags Tags  An HTML document may contain more An HTML document may contain more than one pair of non-overlapping than one pair of non-overlapping <script> <script> and and </script> </script>-tags -tags – Statements executed in order of appearance Statements executed in order of appearance – They constitute part of the same JavaScript They constitute part of the same JavaScript program, however program, however <script> var x = 1; </script> <script> var x = 1; </script> … … <script> document.write(x); </script> <script> document.write(x); </script>
  • 42.
    JavaScript 42 The The <script>…</script> <script>…</script>Tags Tags  Selectively displaying text in Selectively displaying text in JavaScript-ignorant browsers JavaScript-ignorant browsers <script language = “none”> <script language = “none”> Your browser doesn’t understand JavaScript. Your browser doesn’t understand JavaScript. This page won’t work for you. This page won’t work for you. </script> </script>
  • 43.
    JavaScript 43 The The <script>…</script> <script>…</script>Tags Tags  Selectively displaying text in JavaScript- Selectively displaying text in JavaScript- ignorant browsers ignorant browsers – Browsers that recognize the Browsers that recognize the <script> <script>-tag -tag will know there is no such language as will know there is no such language as none and will ignore everything between none and will ignore everything between the the <script> <script> and and <script> <script>- -tags tags – Browsers that don’t understand the Browsers that don’t understand the <script> <script> and and </script> </script>- -tags will ignore them tags will ignore them and display the two lines in-between them and display the two lines in-between them
  • 44.
    JavaScript 44 The The <script>…</script> <script>…</script>Tags Tags  Including JavaScript files Including JavaScript files <script src = “../../javascript /prog.js”> </script> <script src = “../../javascript /prog.js”> </script> – Simplifies your HTML files Simplifies your HTML files – Can share JavaScript among different Can share JavaScript among different HTML files HTML files
  • 45.
    JavaScript 45 The The <script>…</script> <script>…</script>Tags Tags  Including JavaScript files Including JavaScript files – When they are used by more than one When they are used by more than one HTML file, this allows them to be cached HTML file, this allows them to be cached by the browser, allowing them to load by the browser, allowing them to load more quickly more quickly  The time savings of caching outweighs the The time savings of caching outweighs the delay incurred by the browser opening a delay incurred by the browser opening a network connection to download the network connection to download the JavaScript file JavaScript file
  • 46.
    JavaScript 46 The The <script>…</script> <script>…</script>Tags Tags  Including JavaScript files Including JavaScript files – A JavaScript program from one machine A JavaScript program from one machine can use code located on other machines can use code located on other machines – This only works for Netscape 3.0 and This only works for Netscape 3.0 and higher higher  Can include JavaScript code in-between the Can include JavaScript code in-between the <script> <script> and and </script> </script>-tags for Netscape 2.0 -tags for Netscape 2.0 browsers, as this is ignored by Netscape 3.0 browsers, as this is ignored by Netscape 3.0 browsers if the SRC attribute is defined browsers if the SRC attribute is defined
  • 47.
    JavaScript 47 Event HandlerFunctions Event Handler Functions  Area Area – onClick( ), onMouseOver( ), onClick( ), onMouseOver( ), onMouseOut( ) onMouseOut( )  Button Button – onClick( ) onClick( )  Checkbox Checkbox – onClick( ) onClick( )
  • 48.
    JavaScript 48 Event HandlerFunctions Event Handler Functions  FileUpload FileUpload – onBlur( ), onChange( ), onFocus( ) onBlur( ), onChange( ), onFocus( )  Form Form – onSubmit( ) onSubmit( )  Frame Frame – onLoad( ), onUnload( ) onLoad( ), onUnload( )  Image Image – onAbort( ), onError( ), onLoad( ) onAbort( ), onError( ), onLoad( )
  • 49.
    JavaScript 49 Event HandlerFunctions Event Handler Functions  Link Link – onClick( ), onMouseOver( ), onMouseOut( ) onClick( ), onMouseOver( ), onMouseOut( )  Radio Radio – onClick( ) onClick( )  Reset Reset – onClick( ) onClick( )  Select Select – onChange( ) onChange( )
  • 50.
    JavaScript 50 Event HandlerFunctions Event Handler Functions  Submit Submit – onClick( ) onClick( )  Text Text – onBlur( ), onChange( ), onFocus( ) onBlur( ), onChange( ), onFocus( )  Textarea Textarea – onBlur( ), onChange( ), onFocus( ) onBlur( ), onChange( ), onFocus( )  Window Window – onBlur( ), onError( ), onFocus( ), onLoad( ), onBlur( ), onError( ), onFocus( ), onLoad( ), onUnload( ) onUnload( )
  • 51.
    JavaScript 51 JavaScript inURL's JavaScript in URL's  javascript:function;greeting+name+ javascript:function;greeting+name+ message; message; – Multiple statements separated by semi- Multiple statements separated by semi- colons colons – Value of last expression evaluated Value of last expression evaluated becomes the document that URL refers becomes the document that URL refers to and this value will be formatted and to and this value will be formatted and displayed displayed
  • 52.
    JavaScript 52 JavaScript inURL's JavaScript in URL's  javascript:alert(“Hello World!”); javascript:alert(“Hello World!”); – Has side-effect but returns no value Has side-effect but returns no value – Browser executes the code but doesn’t Browser executes the code but doesn’t modify currently displayed document modify currently displayed document
  • 53.
    JavaScript 53 JavaScript inURL's JavaScript in URL's  Can use void operator to remove Can use void operator to remove returned value and just have side- returned value and just have side- effect of assignment effect of assignment javascript:void function( ); javascript:void function( );  Microsoft has syntax, Microsoft has syntax, <a href = “script-engine:script-code”> <a href = “script-engine:script-code”> – Supports Supports vbscript: vbscript:
  • 54.
    JavaScript 54 JavaScript Entities JavaScriptEntities  &{JavaScript-statements}; &{JavaScript-statements}; – Can only appear within the value of Can only appear within the value of HTML attributes HTML attributes <body bgcolor = “&{favorite_color( );};”> <body bgcolor = “&{favorite_color( );};”>
  • 55.
    JavaScript 55 Order ofExecution Order of Execution  Scripts Scripts – JavaScript statements that appear JavaScript statements that appear between between <script> <script> and and </script> </script>-tags are -tags are executed in the order they appear executed in the order they appear – When more than one script appears in a When more than one script appears in a page, they are executed in the order page, they are executed in the order they appear they appear
  • 56.
    JavaScript 56 Order ofExecution Order of Execution  Scripts Scripts – JavaScript code evaluation occurs as part JavaScript code evaluation occurs as part of the browser’s HTML parsing process of the browser’s HTML parsing process  Thus, if script appears in the Thus, if script appears in the <head> <head> portion portion of an HTML document, none of the of an HTML document, none of the <body> <body> of the document will have been defined yet of the document will have been defined yet  Thus, many JavaScript objects, such as Thus, many JavaScript objects, such as form form objects, haven’t as yet been created and objects, haven’t as yet been created and cannot be manipulated by this code cannot be manipulated by this code
  • 57.
    JavaScript 57 Order ofExecution Order of Execution  Functions Functions – Functions shouldn’t be executed before Functions shouldn’t be executed before the objects they manipulate exist the objects they manipulate exist – Functions should be defined before they Functions should be defined before they are invoked are invoked – Can define function to manipulate Can define function to manipulate objects before these objects exist objects before these objects exist
  • 58.
    JavaScript 58 Order ofExecution Order of Execution  Event handlers Event handlers – May be invoked before a page is fully loaded May be invoked before a page is fully loaded and parsed and parsed  In a slow network connection, some links can In a slow network connection, some links can initially appear and be clicked before page fully initially appear and be clicked before page fully loads loads – Thus, if your event handler invokes functions, Thus, if your event handler invokes functions, you must make sure they are defined you must make sure they are defined  Put all function definitions in the Put all function definitions in the <head> <head>
  • 59.
    JavaScript 59 Order ofExecution Order of Execution  Event handlers Event handlers – Also, you must take care that event handlers Also, you must take care that event handlers don’t try to manipulate HTML objects that don’t try to manipulate HTML objects that haven’t been parsed and created haven’t been parsed and created  Can test for existence of object to be manipulated Can test for existence of object to be manipulated if ((parent.frames[1]) && (parent.frames[1].document) && if ((parent.frames[1]) && (parent.frames[1].document) && (parent.frames[1].document.myform)) { (parent.frames[1].document.myform)) { … … } }
  • 60.
    JavaScript 60 Order ofExecution Order of Execution  Event handlers Event handlers – Also, you must take care that event Also, you must take care that event handlers don’t try to manipulate HTML handlers don’t try to manipulate HTML objects that haven’t been parsed and objects that haven’t been parsed and created created  Place this small script at very end of Place this small script at very end of document which sets a flag and have event document which sets a flag and have event handlers test this flag handlers test this flag <script>done_loading=1</script></body></html> <script>done_loading=1</script></body></html>
  • 61.
    JavaScript 61 Order ofExecution Order of Execution  Event handlers Event handlers – onLoad( ) onLoad( ) and and onUnload( ) onUnload( ) event handlers event handlers  In Netscape 3.0, the In Netscape 3.0, the onLoad( ) onLoad( ) handler is handler is executed when document or frameset is executed when document or frameset is fully loaded fully loaded – When using multiple frames, one doesn’t know in When using multiple frames, one doesn’t know in what order the what order the onLoad( ) onLoad( ) handler will be invoked handler will be invoked for the various frames for the various frames  Handler for child frames can be invoked Handler for child frames can be invoked before handler for parent frame before handler for parent frame
  • 62.
    JavaScript 62 Order ofExecution Order of Execution  Event handlers Event handlers – onLoad( ) onLoad( ) and and onUnload( ) onUnload( ) event handlers event handlers  The The onUnload( ) onUnload( ) handler is executed when handler is executed when user requests the browser to move to some user requests the browser to move to some other page and just before the browser other page and just before the browser leaves current document leaves current document
  • 63.
    JavaScript 63 Order ofExecution Order of Execution  JavaScript URLs JavaScript URLs – This is not executed when the document This is not executed when the document containing the URL code is loaded containing the URL code is loaded – Only interpreted when the browser tries Only interpreted when the browser tries to load the document to which URL to load the document to which URL refers refers
  • 64.
    JavaScript 64 Order ofExecution Order of Execution  JavaScript entities JavaScript entities – Executed during process of HTML Executed during process of HTML parsing parsing
  • 65.
    JavaScript 65 JavaScript ObjectHierarchy JavaScript Object Hierarchy  The current window The current window – self self, , window window, , parent parent, , top top (various Window (various Window objects) objects)  navigator ( navigator (navigator navigator object) object) – plugins[ ] plugins[ ] (array of (array of plugin plugin objects) objects)  mimeTypes[ ] mimeTypes[ ] (array of (array of mimeType mimeType objects) objects) var shocked = (navigator.plugins[“Shockwave”] != var shocked = (navigator.plugins[“Shockwave”] != null); null); – mimeTypes[ ] mimeTypes[ ] (array of (array of mimeType mimeType objects) objects) var show_movie=(navigator.mimeTypes[“video/mpeg”] var show_movie=(navigator.mimeTypes[“video/mpeg”] != != null); null);
  • 66.
    JavaScript 66 JavaScript ObjectHierarchy JavaScript Object Hierarchy  frames[ ] frames[ ] (array of (array of window window objects) objects)  location location ( (location location object) object) – location.href = “needsjava.html”; location.href = “needsjava.html”;  history history ( (history history object) object) – <input type=button value = “back” <input type=button value = “back” onClick = “history.back( );”> onClick = “history.back( );”>
  • 67.
    JavaScript 67 JavaScript ObjectHierarchy JavaScript Object Hierarchy  document document ( (document document object) object) – forms[ ] forms[ ] (array of (array of form form objects) objects)  elements[ ] elements[ ] (array of HTML form element objects) (array of HTML form element objects) – button button – checkbox checkbox – fileupload fileupload (3.0) (3.0) – hidden hidden – password password – radio radio – reset reset
  • 68.
    JavaScript 68 JavaScript ObjectHierarchy JavaScript Object Hierarchy  document document ( (document document object) object) – forms[ ] forms[ ] (array of (array of form form objects) objects)  elements[ ] elements[ ] (array of HTML form element (array of HTML form element objects) objects) – select select  options[ ] options[ ] (array of (array of option option objects) objects) – submit submit – text text – textarea textarea
  • 69.
    JavaScript 69 JavaScript ObjectHierarchy JavaScript Object Hierarchy  document document ( (document document object) object) – anchors[ ] anchors[ ] (array of (array of anchor anchor objects) objects) – links[ ] links[ ] (array[ ] of (array[ ] of link link objects) objects) – images[ ] images[ ] (array of (array of image image objects) (3.0) objects) (3.0) – applets[ ] applets[ ] (array of (array of JavaObject JavaObject objects) objects) (3.0) (3.0) – embeds[ ] embeds[ ] (array of (array of JavaObject JavaObject objects) objects) (3.0) (3.0)
  • 70.
    JavaScript 70 JavaScript ObjectHierarchy JavaScript Object Hierarchy  packages packages ( (JavaPackage JavaPackage object) object) – Various Various JavaPackage JavaPackage and and JavaClass JavaClass objects (3.0) objects (3.0)
  • 71.
    JavaScript 71 JavaScript Objects JavaScriptObjects  Built-in objects Built-in objects  HTML objects HTML objects  Browser objects Browser objects
  • 72.
    JavaScript 72 Built-in Objects Built-inObjects  string string objects objects  date date object object  math math object object
  • 73.
    JavaScript 73 string string Objects Objects string string object methods for HTML object methods for HTML formatting formatting – anchor anchor  “ “Bill”.anchor(“anchortext”) Bill”.anchor(“anchortext”) – <a name = “anchortext”>Bill</a> <a name = “anchortext”>Bill</a> – big big  “ “Bill”.big( ) Bill”.big( ) – <big>Bill<big> <big>Bill<big>
  • 74.
    JavaScript 74 string string Objects Objects string string object methods for HTML object methods for HTML formatting formatting – blink blink  “ “Bill”.blink( ) Bill”.blink( ) – <blink>Bill</blink> <blink>Bill</blink> – bold bold  “ “Bill”.bold( ) Bill”.bold( ) – <b>Bill</b> <b>Bill</b>
  • 75.
    JavaScript 75 string string Objects Objects string string object methods for HTML object methods for HTML formatting formatting – fixed fixed  “ “Bill”.fixed( ) Bill”.fixed( ) – <tt>Bill</tt> <tt>Bill</tt> – fontcolor fontcolor  “ “Bill”.fontcolor(“blue”) Bill”.fontcolor(“blue”) – <font color = “blue”><Bill></font> <font color = “blue”><Bill></font>
  • 76.
    JavaScript 76 string string Objects Objects string string object methods for HTML object methods for HTML formatting formatting – fontsize fontsize  “ “Bill”.fontsize(-1) Bill”.fontsize(-1) – <font size = -1>Bill</font> <font size = -1>Bill</font> – italics italics  “ “Bill”.italics( ) Bill”.italics( ) – <i>Bill</i> <i>Bill</i>
  • 77.
    JavaScript 77 string string Objects Objects string string object methods for HTML object methods for HTML formatting formatting – link link  “ “Bill”.link(“linktext”) Bill”.link(“linktext”) – <a href = “linktext”>Bill</a> <a href = “linktext”>Bill</a> – small small  “ “Bill”.small( ) Bill”.small( ) – <small>Bill</small> <small>Bill</small>
  • 78.
    JavaScript 78 string string Objects Objects string string object methods for HTML object methods for HTML formatting formatting – strike strike  “ “Bill”.strike( ) Bill”.strike( ) – <strike>Bill</strike> <strike>Bill</strike> – sub sub  “ “Bill”.sub( ) Bill”.sub( ) – <sub>Bill</sub> <sub>Bill</sub>
  • 79.
    JavaScript 79 string string Objects Objects string string object methods for HTML object methods for HTML formatting formatting – sup sup  “ “Bill”.sup( ) Bill”.sup( ) – <sup>Bill</sup> <sup>Bill</sup> – toLowerCase toLowerCase  “ “Bill”.toLowerCase( ) Bill”.toLowerCase( ) – bill bill
  • 80.
    JavaScript 80 string string Objects Objects string string object methods for HTML object methods for HTML formatting formatting – toUpperCase toUpperCase  “ “Bill”.toUpperCase( ) Bill”.toUpperCase( ) – BILL BILL
  • 81.
    JavaScript 81 string string Objects Objects string string object methods for displaying object methods for displaying subsets of strings subsets of strings – charAt charAt  “ “Bill”.charAt(1) Bill”.charAt(1) is “i” is “i” – indexOf indexOf  “ “Bill”.indexOf(“il”) Bill”.indexOf(“il”) is 1 is 1
  • 82.
    JavaScript 82 string string Objects Objects string string object methods for displaying object methods for displaying subsets of strings subsets of strings – lastIndexOf lastIndexOf  “ “Bill”.lastIndexOf(“l”) Bill”.lastIndexOf(“l”) is 3 is 3 – substring substring  “ “Bill”.substring(1,2) Bill”.substring(1,2) is “il” is “il” – length length  “ “Bill”.length Bill”.length is 4 is 4
  • 83.