Download presentation
Presentation is loading. Please wait.
Published byCuthbert Bennett Modified over 7 years ago
1
Introduction to Client-Side programming using JavaScript
DOM and JavaScript; basic syntax and concepts 5th February 2004 Bogdan L. Vrusias
2
Session II Contents Understanding the DOM Introduction to JavaScript
JavaScript syntax JavaScript objects 5th February 2004 Bogdan L. Vrusias © 2004
3
DOM Basics: The Object Model
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. To navigate to an object in the model you use the dot (.) syntax. window.location.href = " 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. 5th February 2004 Bogdan L. Vrusias © 2004
4
DOM Basics: Browser Object Model
The Browser Object Model describe the object model that a browser provides the user. The browser object model has the structure shown below: 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 5th February 2004 Bogdan L. Vrusias © 2004
5
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 also supports StyleSheet objects. The DOM of an HTML document is shown bellow: document anchors applets body forms images links elements 5th February 2004 Bogdan L. Vrusias © 2004
6
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 5th February 2004 Bogdan L. Vrusias © 2004
7
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" Inserting an element in the document may cause reference problems, as the elements are depended on their position on the document. 5th February 2004 Bogdan L. Vrusias © 2004
8
DOM Basics: DOM as Nodes
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].childNodes[0].childNodes[0].stc = "img2.jpg" Node walking is not a recommended approach. The best thing about the DOM and nodes is that you can add and remove nodes. new_element = document.createElement("div") document.childNodes[1].childNodes[1].appendChild(new_element) new_text_node = document.createTextNode("text") document.childNodes[1].childNodes[1].lastChild.appendChild(new_text_node) 5th February 2004 Bogdan L. Vrusias © 2004
9
DOM Basics: DOM using an ID
DOM using an ID: where you can reference a specific element. Locating elements in a document through the id of the element is preferred, rather than using the object collections or node walking. document.getElementById(" ") What you have to be aware of is that every element you want to locate through the DOM has to have a unique id. <div id="advert_area">…</div> You can access all attributes of a specific element: document.getElementById("img_01").setAttribute("src", "img_02.jpg") 5th February 2004 Bogdan L. Vrusias © 2004
10
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" represent both Netscape and Microsoft implementation of ECMAScript. 5th February 2004 Bogdan L. Vrusias © 2004
11
JavaScript: Introduction
With HTML, 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. The solution to that problem 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. The most popular client-side scripting language is JavaScript. JavaScript adds logic and reactivity to the HTML document. JavaScript is NOT Java! JavaScript is not an independent language that could create stand alone applications. It can only run within another application (the browser). 5th February 2004 Bogdan L. Vrusias © 2004
12
JavaScript: Basic Syntax
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); Respond to events <img src="img.jpg" id="img_1" onmouseover="changeImg();" /> 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 */ 5th February 2004 Bogdan L. Vrusias © 2004
13
JavaScript: Basic Syntax
JavaScript is case sensitive. Variables should be defined (optional… but not recommended) Each statement ends with a semicolon (optional for some browsers); 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!!! 5th February 2004 Bogdan L. Vrusias © 2004
14
JavaScript: Functions
Using functions the developer structures the code and makes it more efficient. Function is a logical set of statements that performs 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); 5th February 2004 Bogdan L. Vrusias © 2004
15
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. 5th February 2004 Bogdan L. Vrusias © 2004
16
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. The basic syntax for entering JavaScript on an HTML page is: <script type="text/javascript"> <!-- window.alert("Hello World!"); //--> </script> 5th February 2004 Bogdan L. Vrusias © 2004
17
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 by: document.write("some text"); 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 5th February 2004 Bogdan L. Vrusias © 2004
18
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. 5th February 2004 Bogdan L. Vrusias © 2004
19
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. 5th February 2004 Bogdan L. Vrusias © 2004
20
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. 5th February 2004 Bogdan L. Vrusias © 2004
21
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. 5th February 2004 Bogdan L. Vrusias © 2004
22
JavaScript: Event Handlers
onfocus onblur onmouseover onmouseout onclick ondblclick onkeydown onkeyup onload onunload onmousedown onmouseup onmousemove onkeypress onchange onselect onreset onsubmit 5th February 2004 Bogdan L. Vrusias © 2004
23
JavaScript: Operators
Operators operate on values. There are five types of operators: Arithmetic Operators Assignment Operators Comparison Operators Logical Operators String Operators 5th February 2004 Bogdan L. Vrusias © 2004
24
JavaScript: Arithmetic Operators
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) 5%2 10%8 10%2 1 2 0 ++ Increment x=5 x++ x=6 -- Decrement x=5 x-- x=4 5th February 2004 Bogdan L. Vrusias © 2004
25
JavaScript: Assignment Operators
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 5th February 2004 Bogdan L. Vrusias © 2004
26
JavaScript: Comparison Operators
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 5th February 2004 Bogdan L. Vrusias © 2004
27
JavaScript: Logical Operators
Description Example && and x=6 y=3 (x < 10 && y > 1) returns true || or (x==5 || y==5) returns false ! not x != y returns true 5th February 2004 Bogdan L. Vrusias © 2004
28
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); 5th February 2004 Bogdan L. Vrusias © 2004
29
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: The Global Object The String Object The RegExp Object The Array Object The Date Object The Math Object The Boolean Object The Number Object The Error Object The Function Object You can also create your own objects 5th February 2004 Bogdan L. Vrusias © 2004
30
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 5th February 2004 Bogdan L. Vrusias © 2004
31
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 5th February 2004 Bogdan L. Vrusias © 2004
32
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) \n (new line) \r (carriage return) \f (form feed) \\ (backslash) \b (backspace) \" (double quote) \' (single quote) 5th February 2004 Bogdan L. Vrusias © 2004
33
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 5th February 2004 Bogdan L. Vrusias © 2004
34
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 5th February 2004 Bogdan L. Vrusias © 2004
35
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 Properties prototype: Provides capability to add properties to instances of the Date object 5th February 2004 Bogdan L. Vrusias © 2004
36
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 5th February 2004 Bogdan L. Vrusias © 2004
37
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 5th February 2004 Bogdan L. Vrusias © 2004
38
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 5th February 2004 Bogdan L. Vrusias © 2004
39
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 5th February 2004 Bogdan L. Vrusias © 2004
40
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. 5th February 2004 Bogdan L. Vrusias © 2004
41
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 5th February 2004 Bogdan L. Vrusias © 2004
42
JavaScript: Conditional Statements
if (condition) { statements } if ( =="") { alert("Please fill in the box"); } if (condition) { statement } else {statement } if ( =="") { alert("Please fill in the 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(); } 5th February 2004 Bogdan L. Vrusias © 2004
43
JavaScript: 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 } var i = 0; 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); } 5th February 2004 Bogdan L. Vrusias © 2004
44
JavaScript: 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); 5th February 2004 Bogdan L. Vrusias © 2004
45
JavaScript: With Statements
with (object) { statements } … with (document) { write("The document\'s title is: " + title); write("The document\'s URL is: " + URL); } 5th February 2004 Bogdan L. Vrusias © 2004
46
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"); default: alert("Not red or blue"); 5th February 2004 Bogdan L. Vrusias © 2004
47
Applications: Hiding & Showing Elements
Consider the scenario where you want to be able to dynamically hide or show a particular HTML element (such as a text filed). var advertVisible = true; function showAdvert() { if (advertVisible == true) { document.getElementById("advert").style.display = "block"; advertVisible = false; } else { document.getElementById("advert").style.display = "none"; advertVisible = true; … <img src="close.jpg" onclick="advertVisible();"> <div id="advert">The annoying advert.</div> 5th February 2004 Bogdan L. Vrusias © 2004
48
Applications: Image Rollovers
Consider the scenario where you want to be able to dynamically update an image when the mouse is over it. This method is useful to create buttons that get activated when the mouse goes over them. To make the rollover effect more efficient you should preload all the images (even those that are not displayed yet) on the clients side. First check if the browser supports images. The code is as follows: if (document.images) { button_01_on = new Image(60, 20); button_01_on.src = "button_01_on.gif"; // highlighted button_01_off = new Image(60, 20); button_01_off.src = "button_01_off.gif"; // normal } … <img src="button_01_off.gif" onmouseover="src=button_01_on.src" /> 5th February 2004 Bogdan L. Vrusias © 2004
49
Applications: Validating Form Data
Validation is the process of making sure that the data entered by the user is complying to the expected format and rules of your application. Validation is a key part of the Web application, and one of the most important uses of JavaScript. Validating the data on the client-side could save a lot of hassle. Data can be validated in three basic ways: Validate the data at the Web server. Validate as each value is added or modified (field-level validation). Validate all fields on the form before the user submits the data to the Web server (form-level validation). Form-level validation is the most common way of validating the data. Common types of validation include: numeric, required, range, or a specific format (such as , zip code, etc.) 5th February 2004 Bogdan L. Vrusias © 2004
50
Applications: Validating Data Example
function isNumeric(e) { if (e.value=="") { return true; } var v = parseFloat(e.value); if (isNaN(v)) { alert("The entry in " + e.name + " must be numeric"); return false; } else { return true; } } function isAllNumeric(e) { var numericExp=/^\d+$/; if (numericExp.test(e.value)) { return true; } else{ 5th February 2004 Bogdan L. Vrusias © 2004
51
Applications: Cookies
Cookies are the mechanism provided by the browser that allow storage and retrieval of information on the computer. Usually the cookies are used to store information about the user and information about settings and preferences. The basic information you can get from a cookie is its name, its domain and path, its value, its security, and its expiration date. For security reasons the cookie is only accessible by Web pages within the same directory (or subdirectory), or in the same domain. The cookie property is accessed from the document object. 5th February 2004 Bogdan L. Vrusias © 2004
52
Applications: Cookies Security
Security issues concerns: A cookie is a simple text file, it is not executed, therefore it cannot be a virus. A cookie cannot steal personal information from your machine, or even interact with any other data stored. A cookie cannot interact with other cookies of even read information from those. Making it safer any way? Then: Don't store private information in a cookie. If possible, kill the cookie as soon as you have finished with it. Provide a privacy policy. Use alternatives, if appropriate, such as HTML hidden fields, appending information to the URI, using a database, or the server. 5th February 2004 Bogdan L. Vrusias © 2004
53
Applications: Cookie Example
function setCookie(sName, sValue) { var expireDate = new Date; expireDate.setYear(expireDate.getFullYear() + 1); document.cookie = sName + "=" + escape(sValue) + ";expires=" + expireDate.toGMTString(); } function getCookie(sName) { var arrCookies = document.cookie.split("; "); for(var i = 0; i < arrCookies.length; i++) { if(sName == arrCookies[i].split("=")[0]) { return unescape(arrCookies[i].split("=")[1]); return ""; 5th February 2004 Bogdan L. Vrusias © 2004
54
Session II: Closing Questions??? Remarks??? Comments!!! Evaluation!
5th February 2004 Bogdan L. Vrusias © 2004
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.