Published on

Introduction to javascript

Published in: Technology
1 Comment
  • A very good presentation on Javascript. It would be very useful for those who are beginners in web programming.
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. JavaScript CCSS TEAM: Eng. Musavir Iftekhar Bhatti
  2. 2. What is JavaScript ? <ul><li>Client-side language.( run in the client browser) </li></ul><ul><li>Scripting language. (interpreted in run-time) </li></ul><ul><li>Not compile like other language </li></ul><ul><li>(C#, C++, VB.Net etc). </li></ul><ul><li>JavaScript code can be inserted directly in </li></ul><ul><li>the HTML or can place it in a separate file </li></ul><ul><li>with the .js extension and link the web page </li></ul><ul><li>with the .js file. </li></ul><ul><li>Use in web browser for making a website more dynamic. </li></ul><ul><li>Supported by Netscape 2+, Internet Explorer 3+, Opera 3+ and most of the other modern web browsers. </li></ul><ul><li>Contains variable, array,object,operators and function. </li></ul>
  3. 3. Usage of JavaScript <ul><li>Used to perform operations that would otherwise encumber the server, like form validation input. </li></ul><ul><li>Can be easily used to interact with HTML elements such as validate text fields, disable buttons, validate forms, or change the background color of page. </li></ul><ul><li>Create dynamic page </li></ul><ul><li>React to events such the user enter name whenever the page load for 1 st time. User can used entered value for welcome page. </li></ul>
  4. 4. Java VS JavaScript Code integrated with, and embedded in, HTML. Applets distinct from HTML (accessed from HTML pages). Variable data types not declared (loose typing). Variable data types must be declared (strong typing). Interpreted (not compiled) by client. Compiled on server before execution on client. Much smaller and simpler set of commands . Much larger and advanced set of commands. Netscape Sun Microsystems JavaScript Java
  5. 5. How to Put a JavaScript Into an HTML Page <ul><li>JavaScript is written in the same way as HTML in a text editor (Notepad) </li></ul><ul><li>JavaScript implementation was quite similar to CSS; you can link to outside files (with the file extension .js) , or write blocks of code into your HTML documents with the <script> tag </li></ul>
  6. 6. <ul><li><html> </li></ul><ul><li><body> </li></ul><ul><li><script type=&quot;text/javascript&quot;> </li></ul><ul><li>document.write(&quot;HelloWorld!&quot;) </li></ul><ul><li></script> </li></ul><ul><li></body> </li></ul><ul><li></html> </li></ul><ul><li>The above code will produce this output on the HTML page. </li></ul><ul><li>HelloWorld!! </li></ul>
  7. 7. <ul><li>To insert a JavaScript into an HTML page, we use the <script> tag. </li></ul><ul><li>The <script type=&quot;text/javascript&quot;> and </script> tells where the JavaScript starts and ends </li></ul><ul><li>The script tag encloses any script code you want to use </li></ul><ul><li>The type attribute alert the browser to the type of script it is about to deal with, it helps in code interpretation. </li></ul>
  8. 8. <ul><li>The comments around the script are there so that old browsers that don’t understand the script tag won’t display the code as text on the page. </li></ul><ul><li>If the browser can do JavaScript, then it will ignore the comments. </li></ul>
  9. 9. <ul><li><html> </li></ul><ul><li><body> </li></ul><ul><li><script type=&quot;text/javascript&quot;> </li></ul><ul><li>... </li></ul><ul><li></script> </li></ul><ul><li></body> </li></ul><ul><li></html> </li></ul>
  10. 10. <ul><li>The word document.write is a standard JavaScript command for writing output to a page. </li></ul><ul><li>If we had not entered the <script> tag, the browser would have treated the document.write(&quot;Hello World!&quot;) command as pure text, and just write the entire line on the page. </li></ul><ul><li>This will be the output </li></ul>document.write(&quot;Hello World!&quot;)
  11. 11. <ul><li>You can place an unlimited number of scripts in your document, so that you can have scripts in both the body and the head section. </li></ul><html> <head> <script type=“text/javascript”> …… </script> </head> <body> <script type=“text/javascript”> …… </script> </body>
  12. 12. External scripts <ul><li>To import scripts from external JavaScript files, save the code in the text file with the .js extension; without the script tags and comment. </li></ul>
  13. 13. A simple example for external scripts <ul><li>Save as main.html </li></ul><ul><li>Save as hello.js </li></ul><html> <head> <body> <script language=&quot;javascript&quot; type=&quot;text/javascript&quot; src=&quot;hello.js&quot;> </body> </head> </script> var hello = 'Hello World'; document.write(hello);
  14. 14. Output <ul><li>Hello World! </li></ul>
  15. 15. <noscript> tag <ul><li>The noscript element is used to define an alternate content (text) if a script is NOT executed. </li></ul><ul><li>This tag is used for browsers that recognizes the <script> tag, but does not support the script in it. </li></ul><ul><li>If a browser supports scripting, it will not display the text in the noscript element. </li></ul>
  16. 16. Example <ul><li><noscript> </li></ul><ul><li>Your browser does not support JavaScript! </li></ul><ul><li></noscript> </li></ul>
  17. 17. <ul><li><html> </li></ul><ul><li><head> </li></ul><ul><li><body> ... ... <script type=&quot;text/javascript&quot;> <!-- document.write(&quot;Hello World!&quot;) //--> </script> <noscript> </li></ul><ul><li>Your browser does not support JavaScript! </li></ul><ul><li></noscript> ... ... </body> </li></ul><ul><li></head> </li></ul><ul><li></html> </li></ul>
  18. 18. Object in JavaScript <ul><li>JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define your own objects and make your own variable types. </li></ul><ul><li>We will only look at the built-in JavaScript objects, and how they are used. The next slides will explain each built-in JavaScript object in detail. </li></ul><ul><li>Note that an object is just a special kind of data. An object has properties and methods. </li></ul>
  19. 19. Object in JavaScript The concept of Object Hierarchy in JavaScript can be illustrated by the above diagram. The window itself is an object that have document in it. In document it has another object such as images and forms. Each of these objects have its own properties and methods.
  20. 20. Object in JavaScript - properties <ul><li>Properties are the values associated with an object. </li></ul><ul><li>Below examples shows how to access length property of document object to return the number of characters in a string. </li></ul><ul><li><script type=&quot;text/javascript&quot;> </li></ul><ul><li>var txt=&quot;Hello World!“ </li></ul><ul><li>document.write(txt.length) </li></ul><ul><li></script> </li></ul><ul><li>The output of the code above will be: </li></ul><ul><li>12 ( H e l l o [space] W o r l d ! ) </li></ul>
  21. 21. Object in JavaScript - methods <ul><li>Methods are the actions that can be performed on objects. </li></ul><ul><li>In the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters: </li></ul><ul><li><script type=&quot;text/javascript&quot;> </li></ul><ul><li>var str=&quot;Hello world!&quot; </li></ul><ul><li>document.write(str.toUpperCase()) </li></ul><ul><li></script> </li></ul><ul><li>The output of the code above will be: </li></ul><ul><li>HELLO WORLD! </li></ul>
  22. 22. The most commonly used JavaScript objects Focus, blur, select defaultValue, name, type, value Text Submit, reset Action, elements, encoding, FileUpload, method, name, target Form None Border, complete, heigth, hspace, lowwsrc, vspace, width Image Clear, close, open, write, writeln alinkColor, anchors, applets, ares, bgColor, cookie, fgColor, forms, images, lastModified, linkColor, links, location, referrer, title, vlinkColor Documents javaEnabled appCodeName, appName, appVersion, mimeTypes, plugins, userAgents Navigator Back Length, forward, go History Reload, replace Hash, host, hostname, href, pathname, por, protocol, search Location Alert, blur, close, confirm, focus, open, prompt, clearTimeout, setTimeout defaultStatus, frames, opener, parent, scroll, self, status, top, window Frame Alert, blur ,close, confirm, focus, open, prompt, clearTimeout, setTimeout defaultStatus, frames, opener, parent, scroll, self, status, top, window Window Methods Properties Object
  23. 23. The most commonly used Built-in JavaScript Objects Methods Properties Objects Anchor, big, blink, bold, charAt, fixed, fontColor, fontSize, indexOf, italics, lastIndexOf, link, small, split, strike, sub, substring, sup, toLowerCase,toUpperCase Length, Prototype String getDate, getDay, getHours, getMinutes, getMonth, getSeconds, getTime, getTimeZoneoffset, getYear, parse, prototype, setDate, setHours, setMinutes, setMonth, setSeconds, setTime, setYear, toGMTString, toLocaleString, UTC None Date Join, reverse, sort xx Length Array
  24. 24. Built-in JavaScript Objects <ul><li>String Object </li></ul><ul><li>Date Object </li></ul><ul><li>Array Object </li></ul><ul><li>Math Object </li></ul><ul><li>Boolean Object </li></ul>
  25. 25. <ul><li>The String object is used to manipulate a stored piece of text. </li></ul><ul><li>The following example uses the length property of the String object to find the length of a string: </li></ul><ul><li><script type=&quot;text/javascript&quot;> </li></ul><ul><li>var txt=&quot;Hello World!” </li></ul><ul><li>document.write(txt.length) </li></ul><ul><li></script> </li></ul><ul><li>The above code will result in following output: </li></ul><ul><li>12 </li></ul>Built-in JavaScript Objects - String
  26. 26. <ul><li>The Date object is used to work with dates and times. </li></ul><ul><li>Example below shows how to use Date() method to get today’s date: </li></ul><ul><li><script type=&quot;text/javascript&quot;> </li></ul><ul><li>document.write(Date()) </li></ul><ul><li></script> </li></ul><ul><li>The output will be: </li></ul><ul><li>Mon Nov 05 15:51:51 2007 </li></ul>Built-in JavaScript Objects - Date
  27. 27. <ul><li>This 2 nd example shows how to use getTime() method to calculate years since 1970: </li></ul><ul><li><script type=&quot;text/javascript&quot;> </li></ul><ul><li>var minutes = 1000*60 </li></ul><ul><li>var hours = minutes*60 </li></ul><ul><li>var days = hours*24 </li></ul><ul><li>var years = days*365 </li></ul><ul><li>var d = new Date() </li></ul><ul><li>var t = d.getTime() </li></ul><ul><li>var y = t/years </li></ul><ul><li>document.write(&quot;It's been: &quot; + y + &quot; years since 1970/01/01!&quot;) </li></ul><ul><li></script> </li></ul><ul><li>The output will be: </li></ul><ul><li> It's been: 37.86941401639396 years since 1970/01/01! </li></ul>Built-in JavaScript Objects - Date
  28. 28. <ul><li>The Array object is used to store a set of values in a single variable name. </li></ul><ul><li>1. We create a new Array by assigning it to a new keyword, myArray: </li></ul><ul><li>var mycars=new Array() </li></ul><ul><li>mycars[0]=“Lotus&quot; </li></ul><ul><li>mycars[1]=&quot;Volvo&quot; </li></ul><ul><li>mycars[2]=&quot;BMW&quot; </li></ul><ul><li>OR </li></ul><ul><li>var mycars=new Array(&quot;Saab&quot;,&quot;Volvo&quot;,&quot;BMW&quot;) </li></ul>Built-in JavaScript Objects - Array
  29. 29. <ul><li>2. We can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0. </li></ul><ul><ul><ul><li>The following code line: </li></ul></ul></ul><ul><ul><li>document.write(mycars[0]) </li></ul></ul><ul><ul><ul><li>will result in the following output: </li></ul></ul></ul><ul><li>Lotus </li></ul><ul><li>3. To modify a value in an existing array, just add a new value to the array with a specified index number and then try to access it: </li></ul><ul><li>mycars[0]=“Lexus” </li></ul><ul><li>document.write(mycars[0]) </li></ul><ul><li>will result in the following output: </li></ul><ul><li>Lexus </li></ul>Built-in JavaScript Objects - Array
  30. 30. <ul><li>The Math object allows you to perform common mathematical tasks. </li></ul><ul><li>The Math object includes several mathematical values and functions. You do not need to define the Math object before using it. </li></ul>Built-in JavaScript Objects - Math
  31. 31. <ul><li>JavaScript provides 8 mathematical values (constants) that can be accessed from the Math object. </li></ul><ul><li>These are: E, PI, square root of 2, square root of 1/2, natural log of 2, natural log of 10, base-2 log of E, and base-10 log of E. </li></ul><ul><li>You may reference these values from your JavaScript like this: </li></ul><ul><li>Math.E </li></ul><ul><li>Math.PI </li></ul><ul><li>Math.SQRT2 </li></ul><ul><li>Math.SQRT1_2 </li></ul><ul><li>Math.LN2 </li></ul><ul><li>Math.LN10 </li></ul><ul><li>Math.LOG2E </li></ul><ul><li>Math.LOG10E </li></ul>Built-in JavaScript Objects – Math - values
  32. 32. <ul><li>In addition to the mathematical values that can be accessed from the Math object there are also several functions (methods) available. </li></ul><ul><li>The following example uses the round() method of the Math object to round a number to the nearest integer: </li></ul><ul><li>document.write(Math.round(4.7)) </li></ul><ul><li>The code above will result in the following output: </li></ul><ul><li> 5 </li></ul>Built-in JavaScript Objects – Math - methods
  33. 33. <ul><li>The Boolean object is an object wrapper for a Boolean value. </li></ul><ul><li>The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false). </li></ul><ul><li>We define a Boolean object with the new keyword. The following code line defines a Boolean object called myBoolean: </li></ul><ul><li>var myBoolean=new Boolean() </li></ul>Built-in JavaScript Objects - Boolean
  34. 34. <ul><li>If the Boolean object has no initial value or if it is 0, -0, null, &quot;&quot;, false, undefined, or NaN, the object is set to false. Otherwise it is true (even with the string &quot;false&quot;). </li></ul><ul><li>Example of Boolean object with initial value of false : </li></ul><ul><li>var myBoolean=new Boolean() </li></ul><ul><li>var myBoolean=new Boolean(0) </li></ul><ul><li>var myBoolean=new Boolean(null) </li></ul><ul><li>var myBoolean=new Boolean(&quot;&quot;) </li></ul><ul><li>var myBoolean=new Boolean(false) </li></ul><ul><li>var myBoolean=new Boolean(NaN) </li></ul><ul><li>Example of Boolean object with initial value of true : </li></ul><ul><li>var myBoolean=new Boolean(true) </li></ul><ul><li>var myBoolean=new Boolean(&quot;true&quot;) </li></ul><ul><li>var myBoolean=new Boolean(&quot;false&quot;) </li></ul><ul><li>var myBoolean=new Boolean(&quot;Richard&quot;) </li></ul>Built-in JavaScript Objects - Boolean
  35. 35. How to create an object? <ul><li>Create a direct instance of an object </li></ul><ul><li>Create template of an object </li></ul>
  36. 36. Object A bird (object) Fly () name age EyeColor Eat() Drink() METHODS PROPERTIES
  37. 37. <ul><li>1. Direct Instance </li></ul><ul><li>Add few properties to the bird </li></ul><ul><li>BirdObj=new Object() </li></ul><ul><li>“MorningBird“ </li></ul><ul><li>BirdObj.age=2 </li></ul><ul><li>BirdObj.eyecolor=“green&quot; </li></ul><ul><li>Add methods to the bird = fly </li></ul><ul><li> = eat </li></ul><ul><li>BirfObj.Breath = breath </li></ul>
  38. 38. <ul><li>2. Create Template to the object </li></ul><ul><li>function Bird(name,age,eyecolor) </li></ul><ul><li>{ </li></ul><ul><li>this.age=age </li></ul><ul><li>this.eyecolor=eyecolor </li></ul><ul><li>} </li></ul><ul><li>When you have template, then you can create new instance of the object : </li></ul><ul><li>myBird= new Bird (“Parrot”, 2, “blue”) </li></ul>
  39. 39. <ul><li>You can also add some methods to the bird object. This is also done inside the template: </li></ul><ul><li>function Bird(name,age,eyecolor) </li></ul><ul><li>{ </li></ul><ul><li>this.age=age this. </li></ul><ul><li>eyecolor=eyecolor </li></ul><ul><li>this.habitat = habitat  new method </li></ul><ul><li>} </li></ul><ul><li>That methods are just functions attached to objects. Then we will have to write the habitat() function: </li></ul><ul><li>function habitat(new_habitat) </li></ul><ul><li>{ </li></ul><ul><li>this.habitat=new_habitat </li></ul><ul><li>} </li></ul><ul><li>Eg : </li></ul><ul><li>myBird.habitat(“Pond”) </li></ul>
  40. 40. DOM: What is it? <ul><li>DOM Specification: </li></ul><ul><li>“ a platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure and style of documents . … [DOM] provides a standard set of objects for representing HTML and XML documents , a standard model of how these objects can be combined, and a standard interface for accessing and manipulating them.” </li></ul>
  41. 41. DOM: Implementations <ul><ul><li>Java-based parsers (e.g. Sun Project X, IBM XML4J, Apache Xerces) </li></ul></ul><ul><ul><li>MS IE5 browser: COM programming interfaces for C/C++ and MS Visual Basic, ActiveX object programming interfaces for script languages </li></ul></ul>
  42. 42. Object-based document modelling <ul><li>Object model covers </li></ul><ul><ul><li>structure of a document </li></ul></ul><ul><ul><li>behaviour of a document and its constituent objects </li></ul></ul><ul><li>DOM defines </li></ul><ul><ul><li>interfaces and objects for representing and manipulating documents </li></ul></ul><ul><ul><li>semantics of these interfaces </li></ul></ul><ul><ul><li>relationships between interfaces and objects </li></ul></ul>
  43. 43. DOM structure model <ul><li>Based on O-O concepts: </li></ul><ul><ul><li>methods (to access or change object’s state) </li></ul></ul><ul><ul><li>interfaces (declaration of a set of methods) </li></ul></ul><ul><ul><li>objects (encapsulation of data and methods) </li></ul></ul><ul><li>Roughly similar to the XSLT/XPath data model </li></ul><ul><li> a parse tree </li></ul>
  44. 44. <invoice> <invoicepage form=&quot;00&quot; type=&quot;estimatedbill&quot;> <addressee> <addressdata> <name>Leila Laskuprintti</name> <address> <streetaddress>Pyynpolku 1 </streetaddress> <postoffice>70460 KUOPIO </postoffice> </address> </addressdata> </addressee> ... XML DOM structure model invoice invoicepage name addressee addressdata address form=&quot;00&quot; type=&quot;estimatedbill&quot; Leila Laskuprintti streetaddress postoffice 70460 KUOPIO Pyynpolku 1 Document Element NamedNodeMap Text
  45. 45. HTML DOM structure model The DOM presents an HTML document as a tree-structure (a node tree), with elements, attributes, and text.
  46. 46. <ul><li>The application support and intermediate DOM which existed before the creation of DOM Level 1. </li></ul><ul><li>Example include the DHTML object model or the Netscape intermediate DOM. </li></ul><ul><li>Level 0 is not a formal specification published by the W3C but rather a short hand that refers to what existed before the standardization process. </li></ul>Structure of DOM Level 0
  47. 47. Structure of DOM Level 1 <ul><li>Two parts: </li></ul><ul><li>I: DOM Core Interfaces </li></ul><ul><ul><li>Fundamental interfaces </li></ul></ul><ul><ul><ul><li>low-level interfaces to structured documents </li></ul></ul></ul><ul><ul><li>Extended interfaces (next page) </li></ul></ul><ul><ul><ul><li>XML specific: CDATASection, DocumentType, Notation, Entity, EntityReference, ProcessingInstruction </li></ul></ul></ul><ul><li>II: DOM HTML Interfaces </li></ul><ul><ul><li>more convenient to access HTML documents </li></ul></ul><ul><li>Level 1 intentionally limited to representation and manipulation of document structure and content </li></ul><ul><ul><li>document instance only; no access to the contents of a DTD </li></ul></ul>
  48. 48. DOM Level 2 <ul><ul><li>support for namespaces </li></ul></ul><ul><ul><li>accessing elements by ID attribute values </li></ul></ul><ul><ul><li>optional features </li></ul></ul><ul><ul><ul><li>interfaces to document views and stylesheets </li></ul></ul></ul><ul><ul><ul><li>an event model (for, say, user actions on elements) </li></ul></ul></ul><ul><ul><ul><li>methods for traversing the document tree and manipulating regions of document (e.g., selected by the user of an editor) </li></ul></ul></ul>
  49. 49. <ul><li>Consists of 6 different specifications: </li></ul><ul><li>DOM Level 3 Core; </li></ul><ul><li>DOM Level 3 Load and Save </li></ul><ul><li>DOM Level 3 XPath; </li></ul><ul><li>DOM Level 3 Views and Formatting; </li></ul><ul><li>DOM Level 3 Requirements; and </li></ul><ul><li>DOM Level 3 Validation, which further enhances the DOM </li></ul>DOM Level 3
  50. 50. Core Interfaces: Node & its variants Node Comment DocumentFragment Attr Text Element CDATASection ProcessingInstruction CharacterData Entity DocumentType Notation EntityReference “ Extended interfaces” Document
  51. 51. DOM interfaces: Node invoice invoicepage name addressee addressdata address form=&quot;00&quot; type=&quot;estimatedbill&quot; Leila Laskuprintti streetaddress postoffice 70460 KUOPIO Pyynpolku 1 Node getNodeType getNodeValue getOwnerDocument getParentNode hasChildNodes getChildNodes getFirstChild getLastChild getPreviousSibling getNextSibling hasAttributes getAttributes appendChild(newChild) insertBefore(newChild,refChild) replaceChild(newChild,oldChild) removeChild(oldChild) Document Element NamedNodeMap Text
  52. 52. invoice invoicepage name addressee addressdata address form=&quot;00&quot; type=&quot;estimatedbill&quot; Leila Laskuprintti streetaddress postoffice 70460 KUOPIO Pyynpolku 1 Document getDocumentElement createAttribute(name) createElement(tagName) createTextNode(data) getDocType() getElementById(IdVal) Node DOM interfaces: Document Document Element NamedNodeMap Text
  53. 53. DOM interfaces: Element invoice invoicepage name addressee addressdata address form=&quot;00&quot; type=&quot;estimatedbill&quot; Leila Laskuprintti streetaddress postoffice 70460 KUOPIO Pyynpolku 1 Element getTagName getAttributeNode(name) setAttributeNode(attr) removeAttribute(name) getElementsByTagName(name) hasAttribute(name) Node Document Element NamedNodeMap Text
  54. 54. Additional Core Interfaces <ul><li>to handle ordered lists of nodes: NodeList </li></ul><ul><ul><li>e.g. from Node.childNodes or Element.getElementsByTagName(&quot;name&quot;) </li></ul></ul><ul><ul><ul><li>all descendant elements of type &quot;name&quot; in document order </li></ul></ul></ul><ul><li>to access unordered sets of nodes by name: NamedNodeMap </li></ul><ul><ul><li>e.g. from Node.attributes </li></ul></ul><ul><li>NodeList s and NamedNodeMap s are &quot;live&quot;: </li></ul><ul><ul><li>changes to the document structure reflected to their contents </li></ul></ul>
  55. 55. Object Creation in DOM <ul><li>Each DOM object X lives in the context of a Document: X .ownerDocument </li></ul><ul><li>Objects implementing interface Y are created by factory methods D .create Y (…) , where D is a Document object. E.g: </li></ul><ul><ul><li>createElement(&quot;A&quot;), createAttribute(&quot;href&quot;), createTextNode(&quot;Hello!&quot;) </li></ul></ul><ul><li>Creation and persistent saving of Document s left to be specified by implementations </li></ul>
  56. 56. The main routine for BuildXml <ul><li>public static void main(String args[]){ if (args.length > 0) { </li></ul><ul><li>String fileName = args[0]; </li></ul><ul><li>BuildXml buildXml = new BuildXml(fileName); </li></ul><ul><li>} else { </li></ul><ul><li>System.err.println( &quot;Give filename as argument&quot;); </li></ul><ul><li>}; </li></ul><ul><li>} // main </li></ul>
  57. 57. JavaScript <ul><li>What is JavaScript? </li></ul><ul><li>JavaScript was designed to add interactivity to HTML pages </li></ul><ul><li>JavaScript is a scripting language </li></ul><ul><li>A scripting language is a lightweight programming language </li></ul><ul><li>A JavaScript consists of lines of executable computer code </li></ul><ul><li>A JavaScript is usually embedded directly into HTML pages </li></ul><ul><li>JavaScript is an interpreted language (means that scripts execute without preliminary compilation) </li></ul><ul><li>Everyone can use JavaScript without purchasing a license </li></ul>
  58. 58. What can a JavaScript Do? <ul><li>JavaScript gives HTML designers a programming tool </li></ul><ul><li>HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small &quot;snippets&quot; of code into their HTML pages </li></ul><ul><li>JavaScript can put dynamic text into an HTML page </li></ul><ul><li>A JavaScript statement like this: document.write(&quot;<h1>&quot; + name + &quot;</h1>&quot;) can write a variable text into an HTML page </li></ul><ul><li>JavaScript can react to events </li></ul><ul><li>A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element </li></ul>
  59. 59. <ul><li>JavaScript can be used to detect the visitor's browser </li></ul><ul><li>A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser </li></ul><ul><li>JavaScript can be used to create cookies </li></ul><ul><li>A JavaScript can be used to store and retrieve information on the visitor's computer </li></ul><ul><li>JavaScript can read and write HTML elements </li></ul><ul><li>A JavaScript can read and change the content of an HTML element </li></ul><ul><li>JavaScript can be used to validate data </li></ul><ul><li>A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing </li></ul>
  60. 60. HTML Node Hierarchy
  61. 61. How Javascript Interact With HTML DOM The primary use of JavaScript is to write functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page. Some simple examples of this usage are: A) Opening or popping up a new window with programmatic control over the size, position and 'look' of the new window (i.e. whether the menus, toolbars, etc. are visible). B) Validation of web form input values to make sure that they will be accepted before they are submitted to the server. C) Changing images as the mouse cursor moves over them: This effect is often used to draw the user's attention to important links displayed as graphical elements.
  62. 62. Javascript Objects Description Object Contains the visited URLs in the browser window History Contains information about the current URL Location Contains information about the client's display screen Screen Contains information about the client's browser Navigator Represents a browser window. A that is created automatically with every instance of a <body> or <frameset> tag Window
  63. 63. HTML DOM Objects Represent an <option> element / selection list in an HTML document. Option / Select Represents an <a> element Anchor Represents a <form> element Form Represents the state of an event Event Represents an <img> element Image Represents a <frame>/<frameset> element Frame / frameset Represent a <table>, <td> and <tr> element. Table, TableHeader, TableRow Represents the entire HTML document and can be used to access all elements in a page. Document Description Object
  64. 64. Adding in a new element <ul><li>var link = document.createElement('a'); link.setAttribute('href', 'mypage.htm'); </li></ul>
  65. 65. locating a slot in the document <ul><li>by location: </li></ul><ul><ul><li>document.childNodes[1].childNodes[0] </li></ul></ul><ul><ul><li>Find the main document element (HTML), and find its second child (BODY), then look for its first child (DIV) </li></ul></ul><ul><li>by ID: </li></ul><ul><ul><li>document.getElementById('myDiv').appendChild(txt); </li></ul></ul>
  66. 66. Hiding an element <ul><li>document.childNodes[1].childNodes[1].childNodes[0].style.display = &quot;none&quot;; </li></ul>
  67. 67. Loading an XML document object into the parser <ul><li><script language=&quot;JavaScript&quot;> var xmlDoc = new ActiveXObject(&quot;Microsoft.XMLDOM&quot;) xmlDoc.async=&quot;false&quot; xmlDoc.load(&quot;note.xml&quot;) // ....... processing the document goes here </script> </li></ul>
  68. 68. Manually loading XML into the parser <ul><li><script language=&quot;JavaScript&quot;> // load up variable var with some xml var text=&quot;<note>&quot; text=text+&quot;<to>John</to><from>Robert</from>&quot; text=text+&quot;<heading>Reminder</heading>&quot; text=text+&quot;<body>Don't forget your homework!</body>&quot; text=text+&quot;</note>&quot; // now create the DO var xmlDoc = new ActiveXObject(&quot;Microsoft.XMLDOM&quot;) xmlDoc.async=&quot;false&quot; xmlDoc. loadXML (text) // ....... process the document </script> </li></ul>
  69. 69. parseError object <ul><li>document.write(xmlDoc.parseError. property ) </li></ul><ul><ul><li>errorCode : Returns a long integer error code </li></ul></ul><ul><ul><li>reason : Returns a string explaining the reason for the error </li></ul></ul><ul><ul><li>line : Returns a long integer representing the line number for the error </li></ul></ul><ul><ul><li>linePos : Returns a long integer representing the line position for the error </li></ul></ul><ul><ul><li>srcText : Returns a string containing the line that caused the error </li></ul></ul><ul><ul><li>url : Returns the url pointing the loaded document </li></ul></ul><ul><ul><li>filePos : Returns a long integer file position of the error </li></ul></ul>
  70. 70. Traversing nodes <ul><li>set xmlDoc=CreateObject(&quot;Microsoft.XMLDOM&quot;) xmlDoc.async=&quot;false&quot; xmlDoc.load(&quot;note.xml&quot;) for each x in xmlDoc.documentElement.childNodes document.write(x.nodename) document.write(&quot;: &quot;) document.write(x.text) next </li></ul>
  71. 71. Calling XML nodes by name <ul><li>var xmlDoc = new ActiveXObject(&quot;Microsoft.XMLDOM&quot;) xmlDoc.async=&quot;false&quot; xmlDoc.load(&quot;note.xml&quot;) document.write(xmlDoc.getElementsByTagName(&quot;from&quot;).item(0).text) </li></ul>