1
Introduction to Web Application
Introduction to Java Script
2
Topics• Review CSS
• Overview Java Script
• A simple Java Script in Web Page
• Syntax of Java Script
3
Review CSS
• What is CSS?
• Box model
• text flow
• id and class
• inline, embedded, and outsource CSS
• Develop CSS in Dreamweaver
• How to use CSS?
4
Overview of Java Script
5
Introduction to JavaScript
• JavaScript scripting language– Enhances functionality and appearance
– Client-side scripting• Makes pages more dynamic and interactive
– Foundation for complex server-side scripting
6
History of JavaScript
• Originally developed by Netscape, as LiveScript
• Became a joint venture of Netscape and Sun in 1995, renamed JavaScript
• Now standardized by the European Computer Manufacturers Association as ECMA-262 (also ISO 16262)
• Microsoft’s JScript
7
JavaScript vs. Java
• JavaScript and Java are only related through syntax– JavaScript is dynamically typed– JavaScript’s support for objects is very different
8
JavaScript and Object Orientation
• JavaScript is NOT an object-oriented programming language– Does not support class-based inheritance– Cannot support polymorphism– Has prototype-based inheritance, which is much
different
9
JavaScript and Object Orientation
• JavaScript Objects:– JavaScript objects have collections of
properties, which are like the members of classes in Java and C++
• Properties can be data properties or method properties
– All JavaScript objects are accessed through references
10
Write a Simple Java Script in Web Page
11
Ways to Add JavaScript to HTML
• Inline Style<html> <head> <title>A First Program in JavaScript</title> <script type = "text/javascript"> <!-- document.writeln( "<h1>Welcome to JavaScript Programming!</h1>" ); // --> </script> </head><body></body></html>
12
13
Ways to Add JavaScript to HTML
• Written in the <head> of a document• <script> tag
– Indicate that the text is part of a script– type attribute
• Specifies the type of file and the scripting language use
– writeln method• Write a line in the document
14
Ways to Add JavaScript to HTML
• Scripts are often hidden from browsers that do not include JavaScript interpreters by putting them in special comments <!--
-- JavaScript script –
//-->
15
Ways to Add JavaScript to HTML• Indirectly, as a file specified in the src attribute of
<script>, as in <script type=“text/javascript” language = "JavaScript" src = "myScript.js"> … </script>
<html><head><title>Use External Script</title><script type="text/javascript"
language="Javascript" src="scripts/alert.js"/>
</head><body></body></html>
16
Other Example of Java Script<html> <head> <title>Printing a Line with Multiple Statements</title> <script type = "text/javascript"> <!-- document.write( "<h1 style = \"color: magenta\">" ); document.write( "Welcome to JavaScript " + "Programming!</h1>" ); // --> </script> </head><body></body></html>
\” “\n new line\t horizontal table\r Carriage return\\ \\’ ‘
\” “\n new line\t horizontal table\r Carriage return\\ \\’ ‘
17
18
Other Example of Java Script
<html > <head><title>Printing Multiple Lines</title> <script type = "text/javascript"> <!-- document.writeln( "<h1>Welcome to<br />
JavaScript" + "<br />Programming!</h1>" ); // --> </script> </head><body></body></html>
19
20
Other Example of Java Script<html> <head><title>Printing Multiple Lines in a Dialog Box</title> <script type = "text/javascript"> <!-- window.alert( "Welcome to \n
JavaScript\n Programming!" );
// --> </script> </head> <body><p>Click Refresh (or Reload) to run this script again.</p>
</body></html>
21
22
Other Example of Java Script<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Using Prompt and Alert Boxes</title>
<script type = "text/javascript"> <!-- var name; // string entered by the user name = window.prompt( "Please enter your name",
"GalAnt" ); document.writeln( "<h1>Hello " + name + ", welcome to JavaScript programming!</h1>" ); // --> </script> </head> <body><p>Click Refresh (or Reload) to run this script again.</p> </body></html>
Different with JavaDifferent with Java
23
24
Other Example of Java Script<script type = "text/javascript"> <!-- var name; // string entered by the user
now = new Date(); hour = now.getHours(); name = window.prompt( "Please
enter your name", "GalAnt" );
if ( hour < 12 ) document.write( "<h1>Good Morning, " ); // determine whether the time is PM …
document.writeln( name + ", welcome to JavaScript programming!</h1>" ); // --> </script>
25
26
Summary of Example
• Write some simple tag in Page
• Alert
• Prompt
• Difference between Java and Java Script
27
Syntax of Java Script
• Identifiers and reserved words
• Comments
• Data types, literals and variables
• Operators and expressions
• Control statements
• Functions and screen output
• Object creation and modification
• Array
28
Identifiers and reserved words
• Identifier form: – Begin with a letter or underscore, followed
by any number of letters, underscores, and digits.
– No length limitation– Case sensitive– Can not be reserved words
• Example– _a, a, a1
29
Identifiers and reserved words
• In JavaScript, identifiers are used to: – name variables, – name functions, – provide labels for loops.
• 25 reserved words, plus future reserved words
30
Comments
• Two forms of comments: – // Rest of a line is considered a comment – /* … */ All lines in it are comments
• JavaScript statements usually do not need to be terminated by semicolons, but we’ll do it
31
Data Types
• In JavaScript, there are three primary data types (String, Number, Boolean) one composite data type (Object), and two special data types (Null, Undefined).
32
Data Types
• Number, String, and Boolean have wrapper objects (Number, String, and Boolean), the wrapper objects provide properties and methods for primitive values
• All objects are allocated on the heap; all primitive values are allocated elsewhere
33
Data Types
34
Data Types
• String Data Type:– A string value is a chain of zero or more
Unicode characters (letters, digits, and punctuation marks) strung together.
• Number Data Type:– In JavaScript, there is no distinction between
integer and floating-point values; a JavaScript number can be either (internally, JavaScript represent all numbers as floating-point values).
35
Data Types
• Boolean Data Type:– Whereas the string and number data types can
have a virtually unlimited number of different values, the Boolean data type can only have two. They are the literals “true” and “false”
• Null Data Type:– The null data type has only one value in
JavaScript: null. – The null keyword cannot be used as the name of
a function or variable.
36
Data Types
• Null Data Type:– You can erase the contents of a variable (without
deleting the variable) by assigning it the null value
• Undefined Data Type:– The undefined value is returned when you use:
• an object property that does not exist, • a variable that has been declared, but has never had a
value assigned to it.
37
Literals
• Numeric literals – Just like Java– All numeric values are stored in double-
precision floating point
• String literals– Delimited by either ' or “– Can include escape sequences (e.g., \t)– All String literals are primitive values
38
Literals
• Boolean values are true and false
• The only Null value is null
• The only Undefined value is undefined
39
Variables
• The first time a variable appears in your script is its declaration
• Variables can be either implicitly or explicitly declared, and explicit declarations are recommended. You do this using the var keyword.
• A variable that has been declared but not assigned a value has the value undefined
40
Operators
41
String Properties and Methods
• String catenation operator: +– Operands can be variables or string literals
• String properties & methods:– length e.g., var len = str1.length; (a property)– charAt(position) e.g., str.charAt(3)– indexOf(string) e.g., str.indexOf('B')– substring(from, to) e.g., str.substring(1, 3)– toLowerCase() e.g., str.toLowerCase()
42
String Properties and Methods• Conversion Functions
– parseInt(string) and parseFloat(string)• The string must begin with a digit or sign and
have a legal number; otherwise NaN is returned
• Not often needed, because of coercions
– toString()
43
Control Statements
• Similar to C, Java, and C++
• Compound statements are delimited by braces, but compound statements are not blocks (cannot declare local variables)
44
Control Statements
• Selection Statements:– If…else– Switch– ? :
45
Control Statements• Loop Statements:
– for– for…in…– while– do…while
<script type="text/javascript" language="Javascript">
var myArray = new Array("itemA","itemB","itemC");
for( key in myArray )
{
document.writeln("<br />");
document.writeln(myArray[key]);
}
</script>
46
Control Statements
• Others:– break– continue– return
47
Functions
• We place all function definitions in the head of the HTML document, and all calls in the body
function function_name([formal_parameters]) {
-- body –
}
48
Functions
• Variables explicitly declared in a function are local
• If a variable appears in a script that is defined both as a local variable and as a global variable, the local variable has precedence.
49
Functions
• Actual parameter vs. formal parameter
• Parameters are passed by value, but when a reference variable is passed, the semantics are pass-by-reference
• There is no clean way to send a primitive by reference
50
Functions
• All parameters are sent through a property array, arguments, which has the length property
• There is no type checking of parameters, nor is the number of parameters checked (excess actual parameters are ignored, excess formal parameters are set to undefined)
51
Functions
• Return value is the parameter of return– If there is no return, or if the end of the function
is reached, undefined is returned– If return has no parameter, undefined is
returned
52
Functions
• Functions are objects, so variables that reference them can be treated as other object references (can be passed as parameters, assigned to variables, and be elements of an array)– If fun is the name of a function:
ref_fun = fun; /* Now ref_fun is a reference to fun */ref_fun(); /* A call to fun */
53
Function
• Recursivefunction factorial(number){
if (number <= 1) //base case
return 1;
else
return number*factorial(number-1);
}
54
Screen Output
• The JavaScript model for the HTML document is the Document object
• The model for the browser display window is the Window object
• The Window object has two properties, document and window, which refer to the Document and Window objects, respectively
55
Screen Output
• The document object has methods write and writeln which dynamically create contents
56
Screen Output
• The Window object has three methods for creating dialog boxes, alert, confirm, and prompt– The default object is the current window, so the
object need not be included in the call to any of these three
57
Objects in JavaScript
• JavaScript objects are collections of properties and methods.– A property is a value or set of values (in the
form of an array or object) that is a member of an object
– A method is a function that is a member of an object
58
Objects in JavaScript
• JavaScript supports two kinds of objects – Intrinsic (or "built-in") objects, includes Array,
Boolean, Date, Math, etc.– User-define objects
59
Object Creation
• Objects can be created with a new expression– The most basic object is one that uses the
Object constructor, as in var myObject = new Object();
• The new object has no properties - a blank object
60
Constructors
• JavaScript constructors are special methods that create and initialize the properties for newly created objects
• When the constructor is called, this is a reference to the newly created object
61
<html><head><title>JavaScript object</title><script type="text/javascript" language="Javascript"><!--
function pasta(grain, width, shape, hasEgg){
this.grain = grain;this.width = width; this.shape = shape; this.hasEgg = hasEgg;
}var myobj = new pasta("wheat", 0.3, "oval", true);
//--></script></head><body>
<h1>This is H1 element</h1><p>Let's see the effective of javascript</p>
<script type="text/javascript" language="Javascript">
document.writeln("<h1>" + myobj.grain + "</h1>");
</script></body></html>
62
Constructors
function plane(newMake, newModel, newYear){
this.make = newMake;
this.model = newModel;
this.year = newYear;
}
myPlane = new plane("Cessna",
"Centurnian",
"1970");
63
Constructors
• Can also have method properties:function displayPlane() {
document.write("Make: ", this.make, "<br />");
document.write("Model: ", this.model, "<br />");
document.write("Year: ", this.year, "<br />");
}
Now add the following to the constructor:this.display = displayPlane;
64
Object Modification
• Properties can be added to any object, any time:var myAirplane = new Object();myAirplane.make = "Cessna "; myAirplane.model = "Centurian";
• The number of properties in a JavaScript object is dynamic
• Objects can be nested, so a property could be itself another object, created with new
65
Object Modification
• Properties can be accessed in two ways:– by dot notation
var property1 = myAirplane.model;– in array notation
var property1 = myAirplane["model"];
• If you try to access a property that does not exist, you get undefined
66
Object Modification
• Properties can be deleted with delete, as in delete myAirplane.model;
• Another Loop Statement– for (identifier in object) statement or compound
for (var prop in myAirplane) document.write(myAirplane[prop] +
"<br />");
67
Arrays
• Arrays in JavaScript are objects with some special functionality
• Array elements can be primitive values or references to other objects
• All array elements are allocated dynamically from the heap, JavaScript arrays have dynamic length
68
Arrays
• Array objects can be created in two ways: with new, or by assigning an array literal, which is a list of values enclosed in brackets:– var myList = new Array(24); – var myList2 = new Array(24, "bread", true);– var myList3 = [24, "bread", true];
69
Arrays• Length of array:
– The array length is dynamic and the length property stores the length
– The lowest index of every JavaScript array is zero
– The length of an array is the highest subscript to which an element has been assigned, plus 1
• myList[122] = "bitsy"; // length is 123
70
Arrays• Length of array:
– Because the length property is writeable, you can set it to make the array any length you like, as in
• myList.length = 150;
– This can also shorten the array (if the new length is less than the old length)
– Only assigned elements take space
71
Sort in Array p355
• A.sort (compareIntegers)
• function compareIntegers(value1, value2)
• {return parseInt(value1)-parseInt(value2)<=0;
• }
72
Multidimensional Arrays
• Two-dimensional arrays analogous to tables– Rows and columns
• Specify row first, then column
– Two subscripts
73
Multidimensional Arrays
a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Row 0
Row 1
Row 2
Column 0 Column 1 Column 2 Column 3
Row subscript (or index)
Array name
Column subscript (or index)
a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]
Fig. 11.12 Two-dimensional array with three rows and four columns.
74
Multidimensional Arrays
• Declaring and initializing multidimensional arrays– Group by row in square brackets– Treated as arrays of arrays– Creating array b with one row of two elements
and a second row of three elements:
var b = [ [ 1, 2 ], [ 3, 4, 5 ] ];
75
Multidimensional Arrays
• Also possible to use new operator– Create array b with two rows, first with five
columns and second with three:
var b;
b = new Array( 2 ); b[ 0 ] = new Array( 5 );b[ 1 ] = new Array( 3 );
76
Summary
• Java Script Examples
• Java Script Syntax
• Preview Chapter 13, 14, 15, 16