introduction to client-side web development introduction to client-side programming using javascript...
TRANSCRIPT
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
Introduction to Client-Side programming Introduction to Client-Side programming using JavaScriptusing JavaScript
DOM and JavaScript; basic syntax and concepts
3th February 2005
Bogdan L. [email protected]
3th February 2005 Bogdan L. Vrusias © 2005 2
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
ContentsContents• Understanding the DOM
• Introduction to JavaScript
• JavaScript syntax
• JavaScript objects
3th February 2005 Bogdan L. Vrusias © 2005 3
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
DOM Basics: The Object Model IDOM 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 4
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
DOM Basics: The Object Model IIDOM 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 5
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
DOM Basics: Browser Object ModelDOM Basics: Browser Object Model• The Browser Object Model describes the object model that a browser
provides the user:
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.
window
document history location navigator
3th February 2005 Bogdan L. Vrusias © 2005 6
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
DOM Basics: The Document Object ModelDOM 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 7
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
DOM Basics: The Document Object ModelDOM 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 8
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
DOM Basics: DOM as ObjectsDOM 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 9
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
DOM Basics: DOM as Nodes IDOM 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 10
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
DOM Basics: DOM as Nodes IIDOM 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 11
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
DOM Basics: DOM using an IDDOM 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 12
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
History: JavaScriptHistory: 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 13
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: Introduction IJavaScript: 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 14
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: Introduction IIJavaScript: 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 15
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: Basic Syntax IJavaScript: Basic Syntax I• With JavaScript the developer can:
– Define variablesvar x = 1;
– Create objectsvar newElement = document.createElement("div");
– Create and call functionsfunction add(x, y) {
return x+y;
}
…
sum = add(2, 3);
3th February 2005 Bogdan L. Vrusias © 2005 16
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: Basic Syntax IIJavaScript: Basic Syntax II– Respond to events
<img src="img.jpg" id="img1" nmouseover=“doit();"/>
– Perform basic operationsx = x + 5;
– Use basic control statementsif (x>y) { y=x; } else { x=y; }
– Comment the source codex += 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 17
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: Basic Syntax IIIJavaScript: 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 18
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: FunctionsJavaScript: 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 19
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: EventsJavaScript: 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 20
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: How it worksJavaScript: 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 21
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: How it worksJavaScript: 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 22
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: Inline scriptingJavaScript: 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 23
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: Embedded scriptingJavaScript: 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 24
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: External scriptingJavaScript: 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 25
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: Event HandlersJavaScript: 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 26
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: Event HandlersJavaScript: Event Handlers
onfocus onblur
onmouseover onmouseout
onclick ondblclick
onkeydown onkeyup
onload onunload
onmousedown onmouseup
onmousemove onkeypress
onchange onselect
onreset onsubmit
3th February 2005 Bogdan L. Vrusias © 2005 27
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: OperatorsJavaScript: 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 28
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: Arithmetic OperatorsJavaScript: Arithmetic OperatorsOperator Description Example Result
+ Addition x=2x+2
4
- Subtraction x=25-x
3
* Multiplication x=4x*5
20
/ Division 15/55/2
32.5
% Modulus (division remainder) 5%210%810%2
120
++ Increment x=5x++
x=6
-- Decrement x=5x--
x=4
3th February 2005 Bogdan L. Vrusias © 2005 29
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: Assignment OperatorsJavaScript: 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 30
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: Comparison OperatorsJavaScript: 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 31
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: Logical OperatorsJavaScript: Logical Operators
Operator Description Example
&& and x=6y=3 (x < 10 && y > 1)returns true
|| or x=6y=3 (x==5 || y==5)returns false
! not x=6y=3 x != yreturns true
3th February 2005 Bogdan L. Vrusias © 2005 32
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: String OperatorsJavaScript: 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 33
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: ObjectsJavaScript: 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:
• You can also create your own objects
Global Object Array Object
String Object Date Object
Math Object Number Object
Error Object Boolean Object
RegExp Object Function Object
3th February 2005 Bogdan L. Vrusias © 2005 34
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: The Global ObjectJavaScript: The Global Object• The basic methods and properties are provided bellow:
– Methodsescape(): 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
– PropertiesInfinity: Represents positive infinity
NaN: Represents an object not equal to any number
3th February 2005 Bogdan L. Vrusias © 2005 35
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: The String ObjectJavaScript: The String Object• The basic methods and properties are provided bellow:
– MethodscharAt(): Returns the character of a specific indexconcat(): Concatenates two strings into oneindexOf(): Returns the index of the first occurrence of a string passedlastIndexOf(): Returns the index of the last occurrence of a string passedmatch(): Returns an array containing the matches found, based on the
regular expression string passedreplace(): Returns the string resulting from performing a search and
replace using the regular expression and replace string passedsubstring(): Returns the string between the first and last index passedtoLowerCase(): Converts all characters in the string passed to lower case
– Propertieslength: Represents the length of the stringprototype: Provides the capability to add properties to instances of the
String object
3th February 2005 Bogdan L. Vrusias © 2005 36
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: The String ObjectJavaScript: 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> elementbig(): Converts the string into an instance of the <big> elementbold(): Converts the string into an instance of the <bold> elementfixed(): Converts the string into an instance of the <tt> elementfontcolor(): Sets the color attribute of an instance of the <font> elementfontsize(): Sets the size attribute of an instance of the <font> elementitalics(): Converts the string into an instance of the <i> elementlink(): Converts the string into an instance of the <a> elementsmall(): Converts the string into an instance of the <small> elementstrike(): Converts the string into an instance of the <strike> elementsub(): Converts the string into an instance of the <sub> elementsup(): Converts the string into an instance of the <sup> element
• Special Characters\t (tab) \n (new line) \r (carriage return) \f (form feed)\\ (backslash) \b (backspace) \" (double quote) \' (single quote)
3th February 2005 Bogdan L. Vrusias © 2005 37
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: The RegExp ObjectJavaScript: The RegExp Object• The basic methods and properties are provided bellow:
– Methodscompile(): Compiles the regular expression (for faster execution)
exec(): Executes the search for a match
test(): Tests for a string match
– PropertiesRegExp.$*: Represents multiline
RegExp.$&: Represents lastmach
RegExp.$_: Represents input
RegExp.$`: Represents leftContext
RegExp.$': Represents rightContext
RegExp.$+: Represents lastParen
3th February 2005 Bogdan L. Vrusias © 2005 38
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: The Array ObjectJavaScript: The Array Object• The basic methods and properties are provided bellow:
– Methodsconcat(): Concatenates the elements passedpop(): Deletes the last element of an arraypush(): Adds elements to the end of the arrayreverse(): Reverses the order of the elements within the arrayshift(): Deletes elements from the front of an arrayslice(): Returns a subsection of the arraysort(): Sorts the elements in the arraysplice(): Inserts and removes elements from an arrayunshift(): Adds elements to the from of an array
– Propertiesindex: If the array is a result of a regular expression this property returns the index
of the matchinput: If the array is a result of a regular expression this property returns the
original stringlength: Represents the number of elements in the arrayprototype: Provides capability to add properties to instances of the Array object
3th February 2005 Bogdan L. Vrusias © 2005 39
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: The Date ObjectJavaScript: The Date Object• The basic methods and properties are provided bellow:
– MethodsgetDate(): Returns date within monthgetDay(): Returns day within weekgetFullYear(): Returns the four digit year in local timegetHours(): Returns the hour within the daygetMilliseconds(): Returns the millisecondsgetMinutes(): Returns the minutes within the hourgetMonth(): Returns the month within the yeargetSeconds(): Returns the seconds within the minuteset…(): Sets the respective values (as above) to a Date objecttoGMTString(): Returns the Date string in Universal format
– Propertiesprototype: Provides capability to add properties to instances of the Date
object
3th February 2005 Bogdan L. Vrusias © 2005 40
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: The Math ObjectJavaScript: The Math Object• The basic methods and properties are provided bellow:
– Methodsabs(): Absolute valuecos(), sin(), tan(): Cosine, sine, and tangent respectively (in radians)exp(): Euler's exponential functionlog(): Natural logarithm with base emax(), min(): Max and min respectively of two values passedpow(): Power of the first value to the second value passedrandom(): Random number between 0 and 1round(): Rounded (whole) number of the value passedsqrt(): Squared root
– PropertiesE: Euler's constant (e=2.718…)LN2, LN10: Natural Log of 2 and 10 respectivelyLOG2E, LOG10E: Log base -2 and -10 of EPI: Pi (=3.14…)SQRT1_2, SQRT2: Square root of 0.5 and 2 respectively
3th February 2005 Bogdan L. Vrusias © 2005 41
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: The Boolean ObjectJavaScript: The Boolean Object• The basic methods and properties are provided bellow:
– MethodstoString(): Returns the string "true" if the values passed is true or the
string "false" if the value is false.
– Propertiesprototype: Provides the capability to add properties to instances of the
Boolean object
3th February 2005 Bogdan L. Vrusias © 2005 42
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: The Number ObjectJavaScript: The Number Object• The basic methods and properties are provided bellow:
– MethodstoSource(): Concatenates the elements passed
toString(): Deletes the last element of an array
valueOf(): Adds elements to the end of the array
– PropertiesMAX_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 43
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: The Error ObjectJavaScript: The Error Object• The basic methods and properties are provided bellow:
– MethodstoString(): Concatenates the elements passed
– Propertiesdescription: 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 44
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: The Function ObjectJavaScript: 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 45
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: Control StatementsJavaScript: 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 46
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: Conditional StatementsJavaScript: Conditional StatementsConditional Statementsif (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 47
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: Looping StatementsJavaScript: Looping Statements• Looping Statementsfor ([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 continuefor (var i=0; i<10; ++i) { if (i>5) { break; } if (i<3) { continue; } alert(i);}
3th February 2005 Bogdan L. Vrusias © 2005 48
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: Label StatementJavaScript: 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 49
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: With StatementsJavaScript: 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 50
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
JavaScript: Switch StatementJavaScript: Switch Statementswitch (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 51
Introduction to Client-SideIntroduction to Client-SideWeb DevelopmentWeb Development
ClosingClosing
• Questions???
• Remarks???
• Comments!!!
• Evaluation!