Document

advertisement
Introduction to Client-Side
Web Development
Introduction to Client-Side programming
using JavaScript
DOM and JavaScript; basic syntax and concepts
3th February 2005
Bogdan L. Vrusias
b.vrusias@surrey.ac.uk
Introduction to Client-Side
Web Development
Contents
•
•
•
•
Understanding the DOM
Introduction to JavaScript
JavaScript syntax
JavaScript objects
3th February 2005
Bogdan L. Vrusias © 2005
2
Introduction to Client-Side
Web Development
DOM Basics: The Object Model I
• An Object Model comprises of objects connected in a
hierarchical structure.
• The top-most object is called the root of the object model,
and all the other objects stem from it.
• Objects have properties and methods. Properties define the
attributes of the object, and methods describe the actions
that the object has.
• The object model provides mechanisms where the user can
navigate, request or define properties, and execute
methods.
3th February 2005
Bogdan L. Vrusias © 2005
3
Introduction to Client-Side
Web Development
DOM Basics: The Object Model II
• To navigate to an object in the model you use the dot (.)
syntax.
window.location.href = "http://www.google.com"
• Objects are some times single, but they can also form a
collection of objects.
window.document.forms[0].elements[3]
• The object model can be represented with a tree structure.
Each object is a node of the tree, and it has a parent node,
children nodes, and siblings.
3th February 2005
Bogdan L. Vrusias © 2005
4
Introduction to Client-Side
Web Development
DOM Basics: Browser Object Model
• The Browser Object Model describes the object model that a browser
provides the user:
window
document
history
location
navigator
Document object: represents the HTML document including the elements and
attributes.
History object: represents the browser's history object that contain
information about previously navigated pages.
Location object: defines the location of the page loaded in the browser's
window.
Navigator object: provides information about the browser itself.
3th February 2005
Bogdan L. Vrusias © 2005
5
Introduction to Client-Side
Web Development
DOM Basics: The Document Object Model
• The Document Object Model (DOM) is a platform and language
neutral model that allows access to its content.
• Through the DOM you can access any of the elements and attributes of
an HTML document.
• DOM Level 1 (defined by W3C) is compatible with most of the
browsers (especially Netscape is fully compatible).
• DOM Level 2, 3 also supports StyleSheet objects.
document
anchors
applets
body
forms
images
links
elements
3th February 2005
Bogdan L. Vrusias © 2005
6
Introduction to Client-Side
Web Development
DOM Basics: The Document Object Model
• There are three ways to locate and work with elements in an HTML
document using DOM:
– DOM as Objects
– DOM as Nodes
– DOM using an ID
3th February 2005
Bogdan L. Vrusias © 2005
7
Introduction to Client-Side
Web Development
DOM Basics: DOM as Objects
• To locate an element object within a collection, you define its position
in the document by referring to its index value (limited to collection of
elements only).
document.forms[0].elements[0]
• This method can be very handy when accessing a collection of similar
elements.
document.images[0].src = "image.jpg"
NOTE: Inserting an element in the document may cause reference
problems, as the elements are depended on their position on the
document.
3th February 2005
Bogdan L. Vrusias © 2005
8
Introduction to Client-Side
Web Development
DOM Basics: DOM as Nodes I
• DOM as Nodes: where you can access any element within the tree
structure of the document. You can get, change, or add nodes to the
document object model.
document.childNodes[0].childNodes[0]
• The content of an element is called text node and can be accessed by:
document.childNodes[0].text = "text"
• You can navigate to find any type of attributes in the same way we
accessed the text node. For example to change the source of an image
you would do:
document.childNodes[0].childNodes[0].src = "img.jpg"
3th February 2005
Bogdan L. Vrusias © 2005
9
Introduction to Client-Side
Web Development
DOM Basics: DOM as Nodes II
• Node walking is not a recommended approach.
• But… the best thing about the DOM and nodes is that you can add and
remove nodes.
• E.g.:
new_element = document.createElement("div")
document.childNodes[1].appendChild(new_element)
new_text_node = document.createTextNode("text")
document.childNodes[1].
lastChild.appendChild(new_text_node)
3th February 2005
Bogdan L. Vrusias © 2005
10
Introduction to Client-Side
Web Development
DOM Basics: DOM using an ID
• DOM using an ID: you can reference a specific element.
document.getElementById("email")
• Locating elements in a document through the id of the element is
preferred, rather than using the object collections or node walking.
• You can access all attributes of a specific element:
document.getElementById("img_01").setAttribute("src"
, "img_02.jpg")
NOTE: What you have to be aware of is that every element you want to
locate through the DOM has to have a unique id.
3th February 2005
Bogdan L. Vrusias © 2005
11
Introduction to Client-Side
Web Development
History: JavaScript
• JavaScript was developed by Netscape and was then
known as LiveScript.
• JavaScript was supported only by Netscape initially, and as
Netscape would only licence technology to Microsoft,
Microsoft implemented JScript to run on Internet Explorer.
• The European Computer Manufacturers Association
(ECMA) turned the variations of JavaScript and JScript
into an international standard script language called
ECMAScript.
• So the term "JavaScript" represents both Netscape and
Microsoft implementation of ECMAScript.
3th February 2005
Bogdan L. Vrusias © 2005
12
Introduction to Client-Side
Web Development
JavaScript: Introduction I
• With HTML only, there is no way you could perform any
kind of dynamic operation over the information within the
document.
• Once the pure HTML document is displayed on the
browser the page is static.
• What makes a page dynamic is the scripting language.
• The scripting language allows the creation of dynamic
HTML (DHTML) pages, where the user can, for example,
perform calculations, change the user interface, or generate
dynamic content, all that within the same page.
3th February 2005
Bogdan L. Vrusias © 2005
13
Introduction to Client-Side
Web Development
JavaScript: Introduction II
• The most popular client-side scripting language is
JavaScript.
• JavaScript adds logic and reactivity to the HTML
document.
• JavaScript is not an independent language that could create
stand alone applications. It can only run within another
application (the browser).
NOTE: JavaScript is NOT Java!
3th February 2005
Bogdan L. Vrusias © 2005
14
Introduction to Client-Side
Web Development
JavaScript: Basic Syntax I
• With JavaScript the developer can:
– Define variables
var x = 1;
– Create objects
var newElement = document.createElement("div");
– Create and call functions
function add(x, y) {
return x+y;
}
…
sum = add(2, 3);
3th February 2005
Bogdan L. Vrusias © 2005
15
Introduction to Client-Side
Web Development
JavaScript: Basic Syntax II
– Respond to events
<img src="img.jpg" id="img1" nmouseover=“doit();"/>
– Perform basic operations
x = x + 5;
– Use basic control statements
if (x>y) { y=x; } else { x=y; }
– Comment the source code
x += 4 // this is a comment
/* using this type of comments you can go over many
lines of code */
3th February 2005
Bogdan L. Vrusias © 2005
16
Introduction to Client-Side
Web Development
JavaScript: Basic Syntax III
• JavaScript is case sensitive (optional for some browsers)
• Variables should be defined (optional… but recommended)
• Each statement ends with a semicolon (optional for some
browsers)
NOTE: Commenting the source code is very helpful, but
remember that the user can see the source code, so you
may not want to give too many details about something!!!
3th February 2005
Bogdan L. Vrusias © 2005
17
Introduction to Client-Side
Web Development
JavaScript: Functions
• Using functions the developer structures the code and
makes it more efficient.
• Function is a logical set of statements that perform a
specific task.
• Function syntax:
function add(x, y) {
var sum;
sum = x + y;
return sum;
}
• The code within a function is only executed when the
function is called. To call a function you type:
s = add(3, 8);
3th February 2005
Bogdan L. Vrusias © 2005
18
Introduction to Client-Side
Web Development
JavaScript: Events
• Events are generated from the elements within the HTML
document.
• Events are caused by the user when an action is performed.
Then the browser flags an event associated with the
performed action.
• An event handler executes the associated action for the
respective event.
<img src="close.jpg" id="close"
onclick="closeWindow();" />
or
<img src="close.jpg" id="close"
onclick="window.close();" />
• Each element has a specific set of event handlers.
3th February 2005
Bogdan L. Vrusias © 2005
19
Introduction to Client-Side
Web Development
JavaScript: How it works
• JavaScript is inserted in the HTML document and it can be
executed on the client only.
• If a task can be performed at the client side, that will
reduce the performance load of the server, and as a result it
will be faster and more efficient for the user.
• JavaScript is an interpreted language, the code is not
compiled, therefore each line of code is processed as the
the script is executed.
• You can either execute the JavaScript code before the
HTML page is displayed or after.
3th February 2005
Bogdan L. Vrusias © 2005
20
Introduction to Client-Side
Web Development
JavaScript: How it works
• Because the JavaScript is executed as the page is parsed by the
browser (from top to bottom), there is a possibility that some errors
may occur:
– If you refer to a function that has not yet been processed by the browser
you will get an error.
– Once the document is fully displayed there is no way you can add
dynamic text to the document (e.g. by document.write(“abc");)
• For security reasons JavaScript cannot perform operations such as:
– Read directory structures
– Execute commands or applications
• JavaScript can be defined is three basic ways in the HTML document:
–
–
–
–
Inline
Embedded
External
Combination of the above
3th February 2005
Bogdan L. Vrusias © 2005
21
Introduction to Client-Side
Web Development
JavaScript: Inline scripting
• Inline scripting is used when the user performs an action on an
element.
<img src="close.jpg" id="close"
onclick="window.close();" />
<img src="close.jpg" id="close"
onclick="gotoPage('1');" />
• You can take advantage of the fact that the element is implied when the
script is inline with the element's tag.
<img src="img.jpg" id="img"
onmouseover="src='img_2.jpg';"
onmouseout"src='img_1.jpg';" />
• From the previous example we observe the use of single quotes within
double quotes to be able to distinguish one from the other.
• You could also have the double quotes within the single quotes, but
you can never use same quotes within same quotes.
3th February 2005
Bogdan L. Vrusias © 2005
22
Introduction to Client-Side
Web Development
JavaScript: Embedded scripting
• Embedded scripting is the most popular way of scripting.
• Its basic syntax is:
<script type="text/javascript">
<!-window.alert("Hello World!");
//-->
</script>
• The main body of the script is placed within <!-- and //-->. This is
done for the browsers that do not support JavaScript, so that the script
is not processed and displayed on the screen.
• The example above is executed when the document is parsed.
• Embedded scripting is used when we want to create functions.
Functions will be executed only when they are called.
3th February 2005
Bogdan L. Vrusias © 2005
23
Introduction to Client-Side
Web Development
JavaScript: External scripting
• External scripting is used when you want to reuse your code all over
your Web pages.
• Having an external JavaScript file that all of your pages use, saves you
from having to update your code over every page that uses it.
• The external JavaScript file is a plain text file with the extension
".js" (e.g. highlight.js).
• The reference to an external JavaScript file from an HTML page is as
follows:
<script language="javascript" src="highlight.js"
/script>
• The source code from external JavaScript files is not directly visible on
the HTML document, but the source files can either be found on the
browser's cache directory or downloaded from the server.
3th February 2005
Bogdan L. Vrusias © 2005
24
Introduction to Client-Side
Web Development
JavaScript: Event Handlers
• Event handlers are very important part of a dynamic page,
as they respond to the user's actions.
• There are some standard events that are used by most
elements and there are other specific to one or just a few
elements.
• Event handlers are lowercase and curry an "on" prefix.
• Some standard event handlers are shown on the next page.
3th February 2005
Bogdan L. Vrusias © 2005
25
Introduction to Client-Side
Web Development
JavaScript: Event Handlers
onfocus
onmouseover
onclick
onkeydown
onload
onmousedown
onmousemove
onchange
onreset
3th February 2005
onblur
onmouseout
ondblclick
onkeyup
onunload
onmouseup
onkeypress
onselect
onsubmit
Bogdan L. Vrusias © 2005
26
Introduction to Client-Side
Web Development
JavaScript: Operators
• Operators operate on values. There are five types of
operators:
–
–
–
–
–
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
String Operators
3th February 2005
Bogdan L. Vrusias © 2005
27
Introduction to Client-Side
Web Development
JavaScript: Arithmetic Operators
Operator
Description
Example
Result
+
Addition
x=2
x+2
4
-
Subtraction
x=2
5-x
3
*
Multiplication
x=4
x*5
20
/
Division
15/5
5/2
3
2.5
%
Modulus (division remainder)
++
Increment
5%2
10%8
10%2
x=5
x++
1
2
0
x=6
--
Decrement
x=5
x--
x=4
3th February 2005
Bogdan L. Vrusias © 2005
28
Introduction to Client-Side
Web Development
JavaScript: Assignment Operators
Operator
Example
Is The Same As
=
x=y
x=y
+=
x+=y
x=x+y
-=
x-=y
x=x-y
*=
x*=y
x=x*y
/=
x/=y
x=x/y
%=
x%=y
x=x%y
3th February 2005
Bogdan L. Vrusias © 2005
29
Introduction to Client-Side
Web Development
JavaScript: Comparison Operators
Operator
Description
Example
==
is equal to
5==8 returns false
!=
is not equal
5!=8 returns true
>
is greater than
5>8 returns false
<
is less than
5<8 returns true
>=
is greater than or equal to
5>=8 returns false
<=
is less than or equal to
5<=8 returns true
3th February 2005
Bogdan L. Vrusias © 2005
30
Introduction to Client-Side
Web Development
JavaScript: Logical Operators
Operator
&&
Description
||
or
x=6
y=3
(x==5 || y==5)
returns false
!
not
x=6
y=3
x != y
returns true
3th February 2005
and
Example
x=6
y=3
(x < 10 && y > 1)
returns true
Bogdan L. Vrusias © 2005
31
Introduction to Client-Side
Web Development
JavaScript: String Operators
• The String Operator contains all comparison operators and
the concatenation operator (+).
• You can concatenate strings with strings, or even string
with numbers. When concatenating strings with numbers
the number is automatically converted into string, so the
result is a string.
var id=123;
var name="Andrew";
document.write("Name="+ name+" has id=" + id);
3th February 2005
Bogdan L. Vrusias © 2005
32
Introduction to Client-Side
Web Development
JavaScript: Objects
• JavaScript supports a set of built-in core language objects available for
both the client and the server side development platforms.
• The basic built-in core language objects are:
Global Object
Array Object
String Object
Date Object
Math Object
Number Object
Error Object
Boolean Object
RegExp Object
Function Object
• You can also create your own objects
3th February 2005
Bogdan L. Vrusias © 2005
33
Introduction to Client-Side
Web Development
JavaScript: The Global Object
• The basic methods and properties are provided bellow:
– Methods
escape(): Returns a string with the numeric equivalent of all
nonalphanumeric characters entered.
eval(): Evaluates a sting as a source code
isFinite(): Checks whether a variable has finite bounds
isNaN(): Checks whether or not a variable is a valid number
parseFloat(): Converts a string into a float number
parseInt(): Converts a string into an integer number
unescape(): Converts a hexadecimal value into the ISO-Latin-1 ACSII
equiveland
– Properties
Infinity: Represents positive infinity
NaN: Represents an object not equal to any number
3th February 2005
Bogdan L. Vrusias © 2005
34
Introduction to Client-Side
Web Development
JavaScript: The String Object
• The basic methods and properties are provided bellow:
– Methods
charAt(): Returns the character of a specific index
concat(): Concatenates two strings into one
indexOf(): Returns the index of the first occurrence of a string passed
lastIndexOf(): Returns the index of the last occurrence of a string passed
match(): Returns an array containing the matches found, based on the
regular expression string passed
replace(): Returns the string resulting from performing a search and
replace using the regular expression and replace string passed
substring(): Returns the string between the first and last index passed
toLowerCase(): Converts all characters in the string passed to lower case
– Properties
length: Represents the length of the string
prototype: Provides the capability to add properties to instances of the
String object
3th February 2005
Bogdan L. Vrusias © 2005
35
Introduction to Client-Side
Web Development
JavaScript: The String Object
• The String Object has also some formatting methods. The basic
methods are provided bellow:
anchor(): Converts the string into an instance of the <a> element
big(): Converts the string into an instance of the <big> element
bold(): Converts the string into an instance of the <bold> element
fixed(): Converts the string into an instance of the <tt> element
fontcolor(): Sets the color attribute of an instance of the <font> element
fontsize(): Sets the size attribute of an instance of the <font> element
italics(): Converts the string into an instance of the <i> element
link(): Converts the string into an instance of the <a> element
small(): Converts the string into an instance of the <small> element
strike(): Converts the string into an instance of the <strike> element
sub(): Converts the string into an instance of the <sub> element
sup(): Converts the string into an instance of the <sup> element
• Special Characters
\t (tab)
\\ (backslash)
3th February 2005
\n (new line)
\b (backspace)
\r (carriage return)
\" (double quote)
Bogdan L. Vrusias © 2005
\f (form feed)
\' (single quote)
36
Introduction to Client-Side
Web Development
JavaScript: The RegExp Object
• The basic methods and properties are provided bellow:
– Methods
compile(): Compiles the regular expression (for faster execution)
exec(): Executes the search for a match
test(): Tests for a string match
– Properties
RegExp.$*: Represents multiline
RegExp.$&: Represents lastmach
RegExp.$_: Represents input
RegExp.$`: Represents leftContext
RegExp.$': Represents rightContext
RegExp.$+: Represents lastParen
3th February 2005
Bogdan L. Vrusias © 2005
37
Introduction to Client-Side
Web Development
JavaScript: The Array Object
• The basic methods and properties are provided bellow:
– Methods
concat(): Concatenates the elements passed
pop(): Deletes the last element of an array
push(): Adds elements to the end of the array
reverse(): Reverses the order of the elements within the array
shift(): Deletes elements from the front of an array
slice(): Returns a subsection of the array
sort(): Sorts the elements in the array
splice(): Inserts and removes elements from an array
unshift(): Adds elements to the from of an array
– Properties
index: If the array is a result of a regular expression this property returns the
index of the match
input: If the array is a result of a regular expression this property returns the
original string
length: Represents the number of elements in the array
prototype: Provides capability to add properties to instances of the Array object
3th February 2005
Bogdan L. Vrusias © 2005
38
Introduction to Client-Side
Web Development
JavaScript: The Date Object
• The basic methods and properties are provided bellow:
– Methods
getDate(): Returns date within month
getDay(): Returns day within week
getFullYear(): Returns the four digit year in local time
getHours(): Returns the hour within the day
getMilliseconds(): Returns the milliseconds
getMinutes(): Returns the minutes within the hour
getMonth(): Returns the month within the year
getSeconds(): Returns the seconds within the minute
set…(): Sets the respective values (as above) to a Date object
toGMTString(): Returns the Date string in Universal format
– Properties
prototype: Provides capability to add properties to instances of the Date
object
3th February 2005
Bogdan L. Vrusias © 2005
39
Introduction to Client-Side
Web Development
JavaScript: The Math Object
• The basic methods and properties are provided bellow:
– Methods
abs(): Absolute value
cos(), sin(), tan(): Cosine, sine, and tangent respectively (in radians)
exp(): Euler's exponential function
log(): Natural logarithm with base e
max(), min(): Max and min respectively of two values passed
pow(): Power of the first value to the second value passed
random(): Random number between 0 and 1
round(): Rounded (whole) number of the value passed
sqrt(): Squared root
– Properties
E: Euler's constant (e=2.718…)
LN2, LN10: Natural Log of 2 and 10 respectively
LOG2E, LOG10E: Log base -2 and -10 of E
PI: Pi (=3.14…)
SQRT1_2, SQRT2: Square root of 0.5 and 2 respectively
3th February 2005
Bogdan L. Vrusias © 2005
40
Introduction to Client-Side
Web Development
JavaScript: The Boolean Object
• The basic methods and properties are provided bellow:
– Methods
toString(): Returns the string "true" if the values passed is true or the
string "false" if the value is false.
– Properties
prototype: Provides the capability to add properties to instances of the
Boolean object
3th February 2005
Bogdan L. Vrusias © 2005
41
Introduction to Client-Side
Web Development
JavaScript: The Number Object
• The basic methods and properties are provided bellow:
– Methods
toSource(): Concatenates the elements passed
toString(): Deletes the last element of an array
valueOf(): Adds elements to the end of the array
– Properties
MAX_VALUE, MIN_VALUE : Largest and smallest number supported
(1.797…e+308 and 5e-324 respectively)
NaN: Not-a-Number value
NEGATIVE_INFINITY, POSITIVE_INFINITY: Negative and positive
infinity respectively
prototype: Provides the capability to add properties to instances of the
Number object
3th February 2005
Bogdan L. Vrusias © 2005
42
Introduction to Client-Side
Web Development
JavaScript: The Error Object
• The basic methods and properties are provided bellow:
– Methods
toString(): Concatenates the elements passed
– Properties
description: Description string of the error
message: Returned error message
name: Exception type of the error
number: Numerical value of the error
3th February 2005
Bogdan L. Vrusias © 2005
43
Introduction to Client-Side
Web Development
JavaScript: The Function Object
• This object lets the user to define and compile a function at
runtime. The syntax is as follows:
newFunctionObj = new Function([arg1, arg2,
…,arg3], body)
• Function objects are slower in execution than normal
functions.
3th February 2005
Bogdan L. Vrusias © 2005
44
Introduction to Client-Side
Web Development
JavaScript: Control Statements
• You can build complex control statements with JavaScript.
The basic control statements are:
– Conditional Statements
• if
• if…else
• try…catch…finally
– Looping Statements
•
•
•
•
•
for
for…in
while
do…while
break and continue
– Label Statement
– With Statement
– Switch Statement
3th February 2005
Bogdan L. Vrusias © 2005
45
Introduction to Client-Side
Web Development
JavaScript: Conditional Statements
Conditional Statements
if (condition) { statements }
if (email=="") { alert("Please fill in the email box"); }
if (condition) { statement } else {statement }
if (email=="") { alert("Please fill in the email box");}
else { submitPage();}
try { statement } catch(exception) { statement }
finally { statement }
try {
if (id=="") { throw "Invalid id error";}
submitPage(id);
}
catch(e) { alert("Error: " + e); }
finally { close(); }
3th February 2005
Bogdan L. Vrusias © 2005
46
Introduction to Client-Side
Web Development
JavaScript: Looping Statements
• Looping Statements
for ([initExpr];[condExpr];[loopExpr]) { statements }
for (var i=0; i<10; ++i) { alert("Step " + i); }
for (property in Object) { statements }
var dObject = document;
for (var pName in dObject) { alert("pName = " + dObject[pName]); }
while (condition) { statements }
while (i<10) { alert("i=" + i); i+=2;}
do {statements} while (condition)
do { alert("i=" +i); i+=2;} while (i<10)
break and continue
for (var i=0; i<10; ++i) {
if (i>5) { break; }
if (i<3) { continue; }
alert(i);
}
th
3 February 2005
Bogdan L. Vrusias © 2005
47
Introduction to Client-Side
Web Development
JavaScript: Label Statement
• Label Statement
…
var n = 10;
loopX:
for (var i=0; i<n; ++i) {
if (i>5) {
n = 5;
break loopX;
}
if (i<3) { continue; }
alert(i);
}
3th February 2005
Bogdan L. Vrusias © 2005
48
Introduction to Client-Side
Web Development
JavaScript: With Statements
•
with (object) { statements }
…
with (document) {
write("The document\'s title is: " + title);
write("The document\'s URL is: " + URL);
}
3th February 2005
Bogdan L. Vrusias © 2005
49
Introduction to Client-Side
Web Development
JavaScript: Switch Statement
switch (expression) {
case value1: statement; break;
case value2: statement; break;
default : statement;
}
var type="red";
switch (type) {
case "red":
alert("red");
break;
case "blue":
alert("blue");
break;
default:
alert("Not red or blue");
}
3th February 2005
Bogdan L. Vrusias © 2005
50
Introduction to Client-Side
Web Development
Closing
•
•
•
•
Questions???
Remarks???
Comments!!!
Evaluation!
3th February 2005
Bogdan L. Vrusias © 2005
51
Download