Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 79

JavaScript

Language Fundamentals

Dec 18, 202


About JavaScript
 JavaScript is not Java, or even related to Java
 The original name for JavaScript was “LiveScript”
 The name was changed when Java became popular
 Now that Microsoft no longer likes Java, its name for their
JavaScript dialect is “Active Script”
 Statements in JavaScript resemble statements in Java,
because both languages borrowed heavily from the C
language
 JavaScript should be fairly easy for Java programmers to learn
 However, JavaScript is a complete, full-featured, complex language
 JavaScript is seldom used to write complete “programs”
 Instead, small bits of JavaScript are used to add functionality to
HTML pages
 JavaScript is often used in conjunction with HTML “forms”
 JavaScript is reasonably platform-independent
2
Using JavaScript in a browser
 JavaScript code is included within <script> tags:
 <script type="text/javascript">
document.write("<h1>Hello World!</h1>") ;
</script>
 Notes:
 The type attribute is to allow you to use other scripting languages
(but JavaScript is the default)
 This simple code does the same thing as just putting <h1>Hello
World!</h1> in the same place in the HTML document
 The semicolon at the end of the JavaScript statement is optional
 You need semicolons if you put two or more statements on the same
line
 It’s probably a good idea to keep using semicolons

3
JavaScript isn’t always available
 Some old browsers do not recognize script tags
 These browsers will ignore the script tags but will display the included
JavaScript
 To get old browsers to ignore the whole thing, use:
<script type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
 The <!-- introduces an HTML comment
 To get JavaScript to ignore the HTML close comment, -->, the // starts a
JavaScript comment, which extends to the end of the line
 Some users turn off JavaScript
 Use the <noscript>message</noscript> to display a message in place of
whatever the JavaScript would put there
4
Where to put JavaScript
 JavaScript can be put in the <head> or in the <body> of an
HTML document
 JavaScript functions should be defined in the <head>
 This ensures that the function is loaded before it is needed

 JavaScript in the <body> will be executed as the page loads


 JavaScript can be put in a separate .js file
 <script src="myJavaScriptFile.js"></script>
 Put this HTML wherever you would put the actual JavaScript code
 An external .js file lets you use the same JavaScript on multiple HTML
pages
 The external .js file cannot itself contain a <script> tag
 JavaScript can be put in an HTML form object, such as a button
 This JavaScript will be executed when the form object is used
5
Primitive data types
 JavaScript has three “primitive” types: number, string, and
boolean
 Everything else is an object
 Numbers are always stored as floating-point values
 Hexadecimal numbers begin with 0x
 Some platforms treat 0123 as octal, others treat it as decimal
 Since you can’t be sure, avoid octal altogether!
 Strings may be enclosed in single quotes or double quotes
 Strings can contains \n (newline), \" (double quote), etc.
 Booleans are either true or false

0, "0", empty strings, undefined, null, and NaN are false , other
values are true

6
Variables

 Variables are declared with a var statement:


 var pi = 3.1416, x, y, name = "Dr. Dave" ;
 Variables names must begin with a letter or underscore
 Variable names are case-sensitive
 Variables are untyped (they can hold values of any type)
 The word var is optional (but it’s good style to use it)
 Variables declared within a function are local to
that function (accessible only within that function)
 Variables declared outside a function are global
(accessible from anywhere on the page)
7
Operators, I
 Because most JavaScript syntax is borrowed from C (and is
therefore just like Java), we won’t spend much time on it
 Arithmetic operators (all numbers are floating-point):
+ - * / % ++ --
 Comparison operators:
< <= == != >= >
 Logical operators:
&& || ! (&& and || are short-circuit operators)
 Bitwise operators:
& | ^ ~ << >> >>>
 Assignment operators:
+= -= *= /= %= <<= >>= >>>= &= ^= |=

8
Operators, II
 String operator:
+
 The conditional operator:
condition ? value_if_true : value_if_false
 Special equality tests:
 == and != try to convert their operands to the same type
before performing the test
 === and !== consider their operands unequal if they are of
different types
 Additional operators (to be discussed):
new typeof void delete

