JavaScript - Prof. Dr. Helmut Dispert

Transcription

JavaScript - Prof. Dr. Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript
JavaScript
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript
JavaScript:
Scripting language developed by Netscape and
Sun Microsystems, released with Navigator 2.0
JavaScript code is similiar to C-code
Script code is embedded into HTML code and runs
within a browser (no stand-alone functionality)
Script is interpreted and executed when loaded or
when triggered by an event
JavaScript has access to browser resources (e.g.
history, back, windows, frames)
Object-based (as compared to object-oriented)
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript
JavaScript:
(Microsoft's version: JScript)
originally named "LiveScript"
Versions 1.0 to 1.3:
Standard according to specification
ECMA-262 (ECMAScript, 1996/1997)
("European Computer Manufacturers Association")
Version 1.5 and up:
Implementation of the DOM
("Document Object Model")
Ref. ECMA-262:
http://www.ecma-international.org/publications/standards/Ecma-262.htm
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript
JavaScript and Java
JavaScript
Java
Interpreted by client (not compiled)
Compiled on server before
execution on client
Object-based, Code uses built-in,
extensible objects, but no classes
or inheritance
Object-oriented. Applets consist of
object classes with inheritance
Code integrated with and
embedded in HTML
Applets distinct from HTML
(accessed from HTML pages)
Variable data types not declared
(loose typing)
Variable data types must be
declared (strong typing)
Dynamic binding. Object references Static binding. Object references
checked at run-time
must exist at compile-time
Cannot automatically write to hard
disk
Internet Applications,  Helmut Dispert
Cannot automatically write to hard
disk
Fachbereich Informatik und Elektrotechnik
JavaScript Syntax
<SCRIPT>
JavaScript statements ...
</SCRIPT>
Optional:
language attribute to specify the scripting language
<SCRIPT LANGUAGE="JavaScript">
JavaScript statements ...
</SCRIPT>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript Syntax
HTML 4.0:
language attribute has been deprecated,
attribute TYPE specifies script language:
e.g. "text/javascript" , "text/vbscript"
<SCRIPT TYPE="text/javascript">
JavaScript statements ...
</SCRIPT>
JavaScript is case sensitive.
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript Syntax - Example
<HTML>
<HEAD>
<SCRIPT TYPE="text/javascript">
document.write("Hello net. ")
</SCRIPT>
</HEAD>
<BODY>
That's all, folks.
</BODY>
</HTML>
Output:
Hello net. That's all, folks.
JavaScript
Internet Applications,  Helmut Dispert
HTML-code
Fachbereich Informatik und Elektrotechnik
JavaScript Syntax - Comment, Code Hiding
Comment in JavaScript:
Multiple-line comment:
/*
Line 1
Line 2 ...
Line n
*/
Single-line (Inline) comment:
//
comment
or
code;
// comment
<SCRIPT>
<!--
Begin to hide script contents
from old browsers.
...
// End the hiding here. -->
</SCRIPT>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript Syntax - Statements
Statements:
a) simple statements:
Example:
z = 42;
b) block statements: delimited by braces "{ ... }"
Examples:
{
statements;
}
hierarchy of blocks:
{ ...
{ ...
}
}
Internet Applications,  Helmut Dispert
inner
block
outer
block
Fachbereich Informatik und Elektrotechnik
JavaScript Syntax
Example: Assignments
<script TYPE="text/javascript">
<!-var X = 42;
// -->
</script>
Variables store values for later use
JavaScript is loosly-typed (no need
to declare type of variables)
Variables can change type
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript Syntax
Example: Declaring numerical values
<script TYPE="text/javascript">
<!-var a = 10;
var a = 47.11;
var b = 1.2345E4;
var c = 2e-3;
// -->
</script>
Declaring JavaScript in separate file:
<script TYPE="text/javascript" SRC="filename.js">
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript Syntax - Operators
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
Rangstufe:
Rangstufe:
Rangstufe:
Rangstufe:
Rangstufe:
Rangstufe:
Rangstufe:
Rangstufe:
Rangstufe:
Rangstufe:
Rangstufe:
Rangstufe:
Rangstufe:
Rangstufe:
Rangstufe:
Internet Applications,  Helmut Dispert
, (Aneinanderreihung)
= += -= <<= >>= &= ^= |=
?: ( Entweder-Oder-Bedingung)
||
&&
|
^
&
== !=
< <= > >=
<< >> >>>
+ * / %
! ~ - ++ -() [] . (Klammerung und Vektoren)
Fachbereich Informatik und Elektrotechnik
JavaScript Syntax
Example: Comparisons
<script TYPE="text/javascript">
<!-if(X == 42) return 1;
if(X != 42) return 0;
if(X > 42) return 0;
if(X < 42) return 0;
if(age >= 18) alert("Okay!");
if(age <= 17) alert("Warning!");
// -->
</script>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript Syntax
Example: Arithmetic Operators
var two
= 1 + 1;
var N1
= 1 - 1;
var N2
= 81 / 3 - 27;
var Neg
= 81 / (3 - 27);
var X
= 6 * 7;
var res
= 84 / 2;
x = year % 4;
if(x == 0) lyear = true;
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript Syntax
Example: Arithmetic Operators
/* Special Notations: */
var Zahl;
Zahl += 3;
Zahl -= 2;
Zahl++;
Zahl--;
Zahl *= 4;
Zahl /= 3;
Internet Applications,  Helmut Dispert
Zahl = Zahl + 3;
Fachbereich Informatik und Elektrotechnik
JavaScript
Software Development
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Software Development - Waterfall Model
The Standard Waterfall Model for System Development
Upstream:
What activities
Downstream: How Acitivities
Requirements
Analysis
Specification
High Level Design
Low Level Design
Coding
Testing
Software Life Cycle
Internet Applications,  Helmut Dispert
Maintenance
Fachbereich Informatik und Elektrotechnik
Software Development - V-Model
The V-Model (Standard of German Federal Armed Forces)
system
requirements
system
integration
software
requirements
acceptance
test
preliminary
design
analyse
and
design
software
integration
detailed
design
code and
debug
Internet Applications,  Helmut Dispert
component
test
unit test
test
and
integrate
Fachbereich Informatik und Elektrotechnik
Software Development – Spiral Model
1.Objectives,
Alternatives,
Constraints
2.Risk Analysis
& Aversion
4.Planning
& Management
3.Product
Development
Developed at TRW
by
Barry W. Boehm
(1988)
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Software Development – Spiral Model
Typical Cycle of the Spiral
• Identification of
- objectives (of the portion of the product being elaborated)
- alternative means of implementing this portion of the product (design
A, design B, buy)
- constraints imposed on the application of the alternatives (cost,
schedule, copyright)
• Evaluate the alternatives relative to the objectives and constraints
- Identify areas of uncertainty that are significant sources of risk
- Evaluate the risks (e.g., by prototyping, simulation, benchmarking)
• The next step is determined by the relative remaining risks. Each level of
software specification and development is followed by a validation step.
• Each cycle is completed by the preparation of plans for the next cycle and
a review involving the primary people or organizations concerned with the
product. The review's major objective is to ensure that all concerned
parties are mutually committed to the approach for the next phase
Ref.: Dr. Jody Paul
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Structure Elements
Stucture Elements
Struktogramme
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Structure Elements
Struktogramme
(Nassi-Shneiderman-Diagramme, DIN 66261)
Elementarblock/Strukturblock:
Reihung/Sequenz:
f1
f1
f2
f3
.
.
.
fn
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Structure Elements
forming blocks:
Module block:
allowed
f1
f2
f3
Modul name
Modul description
f1
f2
f3
not allowed
.
.
.
f1
f2
f3
fn
f1, f2, ..., fn = structural blocks
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Structure Elements - Conditionals
Selektionsblöcke:
Alternative Anweisung (zweiseitige Auswahl):
true
b
f1
false
f2
b
f 1, f 2
= Bedingung
= Strukturblöcke
Alternative Anweisung (einseitige Auswahl):
true
f1
b
false
%
Internet Applications,  Helmut Dispert
b
f1
= Bedingung
= Strukturblock
Fachbereich Informatik und Elektrotechnik
Structure Elements - Conditionals
if (condition)
{
statements
}
true
f1
else
{
statements
}
Internet Applications,  Helmut Dispert
optional
b
false
%
Fachbereich Informatik und Elektrotechnik
Structure Elements
Fallunterscheidung (mit Fehlerausgang):
k1
v=
k2
else
kn
f1
f2
...
Internet Applications,  Helmut Dispert
fn
fx
v
= Variable
f1,...,fn = Strukturblöcke
k1,...,kn = Konstanten
Fachbereich Informatik und Elektrotechnik
Structure Elements - Loops
Iterationsblöcke:
Bedingungsschleife
(abweisende Schleife,
kopfgesteuerte Schleife):
solange b = wahr
f1
Pre-condition test
Internet Applications,  Helmut Dispert
b
f1
= Ausführungsbedingung
= Strukturblock
= Schleifenkörper
Fachbereich Informatik und Elektrotechnik
Structure Elements - Loops
Iterationsblöcke:
Bedingungsschleife
(nichtabweisende Schleife,
fußgesteuerte Schleife):
f1
bis b = wahr
Post-condition test
Internet Applications,  Helmut Dispert
b
f1
= Abbruchbedingung
= Strukturblock
= Schleifenkörper
Fachbereich Informatik und Elektrotechnik
Structure Elements - Loops
while (condition)
{
statements;
}
Pre-condition test
do
Post-condition test
{
statements;
}
while (condition);
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Structure Elements - Loops
Iterationsblöcke:
Zählschleife
(Sonderfall der Bedingungsschleife ):
sv = aw, ew [,sw]
f1
sv
aw
ew
sw
f1
= Schleifenvariable
= Anfangswert
= Endwert
= Schrittweite
(darf fehlen, wenn sw = +1)
= Strukturblock
= Schleifenkörper
Iteration,
"for" statement (similar to "while" statement)
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Structure Elements - for statement
for
([initialisation];[condition];[update])
{
statements;
}
Special loop: iteration through all properties of an object
for (var in object)
{
statements;
}
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Structure Elements
Aneinanderreihung von Strukturelementen
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Structure Elements
Schachtelung von Strukturelementen
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Functions
JavaScript Functions
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Functions
Functions:
set of JavaScript statements
identified by a unique name
can be called from other positions of the script
(reuse of code)
can (optionally) return a result
through a list of parameters (arguments) variables
can be passed to the function when it is called
no return type
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Functions
Functions: Syntax
Declaring a function (without parameters):
function fctName()
{
statements;
}
Declaring a function (with parameters):
function fctName(a, b, ..., n)
{
statements using parameters a, b, ..., n;
}
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Functions
Example:
function declaration:
function add(x,y)
{
z = x + y;
return z;
}
function call:
...
a = 10;
b = 5;
c = add(a,b);
...
Internet Applications,  Helmut Dispert
formal parameter list
actual parameter list
Fachbereich Informatik und Elektrotechnik
JavaScript - Functions
Example:
<HTML>
<HEAD>
<TITLE>Functions</TITLE>
<SCRIPT type="text/javascript">
function add(x,y) {
return x + y;
}
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
document.write("Sum '47 + 11' = " + add(47,11))
</SCRIPT>
</BODY>
</HTML>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Variables and data types
Variables and Data Types
Numbers Integer and floating-point numbers
Booleans
True or False
Strings
Objects
delineated by single or double
quotation marks
testObject = new Object();
Null
no value
Undefined
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Literals
Literals:
Integer
Floating Point
Boolean
Strings
Integer literals:
decimal:
octal:
hexadecimal:
Internet Applications,  Helmut Dispert
normal notation
0...
(leading zero)
0x... or 0X... (leading 0x)
Fachbereich Informatik und Elektrotechnik
JavaScript - Literals
Floating point literals:
decimal point notation
exponent notation (e, E)
Examples:
3.1415
.1E12
2e-10
Boolean literals:
values: "true" or "false"
Examples:
c = true;
z = false;
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Literals
String literals:
using quotes
Examples:
"Text"
"1234"
"line 1 \n line2"
Escape
characters:
Backslash (\) indicates that
a special character should
be used in the string.
Example:
s = "Print\na new line";
Internet Applications,  Helmut Dispert
Escape sequence
\n
\r, \f
\b
\t
\\
\"
\'
Description
Newline (linefeed)
Carriage return
Backspace
Horizontal tab
Backslash
Double quote
Single quote
Fachbereich Informatik und Elektrotechnik
JavaScript - Variables and data types
Loose typing,
Strings and string concatenation:
a = "The result is " (declaring a string variable)
b = 42
(declaring a number variable)
Concatenation:
x=a+b
y = "The result is " + 42
z = 42 + " is the result"
Internet Applications,  Helmut Dispert
The result is 42
The result is 42
42 is the result
Fachbereich Informatik und Elektrotechnik
JavaScript - Scope of Variables
Local and Global Variables:
The "scope" of a variable refers to the visibility of
a variable within a program.
Global variables:
accessible from anywhere in the program
retain their values until the document is unloaded
(persistent variables)
Local variables:
accessible (visible) only within the functions that created
them
created for temporary use
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Scope of Variables
Global variables are used to store values that
must be maintained throughout the life of the document
need to be accessed from many points in the program
Initializing local/global variables:
variables initialized inside a function using the keyword
"var" have a local scope
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Scope of Variables
Example:
a = 10;
/* global variable */
function disp() {
var a = 20;
/* local variable */
document.write("a inside the function: " + a);
}
disp();
/* function call */
document.write("<BR>");
document.write("a outside the function: " + a);
glob
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript Objects
JavaScript is an object-based programming
language
(not truely object-oriented because inheritance and
polymorphism are not fully supported)
JavaScript objects:
well defined data elements with properties and object
related function (methods):
browser elements: windows, documents, frames,
forms (input fields, checkboxes, buttons, etc.), dates,
etc.
Properties of JavaScript objects:
used to describe and modify objects.
Methods of JavaScript objects:
define what object can do (e.g. open windows,
frames, etc.).
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript Objects
Predefined Objects
are used to describe and manipulate
elements of an HTML-form;
frames, images, applets, etc.
Objects are organized in a hierarchy and can be
part of a higher level object.
Highest object in the hierarchy:
window
- contains properties like "title", "size", etc.
document - contains the html-file
HTML-elements
Internet Applications,  Helmut Dispert
next lower object
contained in window
Fachbereich Informatik und Elektrotechnik
JavaScript Objects
JavaScript object are described using the
"dot syntax":
Objects, properties, methods are separated
by periods ("dots").
Examples:
car.wheels
computer.disk.floppy
document.images.name
window.status
properties
document.write()
forms.elements.radio.click()
date.getTime()
Internet Applications,  Helmut Dispert
methods
Fachbereich Informatik und Elektrotechnik
JavaScript Objects
Class-Definition:
Template (blueprint, prototype) of an object.
Methods
Variable Declarations
Object-Definition:
Software unit of variables (data) and related
methods.
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Arrays
Array:
Array object (object oriented)
group of memory locations
0
1
2
3
position number
4
5
6
7
8
9
ArrayName 47 11 05 14 14 36 04 03 02 01
Name of Array
Array Element
Internet Applications,  Helmut Dispert
ArrayName[0]
ArrayName[1]
ArrayName[2]
ArrayName[3]
...
=
=
=
=
47
11
05
14
Fachbereich Informatik und Elektrotechnik
JavaScript - Arrays
new operator:
used to create an instance of an array object in
memory (reserving the required number of memory
locations).
example1:
example2:
var ArrayName;
ArrayName = new Array(10);
quest = new Array(2);
quest[0] = "Yes";
quest[1] = "No";
example3:
var x = new Array(100);
for (i=0; i < x.length; ++i) x[i] = i;
predefined objects:
example4:
lnk1 = document.links[0];
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Examples
JavaScript
Examples
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - predefined function "alert"
<html>
<head>
<title>Test</title>
<script TYPE="text/javascript">
<!-alert("Hello World!");
//-->
</script>
</head>
<body>
</body></html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Conditional statements - "if"
<script TYPE="text/javascript">
<!-if(PLZ >= 20000 && PLZ <= 24000)
alert("Kiel and vicinity!")
if(x > 100 || y == 0)
break;
// -->
</script>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Conditional statements - "if"
<html>
<head><title>TestUser</title>
<script TYPE="text/javascript">
<!-var Passwort = "FHKiel";
UserEingabe = window.prompt("Enter password","");
if(UserEingabe != Passwort)
{
alert("Wrong password!");
history.back();
}
else
document.location.href="geheim.htm";
// -->
</script>
</head>
<body>
</html>
</body>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - "if - then - else"
Ternary Operator:
The ternary operator takes three operands.
Syntax:
condition ? result1 : result2;
Example:
var x = (Answer == "42") ? "Yes" : "No";
alert("The answer is " + x + " !");
This is equivalent to:
if (Answer == "42")
x = "Yes";
else
x = "No";
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - "Switch"
Eingabe = window.prompt("Zahl eingeben","");
switch(Eingabe)
{
case "1":
alert("Zahl = 1");
break;
case "2":
alert("Zahl = 2");
break;
case "3":
alert("Zahl = 3");
break;
case "4":
alert("Zahl = 4");
break;
default:
alert("Zahl ungueltig");
break;
}
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Loop "while"
var Passwort = "FHKiel";
var UserEingabe = "";
var Zaehler = 0;
while((UserEingabe != Passwort)&&(Zaehler <= 3))
{
UserEingabe = window.prompt(Zaehler +
". Versuch: geben Sie das Passwort ein","");
Zaehler++;
}
if(UserEingabe != Passwort)
history.back();
else
document.location.href="geheim.htm";
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Loop "while"
<script language="JavaScript">
<!-var x = 1;
while(x < 10)
{
document.write("<br>x * x = " + (x * x));
x = x + 1;
}
// -->
</script>
Pre-condition test
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Loop "while"
<script language="JavaScript">
<!-var x = 10;
No Problem
while(x < 10)
{
document.write("<br>x * x = " + (x * x));
x = x + 1;
}
// -->
</script>
Pre-condition test
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Loop "do-while"
<script language="JavaScript">
<!-var x = 10;
Problem
do
{
document.write("<br>x * x = " + (x * x));
x = x + 1;
}
Problem
while(x < 10);
// -->
</script>
Post-condition test
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Loop "break und continue" 1
<script TYPE="text/javascript">
<!-var i = 0;
while (i < 6)
{
if (i == 3) break;
i++;
}
alert("i = " + i);
// -->
</script>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Loop "break und continue" 2
<script TYPE="text/javascript">
<!-var i = 0;
while (i < 6)
Label:
{
important for nested loops
Ende:
if (i == 3)
{
alert("Ende, i = " + i);
break Ende;
}
i++;
}
// -->
</script>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Loop "break und continue" 3
<script TYPE="text/javascript">
<!-var i = 0, j = 0;
while (i < 6)
{
i++;
if (i == 3) continue;
j++;
}
alert("i = " + i + " und j = " + j);
</script>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Loop "for"
<body>
<script TYPE="text/javascript">
<!-for(i = 1; i <= 100; i++)
{
var x = i * i;
document.write("<br>Das Quadrat von "
+ i + " ist " + x);
}
// -->
</script>
</body>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Function, "onClick"
<html>
<head>
<title>JavaScript-Test</title>
<script TYPE="text/javascript">
<!-function Quadrat(Zahl)
{
Ergebnis = Zahl * Zahl;
alert("Das Quadrat von " + Zahl + " = " + Ergebnis);
}
//-->
</script>
</head>
<body>
<form>
<input type="button" value="Quadrat von 6 errechnen"
onClick="Quadrat(6)">
</form>
</body>
</html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Function, separate file
<html>
<head>
<title>JavaScript-Test</title>
<script src="quadrat.js" type="text/javascript">
</script>
</head>
<body>
<form>
<input type=button value="Quadrat von 6 errechnen"
onClick="Quadrat(6)">
</form>
</body>
</html>
function Quadrat(Zahl)
{
Ergebnis = Zahl * Zahl;
alert("Das Quadrat von " + Zahl +
" = " + Ergebnis);
}
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Examples
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Objects
JavaScript
Objects
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript Object Hierarchy
predefined objects
self, window,
parent, top
various Window objects
navigator
plugins [ ]
array of Plugin objects
Navigator object
mimeTypes [ ]
frames [ ]
array of MimeType objects
array of Window objects
The
Current
Object
forms [ ]
location
array of Form objects
elements [ ]
array of HTML Form
element objects:
Location object
anchors [ ]
history
array of Anchor objects
History object
links [ ]
document
array of Link objects
Document object
images [ ]
Packages
array of Image objects
JavaPackage object
applets [ ]
array of JavaObject objects
various JavaPackage
and JavaClass objects
Internet Applications,  Helmut Dispert
Button
Checkbox
FileUpload
Hidden
Password
Radio
Reset
Select
Submit
Text
Textarea
embeds [ ]
options [ ]
array of JavaObject objects
array of Option objects
Fachbereich Informatik und Elektrotechnik
JavaScript- Browser Windows and Frames
self, window
frames[0]
frames[1]
frames[1].
frames[0]
frames[1].
frames[1]
top
parent
self
window
parent.frames[2]
parent.frames[0]
top.frames[0]
top.frames[1]
parent.parent
Internet Applications,  Helmut Dispert
frames[1].
frames[2]
Fachbereich Informatik und Elektrotechnik
JavaScript Object Hierarchy
JavaScript objects are arranged in a hierarchy.
Example: window
window
document
form
window object
current document
form in document
form elements
Internet Applications,  Helmut Dispert
button
checkbox
radio
text
textarea
Fachbereich Informatik und Elektrotechnik
JavaScript- Predefined Object "Window"
Properties of Window object
closed
defaultStatus
innerHeight
innerWidth
locationbar
menubar
geschlossenes Fenster
Normalanzeige in der Statuszeile
Höhe des Anzeigebereichs
Breite des Anzeigebereichs
URL-Adresszeile
Menüleiste
name
outerHeight
outerWidth
pageXOffset
pageYOffset
personalbar
scrollbars
statusbar
status
toolbar
Fenstername
Höhe des gesamten Fensters
Breite des gesamten Fensters
Fensterstartposition von links
Fensterstartposition von oben
Zeile für Lieblingsadressen
Scroll-Leisten
Statuszeile
Inhalt der Statuszeile
Werkzeugleiste
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript- Predefined Object "Window"
Methods of Window object - 1
alert()
back()
blur()
captureEvents()
clearInterval()
clearTimeout()
close()
confirm()
disableExternalCapture()
enableExternalCapture()
find()
focus()
forward()
handleEvent()
home()
moveBy()
Internet Applications,  Helmut Dispert
Dialogfenster mit Infos
zurück in History
Fenster verlassen
Ereignisse überwachen
zeitliche Anweisungsfolge abbrechen
Timeout abbrechen
Fenster schließen
Dialogfenster zum Bestätigen
Fremdüberwachung verhindern
Fremdüberwachung erlauben
Text suchen
Fenster aktiv machen
vorwärts in History
Ereignis übergeben
Startseite aufrufen
bewegen mit relativen Angaben
Fachbereich Informatik und Elektrotechnik
JavaScript- Predefined Object "Window"
Methods of Window object - 2
moveTo()
open()
print()
prompt()
releaseEvents()
resizeBy()
resizeTo()
routeEvent()
scrollBy()
scrollTo()
setInterval()
setTimeout()
stop()
Internet Applications,  Helmut Dispert
bewegen mit absoluten Angaben
neues Fenster öffnen
ausdrucken
Dialogfenster für Werteingabe
Ereignisse abschließen
Größe verändern mit relativen Angaben
Größe verändern mit absoluten Angaben
Event-Handler-Hierarchie durchlaufen
Scrollen um Anzahl Pixel
Scrollen zu Position
zeitlische Anweisungsfolge setzen
Timeout setzen
abbrechen
Fachbereich Informatik und Elektrotechnik
JavaScript- Predefined Object "Window"
Important Properties of the Window Object
document
self
parent
history
location
frames
length
name
defaultStatus
status
document contained in the window
identifies current window being referenced
identifies the window containing a particular
window
list of visited URLs
window's URL
array containing the window's frames
number of frames in the window
window's name
default message in the status bar
temporary message in the status bar
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript- Predefined Object "Window"
<html>
<head>
<title>Test</title>
<script type="text/javascript">
window.defaultStatus = "My Homepage";
</script>
</head>
<body>
</body>
</html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript- Predefined Object "Window"
Important Methods of the Window Object
alert(text)
confirm(text)
prompt(text, def)
open(url, [options])
close()
focus()
blur()
Internet Applications,  Helmut Dispert
open pop-up-box
pop-up-box with "OK" or "Cancel"
user input of a line of text
open up new window
close window
give focus to a window
remove focus from a window
Fachbereich Informatik und Elektrotechnik
JavaScript- Predefined Object "Window"
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function NewWindow()
{
MyWindow =
window.open("testwin.html", "Zweitfenster",
"width=250,height=100,scrollbars");
MyWindow.focus();
}
</script>
</head>
<body>
<a href = "javascript: NewWindow()">New Window</a>
</body>
</html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript- window: open() - Parameter
dependent
Yes:
No:
height
Höhe des neuen Fensters in Pixeln, z.B. height=200
hotkeys
No:
Yes:
innerHeight
Höhe des Anzeigebereichs des neuen Fensters in Pixeln, z.B. innerHeight=200
innerWidth
Breite des Anzeigebereichs des neuen Fensters in Pixeln, z.B. innerWidth=200
Locationbar
Yes:
No:
Fenster erhält eine eigene URL Adreßzeile.
(deafult) Fenster erhält keine Adreßzeile.
menubar
Yes:
No:
Fenster erhält eine eigene Menüleiste mit Browser Befehlen.
(deafult) Fenster erhält keine Menüleiste.
resizable
No:
Yes:
Anwender kann das Fenster in der Größe nicht verändern.
(default) Anwender kann die Fenstergröße ändern.
screenX
Horizontalwert der linken oberen Ecke des neuen Fensters in Pixeln, z.B. screenX=100
screenY
Vertikalwert der linken oberen Ecke des neuen Fensters in Pixeln, z.B. screenY=30
status
Yes:
No:
width
Breite des neuen Fensters in Pixeln, z.B. width=400
Fenster wird geschlossen, wenn sein Elternfenster geschlossen wird.
(default) Fenster bleibt erhalten, wenn sein Elternfenster geschlossen wird.
Tastaturbefehle zum Steuern des Browsers in dem Fenster deaktiviert
(default) Tastaturbefehle des Browsers in dem Fenster gültig.
Fenster erhält eine eigene Statuszeile.
(default) Fenster erhält keine Statuszeile.
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript- window: closed
<html>
<head><title>Test</title>
<script type="text/javascript">
var InfoWin = window.open("testwin.html", "Zweitfenster");
function CheckOpen()
{
if(InfoWin.closed == true) alert("Window already closed");
else alert("Window still open");
}
</script>
</head>
<body>
<a href="javascript:CheckOpen()">Window closed?</a>
</body>
</html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript- window: status
<html>
<head>
<title>Test</title>
</head>
<body>
<a href="datei.html"
onmouseover=
"status='this is a link';return true;">
Verweis</a>
</body>
</html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript- window: alert()
<html>
<head>
<title>Test</title>
</head>
<body>
<a href="javascript:alert('No Information')">
Information</a>
</body>
</html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript- back(), home(), forward()
<html>
<head>
<title>Test</title>
</head>
<body>
<a href="javascript:window.back()">Go Back</a>
</body>
</html>
...
<a href="javascript:home()">Home</a>
<a href="javascript:window.forward()">Vor</a>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript- window: close()
<html>
<head>
<title>Test</title>
<script type="text/javascript">
Info = window.open("testwin.html", "Zweitfenster");
</script>
</head>
<body>
<form>
<input type="button" value="close window"
onClick="Info.close()">
</form>
</body>
</html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript- window: confirm()
<html>
<head>
<title>Test</title>
<script type="text/javascript">
Check = confirm("Verify this page?");
if(Check == false) history.back();
</script>
</head>
<body>
</body>
</html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript- window: print()
<html>
<head>
<title>Test</title>
</head>
<body>
<a href="javascript:window.print()">
Print this page</a>
</body>
</html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript- window: setTimeout()
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function Hinweis()
{
x = confirm("10 seconds passed. Continue?");
if(x == false) top.close();
value in msec
}
window.setTimeout("Hinweis()",10000);
</script>
</head>
<body>
<a href="javascript:()">Text?</a>
</body>
</html>
Internet Applications,  Helmut Dispert
timeout
Fachbereich Informatik und Elektrotechnik
JavaScript - Frames
JavaScript
Frames
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Frames
Frames
Property
length
Function
number of frames
Subobjects
document
event
history
location
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Frames
<html>
<head>
<title>Test</title>
<script type="text/javascript">
for(i=0; i < parent.frames.length; ++i)
alert(parent.frames[i].name);
</script>
</head>
<body>
</body>
</html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Predefined Object "Document"
Properties of document object
alinkColor
Farbe für Verweise beim Anklicken
bgColor
Hintergrundfarbe
charset
verwendeter Zeichensatz
cookie
beim Anwender speicherbare Zeichenkette
defaultCharset
normaler Zeichensatz
fgColor
Farbe für Text
lastModified
letzte Änderung am Dokument
linkColor
Farbe für Verweise
referrer
zuvor besuchte Seite
title
Titel der Datei
URL
URL-Adresse der Datei
VlinkColor
Farbe für Verweise zu besuchten Zielen
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Predefined Object "Document"
Methods of Document object
captureEvents()
Ereignisse überwachen
close()
schließen
getSelection()
selektierter Text
handleEvent()
Ereignisse verarbeiten
open()
Dokument öffnen
releaseEvents()
Ereignisse abschließen
routeEvent()
Event-Handler-Hierarchie durchlaufen
write()
ins Dokumentfenster schreiben
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Subobjects of "document"
document
Subobjects
all
anchors
applets
areas
embeds
Internet Applications,  Helmut Dispert
Subobjects
forms
images
layers
links
plugins
Fachbereich Informatik und Elektrotechnik
JavaScript - Examples: use of "document"
Example Statements:
x = document.title;
x = window.document.title;
Zweitfenster = window.open("datei2.htm", "Fenster");
x = Zweitfenster.document.title;
y = parent.frames[2].document.bgColor;
document.write("Hallo Welt");
window.document.write("Hallo Welt");
Zweitfenster.document.close();
parent.frames[2].document.close();
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Examples: use of "bgcolor"
<html>
<head><title>Test</title>
<script type="text/javascript">
var X = new Array("0","1","2","3","4","5","6","7","8","9",
"A","B","C","D","E","F");
document.write("<H1>Color Test</H1>");
var x1 = 0, x2 = 0;
for(i = 0; i < 255; ++i)
{
document.bgColor = X[x1] + X[x2] + X[x1] + X[x2] + X[x1] + X[x2];
x2 = x2 + 1;
if(x2 % 16 == 0) { x2 = 0; x1 = x1 + 1; }
}
</script>
</head>
<body>
</body>
</html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Examples: Two functions
<HTML>
<HEAD>
<SCRIPT>
<!--- hide script from old browsers
function bar()
{
document.write(" <HR ALIGN='left' WIDTH=25%>");
return
}
function output(head, level, string)
{
document.write("<H" + level + ">" + head + "</H"
+ level + "><P>" + string)
}
//* end hiding from old browsers -->
</SCRIPT>
</HEAD>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Examples: Two functions
<BODY>
<SCRIPT>
<!--- hide script from old browsers
bar();
output("Fettdruck (hervorgehoben)",3,"Normaldruck.");
bar();
//* end hiding from old browsers -->
</SCRIPT>
<P>
Vielen Dank!
</BODY>
</HTML>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Examples: Eval functions
<HTML>
<HEAD>
<TITLE>Use Eval-function</TITLE>
<SCRIPT TYPE="text/javascript">
<!-function Simple()
{
var Result = eval("1+1");
alert("1 + 1 = " + Result);
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<A HREF="javaSCRIPT:Simple()">How much is 1+1?</A>
</BODY>
</HTML>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Examples: Function back()
<HTML>
<HEAD>
<TITLE>Back </TITLE>
</HEAD>
<BODY>
<A href="javascript:history.back();">Go Back</A>
</BODY>
</HTML>
Pseudo event handler
Call method back() of object history:
object: history
method: back()
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Navigator
JavaScript
Navigator Object
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Navigator
Navigator object
not within the normal JavaScript object hierarchy
used to obtain information about the client
platform
used for the development of browser-dependent
code
Example:
if (navigator.appName == "Netscape") {
// code for Netscape browser
}
else {
// code for other browsers
}
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Navigator
navigator object
• appCodeName:
Spitzname des Browsers
• appName:
offizieller Name des Browsers
• appVersion:
Browser-Version
• language:
Browser-Sprache
• platform:
Plattform, auf der der Browser läuft
• userAgent:
HTTP-Identifikation des Browser
• javaEnabled():
Unterstützung von Java
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - appCodeName
appCodeName
<html><head><title>Test</title>
<script language="JavaScript">
if(navigator.appCodeName == "Mozilla")
alert("Netscape Browser!");
</script>
</head><body>
</body></html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - appName
appName
<html><head><title>Test</title>
<script language="JavaScript">
</script>
</head>
<body>
<script language="JavaScript">
document.write("Using: " + navigator.appName);
</script>
</body>
</html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - appVersion, platform
appVersion
<script language="JavaScript">
if(navigator.appVersion.substring(0,1) == "4")
alert("Browser der 4. Generation!");
</script>
platform
<script language="JavaScript">
alert(navigator.platform);
</script>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - userAgent
userAgent
<html><head><title>Test</title>
</head>
<body>
Browser-ID:<br>
<script language="JavaScript">
document.write(navigator.userAgent);
</script>
</body>
</html>
Mozilla/4.7 [en] (Win98; U)
Mozilla/4.0 (compatible; MSIE 5.01;
Windows 98; QXW0332c)
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Event Handlers
JavaScript
Event Handlers
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Event Handlers
Event Binding (client side):
Process of instructing an HTML element to respond to a system
or user event.
Syntax:
<TAG eventHandler="JavaScript Code">
with: TAG:
eventHandler:
HTML tag
name of event handler.
Example:
<INPUT
TYPE="button" VALUE="Calculate"
onClick="compute(this.form)">
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Event Models
Event Models:
Support the Document Object Model (DOM)
Event Binding Model 1: Element Attributes
<TAG eventHandler="JavaScript Code">
Example:
<INPUT TYPE="button" onClick="myFunc()">
Event Binding Model 2: Object Properties
Binding events to obects using script statements, assigning a
function reference to an event property.
Example statement:
document.forms[0].mybutton.onclick = myFunc;
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Event Models
Event Binding Model 3: MS-IE <SCRIPT FOR> Tags
Microsoft implements a propietary extension to the <SCRIPT> tag
to bind the enclosed script statements to one event type for one
element.
Example:
<INPUT TYPE="button" NAME="myButton“
ID="button1" VALUE="Click here">
Script statements (no function):
<SCRIPT FOR="button1" EVENT="onclick“>
// script statements
</SCRIPT>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Event Handlers
Events apply to HTML tags as follows:
Events
HTML tags
Focus, Blur, Change events
text fields, textareas, and selections
Click events
buttons, radio buttons, checkboxes,
submit buttons, reset buttons, links
Select events
text fields, textareas
MouseOver event
links
Special Syntax:
this.form
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Event Handlers
OnAbort
OnBlur
OnChange
OnClick
bei Abbruch
beim Verlassen
bei erfolgter Änderung
beim Anklicken
OnDblClick
OnError
OnFocus
OnKeydown
OnKeypress
OnKeyup
bei doppeltem Anklicken
im Fehlerfall
beim Aktivieren
bei gedrückter Taste
bei erfolgtem Tastendruck
bei losgelassener Taste
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Event Handlers
OnLoad
beim Laden einer Datei
OnMousedown
bei gedrückter Maustaste
OnMousemove
bei weiterbewegter Maus
OnMouseout
beim Verlassen des Elements mit der Maus
OnMouseover
beim Überfahren des Elements mit der Maus
OnMouseUp
bei losgelassener Maustaste
OnReset
beim Zurücksetzen des Formulars
OnSelect
beim Selektieren von Text
OnSubmit
beim Absenden des Formulars
OnUnload
beim Verlassen der Datei
javascript:
bei Verweisen
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - onSubmit
<html><head><title>Test</title>
<script language="JavaScript">
function CheckInput()
{
for(i=0; i<document.forms[0].elements.length; ++i)
if(document.forms[0].elements[i].value == "")
{
alert("Nicht alle Felder ausgefuellt!");
document.forms[0].elements[i].focus();
return false;
}
return true;
}
</script>
</head><body>
<form onSubmit="return CheckInput();">
Feld 1: <input size=30><br>
Feld 2: <input size=30><br>
Feld 3: <input size=30><br>
<input type=submit>
</form>
</body></html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - onSubmit
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Event handler "onAbort"
onAbort - Image element aborted
Allowed in the following HTML-tags (Netscape, 4.0):
<img>
Beispiel:
<html>
<head><title>Test</title>
</head>
<body>
<img src="grafik.jpg" width=400 height=600
alt="Grafik"
onAbort="alert('Loading interrupted')">
</body>
</html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Event handler "onBlur"
onBlur - Element becomes inactive
Allowed in the following HTML-tags (Netscape):
<body> <frameset> <input> <layer> <select>
<textarea>
HTML 4.0: Allowed in the following HTML-tags:
<body> <frameset> <input> <layer> <select>
<textarea>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Event handler "onBlur"
Beispiel:
<form name="Test">
Name: <input type=text name="Eingabe"
onBlur="TestInhalt(this.value)">
</form>
<script language="JavaScript">
document.Test.Eingabe.focus();
function TestInhalt(Feld)
{
if(Feld == "")
{
alert("Feld muss einen Inhalt haben!");
document.Test.Eingabe.focus();
return false;
}
}
</script>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Event handler "onChange"
onChange - Form element has changed
Allowed in the following HTML-tags (Netscape, 4.0):
<input> <select> <textarea>
Beispiel:
<form name="Test">
<textarea rows="10" cols="40"
onChange="alert(this.value)">
Your Comment!
</textarea>
</form>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Event handler "onClick"
onClick - Element is clicked
Allowed in the following HTML-tags (Netscape):
<a> <area> <input> <textarea>
HTML 4.0: Allowed in the following HTML-tags:
<a> <abbr> <acronym> <address> <area> <b> <big>
<blockquote> <body> <button> <caption> <center>
<cite> <code> <col> <colgroup> <dd> <del> <dfn>
<dir> <div> <dl> <dt> <em> <fieldset> <form>
<h1> <h2> <h3> <h4> <h5> <h6> <hr> <i> <img>
<input> <ins> <kbd> <label> <legend> <li> <link>
<map> <menu> <noframes> <noscript> <object> <ol>
<optgroup> <option> <p> <pre> <q> <s> <samp>
<select> <small> <span> <strike> <strong> <sub>
<sup> <table> <tbody> <td> <textarea> <tfoot>
<th> <thead> <tr> <tt> <u> <ul> <var>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Event handler "onClick"
Beispiel:
<html>
<head><title>Test</title>
</head>
<body>
<form>
<input size="40" name="Ausgabe" readonly><br>
<input type="button" value="Letzter Update"
onClick="this.form.Ausgabe.value
=document.lastModified">
</form>
</body>
</html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Event handler "onDblClick"
onDblClick - Element is double-clicked
Allowed in the following HTML-tags (Netscape):
<a> <area> <input> <textarea>
HTML 4.0: Allowed in the following HTML-tags:
<a> <abbr> <acronym> <address> <area> <b> <big>
<blockquote> <body> <button> <caption> <center>
<cite> <code> <col> <colgroup> <dd> <del> <dfn>
<dir> <div> <dl> <dt> <em> <fieldset> <form>
<h1> <h2> <h3> <h4> <h5> <h6> <hr> <i> <img>
<input> <ins> <kbd> <label> <legend> <li> <link>
<map> <menu> <noframes> <noscript> <object> <ol>
<optgroup> <option> <p> <pre> <q> <s> <samp>
<select> <small> <span> <strike> <strong> <sub>
<sup> <table> <tbody> <td> <textarea> <tfoot>
<th> <thead> <tr> <tt> <u> <ul> <var>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Event handler " onDblClick"
Beispiel:
<body>
<form name="Rechnen">
Wert:<br>
<input size="40" name="Wert"><br>
<input size="40" name="Ausgabe" readonly><br>
<input type="button" value="Doppelklick = * 2"
onDblClick="document.Rechnen.Wert.value
=document.Rechnen.Wert.value*2"
onClick="this.form.Ausgabe.value
=document.lastModified">
</form>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Event handler "onError"
onError - Image element error
Allowed in the following HTML-tags (Netscape, 4.0):
<img>
Beispiel:
<html>
<head><title>Test</title>
</head>
<body>
<img src="bild.gif" onError="alert('No Grafics')">
</body>
</html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Event handler "onFocus"
onFocus - Element becomes active
Allowed in the following HTML-tags (Netscape):
<body> <frame> <input> <layer> <select>
<textarea>
HTML 4.0: Allowed in the following HTML-tags:
<a> <area> <button> <input> <label> <select>
<textarea>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Event handler " onFocus"
Beispiel:
<html>
<head><title>Test</title>
</head>
<body>
<form>
<input onFocus="this.value='Name ?'"><br>
<input onFocus="this.value='Wohnort ?'"><br>
<input onFocus="this.value='Alter ?'"><br>
</form>
</body>
</html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Event handler "onLoad"
onLoad - during loading of document
Allowed in the following HTML-tags (Netscape, 4.0):
<frameset> <body>
Beispiel:
function NavWindow()
// header section
{
Navigation = window.open("navigat.htm",
"Navigation","height=100,width=300");
Navigation.focus();
}
...
<body onLoad="NavWindow()">
// body section
</body>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Event handler "javascript"
javascript - Pseudo Event Handler
Allowed in the following HTML-tags (Netscape, 4.0):
<a> <area>
Beispiel:
<html>
<head><title>Test</title>
</head>
<body>
<a href="javascript: alert(document.lastModified)">
Last Update</a>
</body>
</html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript – Evaluate form data
<html>
<head>
<script type="text/javascript">
function compute(form)
{
if (confirm("Sind Sie sicher?"))
form.result.value = eval(form.expr.value)
else
alert("Auf Wiedersehen")
}
</script>
</head>
continue
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript - Evaluate form data
<BODY>
<FORM>
bitte Ausdruck eingeben:<BR>
<INPUT TYPE="text" NAME="expr" SIZE=15 >
<INPUT TYPE="button" VALUE="Berechnen"
ONCLICK="compute(this.form)"><BR><BR>
Result:<BR>
<INPUT TYPE="text" NAME="result" SIZE=15 >
</FORM>
</BODY>
</HTML>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Date Object
JavaScript
Date Object
(enhanced by ECMA-262)
used to manipulate dates and times
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Date Object
1. Create an instance of the Date object
using the "new" keyword :
var my_date = new Date()
2. Access the methods of the Date object:
Example: return the date (day, 1 - 31)
my_date.getDate()
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Date Object
Constructor:
new Date()
new Date(milliseconds)
new Date(datestring)
new Date(year, month, day, hours, minutes, seconds, ms)
Format examples:
new Date("Month dd, yyyy hh:mm:ss")
new Date("Month dd, yyyy")
new Date(yy,mm,dd,hh,mm,ss)
new Date(yy,mm,dd)
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Date Object
Examples:
var my_date=new Date("December 10, 2003 14:20:00")
var my_date=new Date("December 10, 2003")
var my_date=new Date(2003,11,10,14,20,00)
var my_date=new Date(2003,11,10)
var my_date=new Date(500)
Observe:
range for month: 0 - 11
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Date Object - Methods
Methods:
Method
Description
Date()
Returns a Date object
getDate()
Returns the date of a Date object (from 1-31)
getDay()
Returns the day of a Date object (f0-6. 0=Sunday,
1=Monday, etc.)
getMonth()
Returns the month of a Date object (0-11. 0=January,
1=February, etc.)
getFullYear()
Returns the year of a Date object (four digits)
getYear()
Returns the year of a Date object (0-99).
getHours()
Returns the hour of a Date object (0-23)
getMinutes()
Returns the minute of a Date object (0-59)
getSeconds()
Returns the second of a Date object (0-59)
getMilliseconds()
Returns the millisecond of a Date object (0-999)
Deprecated
continued
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Date Object - Methods
Method
Description
getTimezoneOffset()
Return the time difference between the user's computer
and GMT
getUTCDate()
Return the date of a Date object in universal (UTC) time
getUTCDay()
Return the day of a Date object in universal time
getUTCMonth()
Return the month of a Date object in universal time
getUTCFullYear()
Return the four-digit year of a Date object in universal
time
getUTCHours()
Return the hour of a Date object in universal time
getUTCMinutes()
Return the minutes of a Date object in universal time
getUTCSeconds()
Return the seconds of a Date object in universal time
getUTCMilliseconds()
Return the milliseconds of a Date object in universal time
parse()
Return a string date value that holds the number of
milliseconds since January 01 1970 00:00:00
continued
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Date Object - Methods
Method
Description
setDate()
Set the date of the month in the Date object (1-31)
setFullYear()
Set the year in the Date object (digits)
setHours()
Set the hour in the Date object (0-23)
setMilliseconds()
Set the millisecond in the Date object (0-999)
setMinutes()
Set the minute in the Date object (0-59)
setMonth()
Set the month in the Date object (0-11. 0=January,
1=February)
setSeconds()
Set the second in the Date object (0-59)
setTime()
Set the milliseconds after 1/1-1970
setYear()
Set the year in the Date object (00-99)
setUTCDate()
Set the date in the Date object, in universal time (1-31)
continued
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Date Object - Methods
Method
Description
setUTCDay()
Sets the day in the Date object, in universal time (0-6.
Sunday=0, Monday=1, etc.)
setUTCMonth()
Sets the month in the Date object, in universal time (0-11.
0=January, 1=February)
setUTCFullYear()
Sets the year in the Date object, in universal time (four
digits)
setUTCHour()
Sets the hour in the Date object, in universal time (0-23)
setUTCMinutes()
Sets the minutes in the Date object, in universal time (0-59)
setUTCSeconds()
Sets the seconds in the Date object, in universal time (0-59)
setUTCMilliseconds()
Sets the milliseconds in the Date object, in universal time
(0-999)
toGMTString()
Converts the Date object to a string, set to GMT time zone
toLocaleString()
Converts the Date object to a string, set to the current time
zone
toString()
Converts the Date object to a string
continued
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Date Object - Example "date"
<html>
<body>
Returns today's date
<script type="text/javascript">
var d = new Date()
document.write(d.getDate())
document.write(".")
document.write(d.getMonth() + 1)
document.write(".")
document.write(d.getFullYear())
</script>
</body>
</html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Date Object - Example "time"
<html>
<body>
Return the current local time
<script type="text/javascript">
var d = new Date()
document.write(d.getHours())
document.write(".")
document.write(d.getMinutes())
document.write(".")
document.write(d.getSeconds())
</script>
</body>
</html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Date Object - Example "UTC"
<html>
<body>
Return the
Universal Coordinated Time (UTC,
time set by the World Time Standard)
<script type="text/javascript">
var d = new Date()
document.write(d.getUTCHours())
document.write(".")
document.write(d.getUTCMinutes())
document.write(".")
document.write(d.getUTCSeconds())
</script>
</body>
</html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Math Object
JavaScript
Math Object
used to perform mathematical calculations
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Math Object
Method
Description
abs(x)
absolute value of x
ceil(x)
rounds x to the smallest integer not less than x
cos(x)
trigonometric cosine of x (radians)
exp(x)
exponential function ex
floor(x)
rounds x to the largest integer not greater than x
log(x)
natural logarithm of x (base e)
max(x,y)
larger value of x and y
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
sin(x)
trigonometric sine of x (radians)
sqrt(x)
square root of x
tan(x)
trigonometric tangent of x (radians)
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Math Object
Commonly used mathematical constants
Constant
Description
Math.E
Euler's constant e
Math.LN2
Natural logarithm of 2
Math.LN10
Natural logarithm of 10
Math.LOG2E
Base 2 logarithm of Euler's constant
Math.LOG10E
Base 10 logarithm of Euler's constant
Math.PI
PI
Math.SQRT1_2 Square root of 0.5
Math.SQRT2
Square root of 2.0
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Cookies
Cookie:
Definition:
A cookie is a small amount of named data stored by the web
browser and associated with a particular web page or web site.
Cookies serve to give the web browser a memory.
Ref.:
David Flanagan, JavaScript, The Definitive Guide
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Cookies
Cookie:
Small piece of textual information that is sent from a server to
a browser. The server can read the information back, in order
to get information about the client's previous visit.
Characteristics of Cookies:
Key-value pairs
Way for server to store information on client
Server appends to HTTP response headers
Client appends to HTTP request headers
Cookies are single-valued
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Cookies
Benefits of Cookies:
User Identification
Storing User ID (Username) and Password
Customize a Web-Site
Allow client specific (focused) advertising
Using Cookies:
Typical applications of Cookies
Identifying a user during an e-commerce session
(Servlets provide API)
Avoiding username and password
Focusing advertising
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Cookies
<html>
<head>
<title>Test</title>
<script language="JavaScript">
var XMemo = "nothing stored";
if(document.cookie) XMemo = document.cookie;
else
document.cookie = "Time=" + document.lastModified;
alert(document.lastModified + " - " + XMemo);
</script>
</head>
<body>
</body>
</html>
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
DOM
Document Object Model (DOM)
JavaScript Object Model
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
DOM - Document Object Model (Preview)
Example: Web page with FORM-Object
<HTML> (Document) Object
<FORM> Object
<INPUT> Object
<INPUT> Object
<IMG> Object
<INPUT> Object
<INPUT> Object
<IMG> Object
<INPUT> Object
<INPUT> Object
<IMG> Object
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JavaScript Object Model
<H1> heading </H1>
<FORM>
<INPUT TYPE = "text" NAME = "name">
<INPUT TYPE = "submit">
</FORM>
<IMG SRC = "img.gif">
<P> more text
Internet Applications,  Helmut Dispert
Access through
JavaScript
Fachbereich Informatik und Elektrotechnik
DOM - Document Object Model (Preview)
<H1> heading </H1>
Access through
DOM
<FORM>
<INPUT TYPE = "text" NAME = "name">
<INPUT TYPE = "submit">
</FORM>
Access through
JavaScript / DOM
<IMG SRC = "img.gif">
<P> more text
Internet Applications,  Helmut Dispert
Access through
DOM
Fachbereich Informatik und Elektrotechnik
DHTML
Dynamic HTML (DHTML)
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
DHTML
Definition:
DHTML - Dynamic HTML
Combination of:
HTML
Cascading Stylesheets (CSS)
JavaScript
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Summary and Applications
Summary and Applications:
Problems with the WWW
(using HTML and JavaScript)
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Spoofing-Attacks
• Fortgeschrittene Technik der Fälschung von Daten auf
einem Netzwerk durch Vortäuschung einer falschen
Absenderadresse, oft mit der Absicht, durch die
gefälschte Absenderadresse authentifziert zu werden.
• Vorgehensweise:
Identifikation des Ziels,
Umgehung des Zielrechners, der ersetzt werden soll,
Vortäuschung der Adresse des angewählten Zielrechners,
Verbinden mit dem Ziel im Namen des ersetzen
Hostrechners,
Bestimmung der korrekten Sequenznummern, die vom Ziel
erwartet werden.
Internet Applications,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Web transaction during Web spoofing attack
WWW.attacker.com
1
4
request spoof URL
change
page
5
spoofed page
contents
2
3
request
real URL
real page
contents
Victim‘s browser
Dean, Felten, Wallach
Princeton University, 1996, 1997
Internet Applications,  Helmut Dispert
WWW.server.de