Introduction to ClientSide Web Development Introduction to ClientSide
Introduction to Client-Side Web Development Introduction to Client-Side programming using Java. Script DOM and Java. Script; basic syntax and concepts 3 th February 2005 Bogdan L. Vrusias b. vrusias@surrey. ac. uk 3 th February 2005 Bogdan L. Vrusias © 2005
Introduction to Client-Side Web Development Contents • • Understanding the DOM Introduction to Java. Script syntax Java. Script objects 3 th 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. 3 th 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. 3 th 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. 3 th 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 W 3 C) is compatible with most of the browsers (especially Netscape is fully compatible). • DOM Level 2, 3 also supports Style. Sheet objects. document anchors applets body forms images links elements 3 th 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 3 th 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. 3 th 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. child. Nodes[0] • The content of an element is called text node and can be accessed by: document. child. Nodes[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. child. Nodes[0]. src = "img. jpg" 3 th 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. create. Element("div") document. child. Nodes[1]. append. Child(new_element) new_text_node = document. create. Text. Node("text") document. child. Nodes[1]. last. Child. append. Child(new_text_node) 3 th 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. get. Element. By. Id("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. get. Element. By. Id("img_01"). set. Attribute("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. 3 th February 2005 Bogdan L. Vrusias © 2005 11
Introduction to Client-Side Web Development History: Java. Script • Java. Script was developed by Netscape and was then known as Live. Script. • Java. Script 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 Java. Script and JScript into an international standard script language called ECMAScript. • So the term "Java. Script" represents both Netscape and Microsoft implementation of ECMAScript. 3 th February 2005 Bogdan L. Vrusias © 2005 12
Introduction to Client-Side Web Development Java. Script: 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. 3 th February 2005 Bogdan L. Vrusias © 2005 13
Introduction to Client-Side Web Development Java. Script: Introduction II • The most popular client-side scripting language is Java. Script. • Java. Script adds logic and reactivity to the HTML document. • Java. Script is not an independent language that could create stand alone applications. It can only run within another application (the browser). NOTE: Java. Script is NOT Java! 3 th February 2005 Bogdan L. Vrusias © 2005 14
Introduction to Client-Side Web Development Java. Script: Basic Syntax I • With Java. Script the developer can: – Define variables var x = 1; – Create objects var new. Element = document. create. Element("div"); – Create and call functions function add(x, y) { return x+y; } … sum = add(2, 3); 3 th February 2005 Bogdan L. Vrusias © 2005 15
Introduction to Client-Side Web Development Java. Script: Basic Syntax II – Respond to events <img src="img. jpg" id="img 1" 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 */ 3 th February 2005 Bogdan L. Vrusias © 2005 16
Introduction to Client-Side Web Development Java. Script: Basic Syntax III • Java. Script 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!!! 3 th February 2005 Bogdan L. Vrusias © 2005 17
Introduction to Client-Side Web Development Java. Script: 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); 3 th February 2005 Bogdan L. Vrusias © 2005 18
Introduction to Client-Side Web Development Java. Script: 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="close. Window(); " /> or <img src="close. jpg" id="close" onclick="window. close(); " /> • Each element has a specific set of event handlers. 3 th February 2005 Bogdan L. Vrusias © 2005 19
Introduction to Client-Side Web Development Java. Script: How it works • Java. Script 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. • Java. Script is an interpreted language, the code is not compiled, therefore each line of code is processed as the script is executed. • You can either execute the Java. Script code before the HTML page is displayed or after. 3 th February 2005 Bogdan L. Vrusias © 2005 20
Introduction to Client-Side Web Development Java. Script: How it works • Because the Java. Script 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 Java. Script cannot perform operations such as: – Read directory structures – Execute commands or applications • Java. Script can be defined is three basic ways in the HTML document: – – Inline Embedded External Combination of the above 3 th February 2005 Bogdan L. Vrusias © 2005 21
Introduction to Client-Side Web Development Java. Script: 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="goto. Page('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. 3 th February 2005 Bogdan L. Vrusias © 2005 22
Introduction to Client-Side Web Development Java. Script: 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 Java. Script, 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. 3 th February 2005 Bogdan L. Vrusias © 2005 23
Introduction to Client-Side Web Development Java. Script: External scripting • External scripting is used when you want to reuse your code all over your Web pages. • Having an external Java. Script file that all of your pages use, saves you from having to update your code over every page that uses it. • The external Java. Script file is a plain text file with the extension ". js" (e. g. highlight. js). • The reference to an external Java. Script file from an HTML page is as follows: <script language="javascript" src="highlight. js" /script> • The source code from external Java. Script 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. 3 th February 2005 Bogdan L. Vrusias © 2005 24
Introduction to Client-Side Web Development Java. Script: 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. 3 th February 2005 Bogdan L. Vrusias © 2005 25
Introduction to Client-Side Web Development Java. Script: Event Handlers onfocus onblur onmouseover onmouseout onclick ondblclick onkeydown onkeyup onload onunload onmousedown onmouseup onmousemove onkeypress onchange onselect onreset onsubmit 3 th February 2005 Bogdan L. Vrusias © 2005 26
Introduction to Client-Side Web Development Java. Script: Operators • Operators operate on values. There are five types of operators: – – – Arithmetic Operators Assignment Operators Comparison Operators Logical Operators String Operators 3 th February 2005 Bogdan L. Vrusias © 2005 27
Introduction to Client-Side Web Development Java. Script: 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 3 th February 2005 Bogdan L. Vrusias © 2005 28
Introduction to Client-Side Web Development Java. Script: Assignment Operators Operator Example Is The Same As = 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 3 th February 2005 Bogdan L. Vrusias © 2005 29
Introduction to Client-Side Web Development Java. Script: 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 3 th February 2005 Bogdan L. Vrusias © 2005 30
Introduction to Client-Side Web Development Java. Script: Logical Operators Operator && Description || or x=6 y=3 (x==5 || y==5) returns false ! not x=6 y=3 x != y returns true 3 th 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 Java. Script: 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); 3 th February 2005 Bogdan L. Vrusias © 2005 32
Introduction to Client-Side Web Development Java. Script: Objects • Java. Script 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 Reg. Exp Object Function Object • You can also create your own objects 3 th February 2005 Bogdan L. Vrusias © 2005 33
Introduction to Client-Side Web Development Java. Script: 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 is. Finite(): Checks whether a variable has finite bounds is. Na. N(): Checks whether or not a variable is a valid number parse. Float(): Converts a string into a float number parse. Int(): Converts a string into an integer number unescape(): Converts a hexadecimal value into the ISO-Latin-1 ACSII equiveland – Properties Infinity: Represents positive infinity Na. N: Represents an object not equal to any number 3 th February 2005 Bogdan L. Vrusias © 2005 34
Introduction to Client-Side Web Development Java. Script: The String Object • The basic methods and properties are provided bellow: – Methods char. At(): Returns the character of a specific index concat(): Concatenates two strings into one index. Of(): Returns the index of the first occurrence of a string passed last. Index. Of(): 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 to. Lower. Case(): 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 3 th February 2005 Bogdan L. Vrusias © 2005 35
Introduction to Client-Side Web Development Java. Script: 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) 3 th 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 Java. Script: The Reg. Exp 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 Reg. Exp. $*: Represents multiline Reg. Exp. $&: Represents lastmach Reg. Exp. $_: Represents input Reg. Exp. $`: Represents left. Context Reg. Exp. $': Represents right. Context Reg. Exp. $+: Represents last. Paren 3 th February 2005 Bogdan L. Vrusias © 2005 37
Introduction to Client-Side Web Development Java. Script: 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 3 th February 2005 Bogdan L. Vrusias © 2005 38
Introduction to Client-Side Web Development Java. Script: The Date Object • The basic methods and properties are provided bellow: – Methods get. Date(): Returns date within month get. Day(): Returns day within week get. Full. Year(): Returns the four digit year in local time get. Hours(): Returns the hour within the day get. Milliseconds(): Returns the milliseconds get. Minutes(): Returns the minutes within the hour get. Month(): Returns the month within the year get. Seconds(): Returns the seconds within the minute set…(): Sets the respective values (as above) to a Date object to. GMTString(): Returns the Date string in Universal format – Properties prototype: Provides capability to add properties to instances of the Date object 3 th February 2005 Bogdan L. Vrusias © 2005 39
Introduction to Client-Side Web Development Java. Script: The Math Object • The basic methods and properties are provided bellow: – Methods abs(): Absolute value cos(), sin(), tan(): Cosine, 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…) LN 2, LN 10: Natural Log of 2 and 10 respectively LOG 2 E, LOG 10 E: Log base -2 and -10 of E PI: Pi ( =3. 14…) SQRT 1_2, SQRT 2: Square root of 0. 5 and 2 respectively 3 th February 2005 Bogdan L. Vrusias © 2005 40
Introduction to Client-Side Web Development Java. Script: The Boolean Object • The basic methods and properties are provided bellow: – Methods to. String(): 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 3 th February 2005 Bogdan L. Vrusias © 2005 41
Introduction to Client-Side Web Development Java. Script: The Number Object • The basic methods and properties are provided bellow: – Methods to. Source(): Concatenates the elements passed to. String(): Deletes the last element of an array value. Of(): Adds elements to the end of the array – Properties MAX_VALUE, MIN_VALUE : Largest and smallest number supported (1. 797…e+308 and 5 e-324 respectively) Na. N: 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 3 th February 2005 Bogdan L. Vrusias © 2005 42
Introduction to Client-Side Web Development Java. Script: The Error Object • The basic methods and properties are provided bellow: – Methods to. String(): 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 3 th February 2005 Bogdan L. Vrusias © 2005 43
Introduction to Client-Side Web Development Java. Script: The Function Object • This object lets the user to define and compile a function at runtime. The syntax is as follows: new. Function. Obj = new Function([arg 1, arg 2, …, arg 3], body) • Function objects are slower in execution than normal functions. 3 th February 2005 Bogdan L. Vrusias © 2005 44
Introduction to Client-Side Web Development Java. Script: Control Statements • You can build complex control statements with Java. Script. The basic control statements are: – Conditional Statements • if…else • try…catch…finally – Looping Statements • • • for…in while do…while break and continue – Label Statement – With Statement – Switch Statement 3 th February 2005 Bogdan L. Vrusias © 2005 45
Introduction to Client-Side Web Development Java. Script: 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 { submit. Page(); } try { statement } catch(exception) { statement } finally { statement } try { if (id=="") { throw "Invalid id error"; } submit. Page(id); } catch(e) { alert("Error: " + e); } finally { close(); } 3 th February 2005 Bogdan L. Vrusias © 2005 46
Introduction to Client-Side Web Development Java. Script: Looping Statements • Looping Statements for ([init. Expr]; [cond. Expr]; [loop. Expr]) { statements } for (var i=0; i<10; ++i) { alert("Step " + i); } for (property in Object) { statements } var d. Object = document; for (var p. Name in d. Object) { alert("p. Name = " + d. Object[p. Name]); } 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 Java. Script: Label Statement • Label Statement … var n = 10; loop. X: for (var i=0; i<n; ++i) { if (i>5) { n = 5; break loop. X; } if (i<3) { continue; } alert(i); } 3 th February 2005 Bogdan L. Vrusias © 2005 48
Introduction to Client-Side Web Development Java. Script: With Statements • with (object) { statements } … with (document) { write("The document's title is: " + title); write("The document's URL is: " + URL); } 3 th February 2005 Bogdan L. Vrusias © 2005 49
Introduction to Client-Side Web Development Java. Script: Switch Statement switch (expression) { case value 1: statement; break; case value 2: 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"); } 3 th February 2005 Bogdan L. Vrusias © 2005 50
Introduction to Client-Side Web Development Closing • • Questions? ? ? Remarks? ? ? Comments!!! Evaluation! 3 th February 2005 Bogdan L. Vrusias © 2005 51
- Slides: 51