9
Comments
 Comments are as in C or Java:
 Between // and the end of the line
 Between /* and */
 Java’s javadoc comments, /** ... */, are treated just the
same as /* ... */ comments; they have no special
meaning in JavaScript

10
Statements, I

 Most JavaScript statements are also borrowed from C


 Assignment: greeting = "Hello, " + name;
 Compound statement:
{ statement; ...; statement }
 If statements:
if (condition) statement;
if (condition) statement; else statement;
 Familiar loop statements:
while (condition) statement;
do statement while (condition);
for (initialization; condition; increment) statement;

11
Statements, II
 The switch statement:
switch (expression) {
case label :
statement;
break;
case label :
statement;
break;
...
default : statement;
}
 Other familiar statements:
 break;
 continue;
 The empty statement, as in ;; or { }

12
JavaScript is not Java
 By now you should have realized that you already know a
great deal of JavaScript
 So far we have talked about things that are the same as in Java
 JavaScript has some features that resemble features in Java:
 JavaScript has Objects and primitive data types
 JavaScript has qualified names; for example,
document.write("Hello World");
 JavaScript has Events and event handlers
 Exception handling in JavaScript is almost the same as in Java
 JavaScript has some features unlike anything in Java:
 Variable names are untyped: the type of a variable depends on the
value it is currently holding
 Objects and arrays are defined in quite a different way
 JavaScript has with statements and a new kind of for statement

13
Exception handling, I
 Exception handling in JavaScript is almost the same as in Java
 throw expression creates and throws an exception
 The expression is the value of the exception, and can be of any type
