2. AboutJavaScript
JavaScript is notJava, or even related to Java
The original name for JavaScript was “LiveScript”
The name was changed when Java became popular
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
3. What is JavaScript?
• JavaScript is a programming language for use in HTML
pages
• Invented in 1995 at Netscape Corporation (LiveScript)
• JavaScript has nothing to do with Java
• JavaScript programs are run by an interpreter built into the
user's web browser (not on the server)
4. UsingJavaScript 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
5. Dealing with old browsers
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
6. 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 HTML form object, such as a button
This JavaScript will be executed when the form object is used
7. Where does JavaScript Fit In?
•
• Recall
1. client opens connection to server
2. client sends request to server
3. server sends response to client
4. client and server close connection
What about Step 5?
5. Client renders (displays) the response received from server
• Step 5 involves displaying HTML
• And running any JavaScript code within the HTML
8. What can JavaScript Do?
• JavaScript can dynamically modify an HTML page
• JavaScript can react to user input
• JavaScript can validate user input
• JavaScript can be used to create cookies (yum!)
• JavaScript is a full-featured programming language
• JavaScript user interaction does not require any
communication with the server
9. Pros and Cons of JavaScript
•
• Pros:
– Allows more dynamic HTML pages, even complete web
applications
Cons:
– Requires a JavaScript-enabled browser
– Requires a client who trusts the server enough to run the
code the server provides
• JavaScript has some protection in place but can
still cause security problems for clients
– Remember JavaScript was invented in 1995 and web-
browsers have changed a lot since then
10. Using JavaScript in your HTML
• JavaScript can be inserted into documents by
using the SCRIPT tag
<html>
<head>
<title>Hello World in JavaScript</title>
</head>
<body>
<script type="text/javascript">
document.write("Hello World!");
</script>
</body>
</html>
11. Where to Put your Scripts
• You can have any number of scripts
• Scripts can be placed in the HEAD or in the
BODY
– In the HEAD, scripts are run before the page is displayed
– In the BODY, scripts are run as the page is displayed
• In the HEAD is the right place to define functions
and variables that are used by scripts within the
BODY
12. Using JavaScript in your HTML
<html>
<head>
<title>Hello World in JavaScript</title>
<script type="text/javascript"> function
helloWorld() {
document.write("Hello World!");
}
</script>
</head>
<body>
<script type="text/javascript"> helloWorld();
</script>
</body>
</html>
13. External Scripts
• Scripts can also be loaded from an external file
• This is useful if you have a complicated script or
set of subroutines that are used in several
different documents
<script src="myscript.js"></script>
14. 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
15. 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
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
16. JavaScriptVariables
JavaScript has variables that you can declare with the
optional var keyword
Variables declared within a function are local to that
function
Variables declared outside of any function are global
variables
var myname = "Pat Morin";
17. 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)
18. JavaScriptOperators and Constructs
• JavaScript has most of the operators we're used to
from C/Java
– Arithmetic (+, - , *, /, %)
– Assignment (=, +=, -=, *= /=, %=, ++, --)
– Logical (&&, ||, !)
– Comparison (<, >, <=, >=, ==)
• Note: + also does string concatentation
• Constructs:
– if, else, while, for, switch, case
19. 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:
+ - * / % ++ --
Comparison operators:
< <= == != >= >
Logical operators:
&& || ! (&& and || are short-circuit operators)
Bitwise operators:
& | ^ ~ << >> >>>
Assignment operators:
+= -= *= /= %= <<= >>= >>>= &= ^= |=
20. 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
21. Simple User Interaction
• There are three built-in methods of doing simple
user interaction
– alert(msg) alerts the user that something has
happened
– confirm(msg) asks the user to confirm (or cancel)
something
– prompt(msg, default) asks the user to enter some
text
alert("There's a monster on the wing!");
confirm("Are you sure you want to do that?");
prompt("Enter you name", "Adam");
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. JavaScript Functions
• JavaScript lets you define functions using the
function keyword
• Functions can return values using the return
keyword
function showConfirm() {
confirm("Are you sure you want to do that?");
}
25. 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
26. 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
27. 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
28. JavaScriptArrays
• JavaScript has arrays that are indexed starting at 0
• Special version of for works with arrays
<script type="text/javascript"> var colors = new Array();
colors[0] = "red"; colors[1] = "green"; colors[2] =
"blue"; colors[3] = "orange"; colors[4] = "magenta";
colors[5] = "cyan"; for (var i in colors) {
document.write("<div style="background-color:"
+ colors[i] + ";">"
+ colors[i] + "</div>n");
}
</script>
29. 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
30. 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");
31. 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]
32. 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"]
33. 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
34. JavaScript Events
• JavaScript can be made to respond to user events
• Common Events:
– onload and onunload : when a page is first visited or left
– onfocus, onblur, onchange : events pertaining to form
elements
– onsubmit : when a form is submitted
– onmouseover, onmouseout : for "menu effects"
35. Exception Handling
• JavaScript also has try, catch, and throw
keywords for handling JavaScript errors
try {
runSomeCode();
} catch(err) {
var txt="There was an error on this page.nn"
+ "Error description: "
+ err.description + "nn" alert(txt)
}
36. 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
37. 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"
38. Comments in JavaScript
• Comments in JavaScript are delimited with // and /*
*/ as in Java and C++
39. JavaScriptObjects
• JavaScript is object-oriented and uses the same
method-calling syntax as Java
• We have already seen this with the document
object
document.write("Hello World!");
41. 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);
42. 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;
this.teacher = t;
}
– var course = new Course("CIT597", "Dr. Dave");
43. JavaScriptStrings
• A String object is created every time you use a string
literal (just like in Java)
• Have many of the same methods as in Java
– charAt, concat, indexOf, lastIndexOf, match, replace, search, slice,
split, substr, substring, toLowerCase, toUpperCase, valueOf
• There are also some HTML specific methods
– big, blink, bold, fixed, fontcolor, fontsize, italics, link, small, strike, sub,
sup
• Don't use the HTML methods (use CSS instead)
– This is the worst kind of visual formatting
44. JavaScript Dates
• The Date class makes working with dates easier
• A new date is initialized with the current date
• Dates can be compared and incremented
var myDate = new Date();
myDate.setFullYear(2007,2,14);
var today = new Date(); var nextWeek =
today + 7;
if (nextWeek > today) {
alert("You have less than one week left");
}
46. The JavaScript Math Class
• The Math class encapsulates many commonly- used
mathematical entities and formulas
• These are all class methods
– abs, acos, asin, atan, atan2, ceil, cos, exp, floor, log, max, min, pow,
random, round, sin, sqrt, tan
• These are all class methods
– E, LN2, LN10, LOG2E, LOG10E, PI, SQRT1_2, SQRT2
if (Math.cos(Math.PI) != 0) {
alert("Something is wrong with
Math.cos");
}
47. JavaScript and the DOM
• The Document Object Model (DOM) is a specification
that determines a mapping between programming
language objects and the elements of an HTML
document
• Not specific to JavaScript
49. HTML DOM: Document
•
• The Document object represents an HTML document and
can be used to access all documents in a page
A Document contains several collections
– anchors, forms, images, links
• Has several properties
– body, cookie, domain, lastModified, referrer, title, URL
• Has several useful methods
– getElementById, getElementsByName, getElementsByTagName, write,
writeln, open, close
50. HTML DOM: Document
• An instance of Document is already created for you,
called document
function changeF() {
var cText = document.getElementById("c"); var fText =
document.getElementById("f");
...
}
...
<input type="text" id="c" onchange="changeC()">C
<input type="text" id="f" onchange="changeF()">F
51. HTML DOM: Form Elements
• One of the most common uses of JavaScript is for form
validation
• Several HTML DOM classes encapsulate form elements
– Form, Button, Checkbox, Hidden, Password, Text, Radio, Reset, Submit,
Textarea
• Warning: Using JavaScript is not a substitute for validating
form data in CGI scripts
52. HTML DOM:Text
•
A text entry field (input type="text") is
encapsulated by aText object
Variables
– value, maxLength, id, size, name, tabindex, readOnly
Changing these variables has an immediate effect
on the displayed data
53. HTML DOM:The DocumentTree
• Accessing elements and changing their properties lets us
do simple things like form validation, data transfer etc
• HTML DOM lets us do much more
• We can create, delete, and modify parts of the HTML
document
• For this we need to understand the Document Tree
55. Navigating the DocumentTree
•
• With JavaScript we can navigate the document tree
• document.getElementById(), getElementsByName(), and
getElementsByTagName() return nodes in the document
tree
Information can be obtained from
– nodeName – The tag name
– nodeValue – The the text of a text node
– nodeType – The kind of node