(often, it's a literal String)
 try {
statements to try
} catch (e) { // Notice: no type declaration for e
exception handling statements
} finally { // optional, as usual
code that is always executed
}
 With this form, there is only one catch clause

14
Exception handling, II
 try {
statements to try
} catch (e if test1) {
exception handling for the case that test1 is true
} catch (e if test2) {
exception handling for when test1 is false and test2 is true
} catch (e) {
exception handling for when both test1and test2 are false
} finally { // optional, as usual
code that is always executed
}
 Typically, the test would be something like
e == "InvalidNameException"

15
Object literals
 You don’t declare the types of variables in JavaScript
 JavaScript has object literals, written with this syntax:
 { name1 : value1 , ... , nameN : valueN }

 Example (from Netscape’s documentation):


 car = {myCar: "Saturn", 7: "Mazda",
getCar: CarTypes("Honda"), special: Sales}
 The fields are myCar, getCar, 7 (this is a legal field name) , and

special
 "Saturn" and "Mazda" are Strings

 CarTypes is a function call

 Sales is a variable you defined earlier

 Example use: document.write("I own a " + car.myCar);

16
Three ways to create an object
 You can use an object literal:
 var course = { number: "CIT597", teacher: "Dr. Dave" }
 You can use new to create a “blank” object, and add fields to it
later:
 var course = new Object();
course.number = "CIT597";
course.teacher = "Dr. Dave";
 You can write and use a constructor:
 function Course(n, t) { // best placed in <head>
this.number = n; // keyword "this" is required, not optional
this.teacher = t;
}
 var course = new Course("CIT597", "Dr. Dave");

17
Array literals
 You don’t declare the types of variables in JavaScript
 JavaScript has array literals, written with brackets and
commas
 Example: color = ["red", "yellow", "green", "blue"];
 Arrays are zero-based: color[0] is "red"
 If you put two commas in a row, the array has an
“empty” element in that location
 Example: color = ["red", , , "green", "blue"];
 color has 5 elements
 However, a single comma at the end is ignored
 Example: color = ["red", , , "green", "blue”,]; still has 5 elements

18
Four ways to create an array
 You can use an array literal:
var colors = ["red", "green", "blue"];
 You can use new Array() to create an empty array:
 var colors = new Array();
 You can add elements to the array later:
colors[0] = "red"; colors[2] = "blue"; colors[1]="green";
 You can use new Array(n) with a single numeric
argument to create an array of that size
 var colors = new Array(3);
 You can use new Array(…) with two or more arguments
to create an array containing those values:
 var colors = new Array("red","green", "blue");

19
The length of an array

 If myArray is an array, its length is given by


myArray.length
 Array length can be changed by assignment beyond the
current length
 Example: var myArray = new Array(5); myArray[10] = 3;

 Arrays are sparse, that is, space is only allocated for


elements that have been assigned a value
 Example: myArray[50000] = 3; is perfectly OK
 But indices must be between 0 and 232-1
 As in C and Java, there are no two-dimensional arrays; but
you can have an array of arrays: myArray[5][3]

20
Arrays and objects
 Arrays are objects
 car = { myCar: "Saturn", 7: "Mazda" }
 car[7] is the same as car.7
 car.myCar is the same as car["myCar"]
 If you know the name of a property, you can use dot
notation: car.myCar
 If you don’t know the name of a property, but you have
it in a variable (or can compute it), you must use array
notation: car["my" + "Car"]

21
Array functions
 If myArray is an array,
 myArray.sort() sorts the array alphabetically
 myArray.sort(function(a, b) { return a - b; }) sorts
numerically
 myArray.reverse() reverses the array elements
 myArray.push(…) adds any number of new elements to the
end of the array, and increases the array’s length
 myArray.pop() removes and returns the last element of the
array, and decrements the array’s length
 myArray.toString() returns a string containing the values of
the array elements, separated by commas

22
The for…in statement
 You can loop through all the properties of an object with
for (variable in object) statement;
 Example: for (var prop in course) {
document.write(prop + ": " + course[prop]);
}
 Possible output: teacher: Dr. Dave
number: CIT597
 The properties are accessed in an undefined order
 If you add or delete properties of the object within the loop, it is
undefined whether the loop will visit those properties
 Arrays are objects; applied to an array, for…in will visit the
“properties” 0, 1, 2, …
 Notice that course["teacher"] is equivalent to course.teacher
 You must use brackets if the property name is in a variable

23
The with statement
 with (object) statement ; uses the object as the default
prefix for variables in the statement
 For example, the following are equivalent:
 with (document.myForm) {
result.value = compute(myInput.value) ;
}
 document.myForm.result.value =
compute(document.myForm.myInput.value);
 One of my books hints at mysterious problems resulting
from the use of with, and recommends against ever
using it

24
Functions
 Functions should be defined in the <head> of an
HTML page, to ensure that they are loaded first
 The syntax for defining a function is:
function name(arg1, …, argN) { statements }
 The function may contain return value; statements
 Any variables declared within the function are local to it
 The syntax for calling a function is just
name(arg1, …, argN)
 Simple parameters are passed by value, objects are
passed by reference

25
Regular expressions
 A regular expression can be written in either of two ways:
 Within slashes, such as re = /ab+c/
 With a constructor, such as re = new RegExp("ab+c")
 Regular expressions are almost the same as in Perl or Java (only
a few unusual features are missing)
 string.match(regexp) searches string for an occurrence of
regexp
 It returns null if nothing is found
 If regexp has the g (global search) flag set, match returns an array of
matched substrings
 If g is not set, match returns an array whose 0th element is the matched
text, extra elements are the parenthesized subexpressions, and the index
property is the start position of the matched substring

26
Warnings
 JavaScript is a big, complex language
 We’ve only scratched the surface
 It’s easy to get started in JavaScript, but if you need to use it
heavily, plan to invest time in learning it well
 Write and test your programs a little bit at a time
 JavaScript is not totally platform independent
 Expect different browsers to behave differently
 Write and test your programs a little bit at a time
 Browsers aren’t designed to report errors
 Don’t expect to get any helpful error messages
 Write and test your programs a little bit at a time

27
Evaluation (i.e., Dave’s opinion)
 JavaScript, like Java, is in the C family of languages
 JavaScript has lots of convenience features
 Global variables
 Not having to declare variables at all
 Untyped variables
 Easy modification of objects
 JavaScript is designed for programming in the small, not for
large programs
 Many features, such as global variables, are bad news for large programs
 My experience is that JavaScript is very nice if you use it for the
purposes that its designers expected, but very ugly if you try to
use it in non-routine ways

28
The End

29
More JavaScript

Dec 18, 202


Browser support
 JavaScript works on almost all browsers
 Internet Explorer uses JScript (referred to in menus as
“Active Scripting”), which is Microsoft’s dialect of
JavaScript
 Older browsers don’t support some of the newer
features of JavaScript
 We will assume modern browser support
 Enabling and disabling JavaScript:
 See http://www.valleyvet.com/si_javascript_help.html

31
What you can’t do
 To protect the visitor to your web pages, you can’t:
 Read or write user files
 However, JScript on IE allows ASP scripting, which is how the very
destructive JS.Gigger.A@mm worm spreads
 To turn off active scripting in Outlook Express, see
http://support.microsoft.com/support/kb/articles/Q192/8/46.ASP
 Execute any other programs
 Connect to any other computer, except to download another
HTML page or to send e-mail
 Determine what other sites the user has visited
 Open a very small (less than 100px by 100px) window or an
offscreen window (except in IE)

32
Debugging
 Mozilla/Netscape has much better debugging tools than IE
 Mozilla
 Select Tools => Web Development => JavaScript console
 Netscape 6:
 Select Tasks => Tools => JavaScript console
 Netscape 4:
 Select Communicator => Tools => JavaScript console
 Any Mozilla or Netscape:
 Type javascript: in the location bar and press Enter
 Internet Explorer:
 Go to the Preferences... dialog and look for something like Web
content => Show scripting error alerts
 After debugging, test your program in IE
 IE is the most popular browser

33
Numbers
 In JavaScript, all numbers are floating point
 Special predefined numbers:
 Infinity, Number.POSITIVE_INFINITY -- the result of dividing a positive
number by zero
 Number.NEGATIVE_INFINITY -- the result of dividing a negative number
by zero
 NaN, Number.NaN (Not a Number) -- the result of dividing 0/0
 NaN is unequal to everything, even itself
 There is a global isNaN() function
 Number.MAX_VALUE -- the largest representable number
 Number.MIN_VALUE -- the smallest (closest to zero) representable
number

34
Strings and characters
 In JavaScript, string is a primitive type
 Strings are surrounded by either single quotes or double quotes
 There is no “character” type
 Special characters are:

\0 NUL \v vertical tab


\b backspace \' single quote
\f form feed \" double quote
\n newline \\ backslash
\r carriage return \xDD Unicode hex DD
\t horizontal tab \xDDDD Unicode hex DDDD

35
Some string methods
 charAt(n)
 Returns the nth character of a string
 concat(string1, ..., stringN)
 Concatenates the string arguments to the recipient string
 indexOf(substring)
 Returns the position of the first character of substring in the recipient
string, or -1 if not found
 indexOf(substring, start)
 Returns the position of the first character of substring in the given string
that begins at or after position start, or -1 if not found
 lastIndexOf(substring), lastIndexOf(substring, start)
 Like indexOf, but searching starts from the end of the recipient string

36
More string methods
 match(regexp)
 Returns an array containing the results, or null if no match is found

 On a successful match:

 If g (global) is set, the array contains the matched substrings


 If g is not set:
Array location 0 contains the matched text
 Locations 1... contain text matched by parenthesized

groups
 The array index property gives the first matched position

 replace(regexp, replacement)
 Returns a new string that has the matched substring replaced with

the replacement
 search(regexp)
 Returns the position of the first matched substring in the given

string, or -1 if not found.


37
boolean
 The boolean values are true and false
 When converted to a boolean, the following values are
also false:
 0
 "0" and '0'
 The empty string, '' or ""
 undefined
 null
 NaN

38
undefined and null
 There are special values undefined and null
 undefined is the only value of its “type”
 This is the value of a variable that has been declared but not
defined, or an object property that does not exist
 void is an operator that, applied to any value, returns the
value undefined
 null is an “object” with no properties
 null and undefined are == but not ===

39
Arrays
 As in C and Java, there are no “true”
multidimensional arrays
 However, an array can contain arrays
 The syntax for array reference is as in C and Java
 Example:
var a = [ ["red", 255], ["green", 128] ];
var b = a[1][0]; // b is now "green"
var c = a[1]; // c is now ["green", 128]
var d = c[1]; // d is now 128

40
Determining types
 The unary operator typeof returns one of the following
strings: "number", "string", "boolean", "object",
"undefined", and "function"
 typeof null is "object"
 If myArray is an array, typeof myArray is "object"
 To distinguish between different types of objects,
 myObject instanceof Constructor
 The Constructor should be an object that is a constructor function
 It is an error if the right-hand side is not an object at all
 myObject.constructor == Constructor
 myObject.toString() == "ConstructorName"

41
Wrappers and conversions
 JavaScript has “wrapper” objects for when a primitive value must
be treated as an object
 var s = new String("Hello"); // s is now a String
 var n = new Number(5); // n is now a Number
 var b = new Boolean(true); // b is now a Boolean
 Because JavaScript does automatic conversions as needed, wrapper
objects are hardly ever needed
 JavaScript has no “casts,” but conversions can be forced
 var s = x + ""; // s is now a string
 var n = x + 0; // n is now a number
 var b = !!x; // b is now a boolean
 Because JavaScript does automatic conversions as needed, explicit
conversions are hardly ever needed

42
Variables
 Every variable is a property of an object
 When JavaScript starts, it creates a global object
 In client-side JavaScript, the window is the global
object
 It can be referred to as window or as this
 The “built-in” variables and methods are defined here
 There can be more than one “global” object
 For example, one frame can refer to another frame with
code such as parent.frames[1]
 Local variables in a function are properties of a
special call object
43
HTML names in JavaScript
 In HTML the window is the global object
 It is assumed that all variables are properties of this
object, or of some object descended from this object
 The most important window property is document
 HTML form elements can be referred to by
document.forms[formNumber].elements[elementNumber]
 Every HTML form element has a name attribute
 The name can be used in place of the array reference
 Hence, if
 <form name="myForm">
<input type="button" name="myButton" ...>
 Then instead of document.forms[0].elements[0]
 you can say document.myForm.myButton
44
More about with
 with (object) statement ; uses the object as the default
prefix for variables in the statement
 As noted in an earlier lecture, one book hints at
mysterious problems resulting from the use of with,
and recommends against ever using it
 It turns out that there are two problems:
 with is difficult to optimize, hence may be inefficient
 More importantly, variable declarations and function
definitions have odd and counterintuitive behavior
 The problem appears to be determining if the prefix is used
 Other types of statements are fine

45
Functions
 In Java, methods are associated with objects
 In JavaScript, a function is an object
 Functions can be recursive:
 function factorial(n) {
if (n <= 1) return 1;
else return n * factorial(n - 1);
}
 Functions can be nested:
 function hypotenuse(a, b) {
function square(x) { return x * x; }
return Math.sqrt(square(a) + square(b));
}

46
The Function() constructor
 Since functions are objects, they have a constructor:
 Function(arg1, arg2, ..., argN, body)
 All the arguments to the constructor are strings
 Example:
var f = new Function("x", "y", "return x * y;");
 Notice that the function has no name
 But you can assign it to a variable and use that name
 The name can be used to call the function as usual
 You can construct functions dynamically in JavaScript
(they are automatically compiled)
 However, compilation is computationally expensive
 Functions defined in this way are always global

47
Function literals
 As we just saw, a function can be defined by means of a
constructor:
 var f = new Function("x", "y", "return x * y;");
 A function can be written literally, as in the following
example:
 var f = function(x, y) { return x * y; }
 This function is not necessarily global
 To write a recursive literal function, give it a name:
 var f = function fact(n) { if (n <= 1) return n;
else return n * fact(n - 1) ; };
 The name does not persist after the function is created

48
Function names
 The “name” of a function is just the variable that holds
the function
 var square = function(x) { return x * x; };
 var a = square(4); // a now holds 16
 var b = square; // b now holds square
 var c = b(5); // c now holds 25
 var d = [ b ]; // d is an array
 var e = d[0](6); // e now holds 36

49
The call object
 When a function is called, a new call object
is created
 The properties of the call object include:
 The function parameters
 Local variables declared with the var statement
 The arguments object

50
arguments
 The arguments object is like an array
 arguments[n] is a synonym for the nth argument
 arguments.length is the number of arguments
that the function was called with
 function.length is the number of arguments it was
defined with
 arguments.length, unlike function.length, is
available only within the function
 arguments.callee is the function itself

51
Example uses of arguments
 function max() {
var m = Number.NEGATIVE_INFINITY;
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] > m) m = arguments[i];
}
return m;
}
 function(n) {
if (n <= 1) return 1;
return n * arguments.callee(n - 1);
}

52
Methods
 When a function is a property of an object, we call it a
“method”
 A method can be invoked by either of
call(object, arg1, ..., argN) or
apply(object, [arg1, ..., argN])
 call and apply are defined for all functions
 call takes any number of arguments
 apply takes an array of arguments
 Both allow you to invoke a function as if it were a method of
some other object, object
 Inside the function, the keyword this refers to the object

53
Properties of functions
 Since a function is an object, you can add properties
to it
 Function properties are often a good alternative to global
variables
 Example:
uniqueInteger.counter = 0;
function uniqueInteger() {
return uniqueInteger.counter++;
}
 Function properties are a bit like static variables in Java

54
The End

55
JavaScript and HTML

Simple Event Handling


JavaScript and DOM
 JavaScript relies on a Document Object Model (DOM)
that describes the structure of the web page
 This is not the same as the XML DOM
 You can do a lot with a just a little understanding of the
DOM
 You use the DOM to access elements on the web page
 You can capture events without knowing the DOM at all
 You need the DOM to make any changes to the web page

57
Events
 Some (but not all) elements on the web page respond to
user interactivity (keystrokes, mouse clicks) by creating
events
 Different kinds of elements produce different events
 Browsers are not all alike in what events are produced
 We will concentrate on events from HTML form elements
and commonly recognized events
 You can put handlers on HTML form elements
 If the event isn’t generated, the handler does nothing
 A handler should be very short
 Most handlers call a function to do their work

58
A simple event handler
 <form method="post" action="">
<input type="button"
name="myButton"
value="Click me"
onclick="alert('You clicked the button!');">
</form>
 The button is enclosed in a form

 The tag is input type="button"

 The name can be used by other JavaScript code

 The value is what appears on the button

 onclick is the name of the event being handled

 The value of the onclick element is the JavaScript code to execute


 alert pops up an alert box with the given text

59
Capitalization
 JavaScript is case sensitive
 HTML is not case sensitive
 onclick="alert('You clicked the button!');"
 The underlined parts are HTML
 The quoted string is JavaScript
 You will frequently see onclick capitalized as onClick
 The Java naming convention is easier to read
 This is fine in HTML, but an error if it occurs in JavaScript

 Also note: Since we have a quoted string inside


another quoted string, we need both single and
double quotes
60
Common events
 Most HTML elements produce the following events:
 onClick -- the form element is clicked
 onDblClick -- the form element is clicked twice in close succession
 onMouseDown -- the mouse button is pressed while over the form
element
 onMouseOver -- the mouse is moved over the form element
 onMouseOut -- the mouse is moved away from the form element
 onMouseUp -- the mouse button is released while over the form element
 onMouseMove -- the mouse is moved
 In JavaScript, these should be spelled in all lowercase

61
Example: Simple rollover
 The following code will make the text Hello
red when the mouse moves over it, and
blue when the mouse moves away
<h1 onMouseOver="style.color='red';"
onMouseOut="style.color='blue';">Hello </h1>
 Image rollovers are just as easy:
<img src="../Images/duke.gif"
width="55" height="68"
onMouseOver="src='../Images/duke_wave.gif';"
onMouseOut="src='../Images/duke.gif';">

62
Events and event handlers I
 The following tables are taken from:
http://developer.netscape.com/docs/manuals/js/client/
jsguide/index.htm

Event Applies to Occurs when Handler


Load Document body User loads the page onLoad
in a browser
Unload Document body User exits the page onUnload
Error Images, window Error on loading an onError
image or a window
Abort Images User aborts the onAbort
loading of an image
63
Events and event handlers II
Event Applies to Occurs when Handler
KeyDown Documents, images, User depresses onKeyDown
links, text areas a key

KeyUp Documents, images, User releases a onKeyUp


links, text areas key

KeyPress Documents, images, User presses onKeyPress


links, text areas or holds down
a key
Change Text fields, text User changes onChange
areas, select lists the value of an
element
64
Events and event handlers III

Event Applies to Occurs when Handler


MouseDown Documents, User onMouseDown
buttons, links depresses a
mouse button
MouseUp Documents, User releases onMouseUp
buttons, links a mouse
button
Click Buttons, radio User clicks a onClick
buttons, form element
checkboxes, or link
submit buttons,
reset buttons, links
65
Events and event handlers IV

Event Applies to Occurs when Handler


MouseOver Links User moves onMouseOver
cursor over a
link
MouseOut Areas, links User moves onMouseOut
cursor out of an
image map or
link
Select Text fields, text User selects onSelect
areas form element’s
input field

66
Events and event handlers V

Event Applies to Occurs when Handler


Move Windows User or script onMove
moves a window

Resize Windows User or script onResize


resizes a window
DragDrop Windows User drops an onDragDrop
object onto the
browser window

67
Events and event handlers VI

Event Applies to Occurs when Handler


Focus Windows and all User gives onFocus
form elements element input
focus
Blur Windows and all User moves onBlur
form elements focus to some
other element
Reset Forms User clicks a onReset
Reset button

Submit Forms User clicks a onSubmit


Submit button
68
Back to the DOM
 You can attach event handlers to HTML elements with very little
knowledge of the DOM
 However, to change what is displayed on the page requires
knowledge of how to refer to the various elements
 The basic DOM is a W3C standard and is consistent across
various browsers
 More complex features are browser-dependent
 The highest level element (for the current page) is window, and
everything else descends from that
 Every JavaScript variable is a field of some object
 In the DOM, all variables are assumed to start with “window.”
 All other elements can be reached by working down from there

69
The DOM
hierarchy

Source:
http://sislands.com/coin70/week1/dom.htm
70
Fields of window, I
 window
 The current window (not usually needed).
 self
 Same as window.
 parent
 If in a frame, the immediately enclosing window.
 top
 If in a frame, the outermost enclosing window.
 frames[ ]
 An array of frames (if any) within the current window. Frames are
themselves windows.
 length
 The number of frames contained in this window.

71
Fields of window, II
 document
 The HTML document being displayed in this window.
 location
 The URL of the document being displayed in this window. If you set this
property to a new URL, that URL will be loaded into this window. Calling
location.reload() will refresh the window.
 navigator
 A reference to the Navigator (browser) object. Some properties of
Navigator are:
 appName -- the name of the browser, such as "Netscape"
 platform -- the computer running the browser, such as "Win32"
 status
 A read/write string displayed in the status area of the browser window.
Can be changed with a simple assignment statement.

72
Methods of window, I
 alert(string)
 Displays an alert dialog box containing the string and an OK
button.
 confirm(string)
 Displays a confirmation box containing the string along with
Cancel and OK buttons. Returns true if OK is pressed, false if
Cancel is pressed.
 prompt(string)
 Displays a confirmation box containing the string, a text field,
and Cancel and OK buttons. Returns the string entered by the
user if OK is pressed, null if Cancel is pressed.

73
Methods of window, II
 open(URL)
 Opens a new window containing the document specified by
the URL.
 close()
 Closes the given window (which should be a top-level
window, not a frame).

74
Fields of document, I
 You must prefix these fields with document.
 anchors[ ]
 An array of Anchor objects (objects representing
<a name=...> tags)
 applets[ ]
 An array of Applet objects
 The properties are the public fields defined in the applet
 The methods are the public methods of the applet
 Cautions:
 You must supply values of the correct types for the fields

and method parameters


 Changes and method calls are done in a separate Thread

75
Fields of document, II
 forms[ ]

An array of Form elements
 If the document contains only one form, it is forms[0]
 images[ ]
 An array of Image objects
 To change the image, assign a new URL to the src property
 links[ ]
 An array of Link objects
 A link has several properties, including href, which holds the
complete URL

76
Fields of document, III
 bgColor
 The background color of the document
 May be changed at any time

 title
 A read-only string containing the title of the document

 URL
 A read-only string containing the URL of the document

77
Fields of the form object
 elements[ ]
 An array of form elements

78
The End

79

You might also like