JavaScript History First web scripting language Developed by Netscape and Sun Initiated by Netscape and called LiveScript In parallel with this, Sun was developing Java JavaScript 2 History Netscape and Sun got together and realized that many of the specifications for Java could apply to LiveScript Result is JavaScript JavaScript 3 JavaScript Versus Java JavaScript is interpreted while Java is compiled – But server-side JavaScript is compiled JavaScript is object-based while Java is object-oriented – Object-based languages can utilize predefined objects, but you are limited in terms of creating your own objects JavaScript 4 JavaScript Versus Java JavaScript has loose data typing, while Java has strong data typing – Loose data typing means that a variable can hold any kind of data JavaScript JavaScript code is embedded in an HTML document while Java applets are stand-alone applications that can be accessed from HTML 5 JavaScript Versus Java JavaScript has dynamic binding, while Java has static binding – Names bound at runtime JavaScript JavaScript can access browser objects and functionality, while Java cannot 6 Client-Side JavaScript JavaScript Client-side JavaScript scripts operate on a client running Netscape Navigator (Microsoft Internet Explorer also supports it now) and are interpreted by Netscape Navigator 7 Client-Side JavaScript Detect whether the browser supports a certain plug-in Control a plug-in Validate user form input Prompt a user for confirmation Perform post-processing of information retrieved from server-side JavaScript scripts JavaScript 8 Server-Side JavaScript JavaScript scripts that run on the server are called LiveWire applications because they use the Netscape LiveWire development environment – This is the only system that supports server-side JavaScript development JavaScript 9 Server-Side JavaScript Unlike CGI scripts, LiveWire applications are more closely integrated to the HTML pages that control them – Can have a page that accepts credit card payments and gives user immediate feedback on the same page about whether card was accepted JavaScript 10 Client Scripts To display error or information boxes To validate user input To display confirmation boxes To process server data, such as aggregate calculations To add programmable logic to HTML JavaScript 11 Client Scripts To perform functions that don’t require information from the server To produce a new HTML page without making a request to the server JavaScript 12 Server Scripts To maintain data shared among applications or clients To maintain information during client accesses To access a database To access server files To call server C libraries To customize Java applets JavaScript 13 Scripts Client-side and server-side JavaScript scripts are both embedded in an HTML file For server-side JavaScript scripts, this HTML file is compiled with the LiveWire compiler – Creates a file that is in a platformindependent and compiled bytecode format JavaScript 14 Scripts Client-side JavaScript needs Netscape Navigator and a standard HTML server Server-side JavaScript needs the LiveWire compiler, the LiveWire Application Manager, and a Netscape HTML server that supports the LiveWire server extension JavaScript 15 Scripts Examples js1.htm, js2.htm, js3.htm The <head> portion of an HTML page is the first to load, so it is best to define the functions for a page in this portion – Functions can be called in the <body> portion JavaScript 16 JavaScript Program Code Main body Event handlers Functions JavaScript 17 Main Body Main Body – Any code that is between <script> and </script> that is not a function definition JavaScript 18 Events Events – Mouse click – Re-sizing window JavaScript 19 Event Handlers Event handlers – Scripts that link events to JavaScript functions – Embed in HTML documents as attributes of HTML tags JavaScript <tag eventHandler = “JavaScript Code”> Example js4.htm 20 More Events Top-level actions causing change in web page being displayed – Navigation – Interaction with an element of an HTML form JavaScript 21 Navigation Selecting a hypertext link Moving forward or backward in the history list Opening a new URL Quitting the browser JavaScript 22 Navigation In these events, some page is being loaded or unloaded – These are document-level events that can be handled by JavaScript JavaScript 23 JavaScript Events button – click checkbox – click document – load – unload JavaScript 24 JavaScript Events form – submit link – click – mouseover radio – click JavaScript 25 JavaScript Events selection – blur – change – focus submit – click JavaScript 26 JavaScript Events text – change – focus A text field is said to have focus when it is currently accepting typed input Clicking anywhere inside a text item gives it focus Moving the mouse over the text field may give it focus – blur The opposite of focus – select JavaScript 27 JavaScript Events textarea – blur – change – focus – select JavaScript 28 Functions JavaScript Defining a function to create an object function house(rms, stl, yr, gar){ this.rooms = rms; this.style = stl; this.yearBuilt = yr; this.hasGarage = gar; } var myhouse = new house(8, “Ranch”, 1990, true) 29 Functions Every object is an array of its property values and every array is an object – 0-based indexing Thus, – myhouse[0] – myhouse[1] – myhouse[2] – myhouse[3] JavaScript =8 = “Ranch” = 1990 = true 30 Functions Every object is also an associative array Thus, – myhouse[“rooms”] = 8 – myhouse[“style”] = “Ranch” – myhouse[“yearBuilt”] = 1990 – myhouse[“hasGarage”] = true JavaScript 31 Functions Can dynamically instance extend an object yourhouse = new house(12, “Tudor”, 1934, true); yourhouse.hasPorch = “false”; yourhouse.windows = 46; – Doesn’t affect other object instances nor the object itself JavaScript 32 Functions A variable-length array-of-strings object function stringarr(howMany, initStr) { this.length = howMany; for (var j = 1; j <= howMany; j++) { this[j] = initStr; } } JavaScript 33 for..in Statement for (varName in objName) { forBody } JavaScript varName takes on the successive property names of the object objName 34 for..in Statement function showAny(anyObj) { for (var iter in anyObj) { document.write(“<br>Property ” + iter + “ is ” + anyObj[iter]); } document.write(“<br>”); } JavaScript 35 Methods function house(rms, stl, yr, garp) { this.length = 5; this.rooms = rms; this.style = stl; this.yearBuilt = yr; this.hasGarage = gar; this.show = mshowHouse; } JavaScript 36 Methods function mshowHouse( ) { var nprops = this.length; for (var iter = 1; iter < nprops; iter++) { document.write(“<br>Property ” + iter + “ is ” + this[iter]); } document.write(“<br>”); } myhouse.show( ); JavaScript 37 Techniques for Including JavaScript Code in HTML Embed script between <script> and </script> Event-handler functions Through the javascript: URL pseudoprotocol The JavaScript HTML entity – &lt JavaScript 38 The <script>…</script> Tags <script>-tag may appear in head or body The language attribute is optional <script language = // JavaScript code </script> JavaScript “JavaScript”> – Works for both Navigator 2.0 and Navigator 3.0 – language = “JavaScript1.1” works only for Navigator 3.0 39 The <script>…</script> Tags JavaScript is not the only language to use the <script>-tag <script language = “VBScript”> ' VBScript code </script> JavaScript language is the default scripting – Can leave out the language attribute JavaScript 40 The <script>…</script> Tags An HTML document may contain more than one pair of non-overlapping <script> and </script>-tags – Statements executed in order of appearance – They constitute part of the same JavaScript program, however <script> var x = 1; </script> … <script> document.write(x); </script> JavaScript 41 The <script>…</script> Tags Selectively displaying text in JavaScriptignorant browsers <script language = “none”> Your browser doesn’t JavaScript. This page won’t work for you. </script> JavaScript understand 42 The <script>…</script> Tags JavaScript Selectively displaying text in JavaScriptignorant browsers – Browsers that recognize the <script>-tag will know there is no such language as none and will ignore everything between the <script> and <script>-tags – Browsers that don’t understand the <script> and </script>-tags will ignore them and display the two lines in-between them 43 The <script>…</script> Tags Including JavaScript files <script src = “../../javascript /prog.js”> </script> – Simplifies your HTML files – Can share JavaScript among different HTML files JavaScript 44 The <script>…</script> Tags Including JavaScript files – When they are used by more than one HTML file, this allows them to be cached by the browser, allowing them to load more quickly JavaScript The time savings of caching outweighs the delay incurred by the browser opening a network connection to download the JavaScript file 45 The <script>…</script> Tags Including JavaScript files – A JavaScript program from one machine can use code located on other machines – This only works for Netscape 3.0 and higher JavaScript Can include JavaScript code in-between the <script> and </script>-tags for Netscape 2.0 browsers, as this is ignored by Netscape 3.0 browsers if the SRC attribute is defined 46 Event Handler Functions Area – onClick( ), onMouseOver( ), onMouseOut( ) Button – onClick( ) Checkbox – onClick( ) JavaScript 47 Event Handler Functions FileUpload – onBlur( ), onChange( ), onFocus( ) Form – onSubmit( ) Frame – onLoad( ), onUnload( ) Image – onAbort( ), onError( ), onLoad( ) JavaScript 48 Event Handler Functions Link – onClick( ), onMouseOver( ), onMouseOut( ) Radio – onClick( ) Reset – onClick( ) JavaScript Select – onChange( ) 49 Event Handler Functions Submit – onClick( ) Text – onBlur( ), onChange( ), onFocus( ) Textarea – onBlur( ), onChange( ), onFocus( ) Window – onBlur( ), onError( ), onFocus( ), onLoad( ), onUnload( ) JavaScript 50 JavaScript in URL's javascript:function;greeting+name +message; – Multiple statements separated by semicolons – Value of last expression evaluated becomes the document that URL refers to and this value will be formatted and displayed JavaScript 51 JavaScript in URL's javascript:alert(“Hello World!”); – Has side-effect but returns no value – Browser executes the code but doesn’t modify currently displayed document JavaScript 52 JavaScript in URL's Can use void operator to remove returned value and just have side-effect of assignment javascript:void function( ); Microsoft has syntax, <a href = “script-engine:script-code”> – Supports vbscript: JavaScript 53 JavaScript Entities &{JavaScript-statements}; – Can only appear within the value of HTML attributes <body bgcolor = “&{favorite_color( );};”> JavaScript 54 Order of Execution Scripts – JavaScript statements that appear between <script> and </script>-tags are executed in the order they appear – When more than one script appears in a page, they are executed in the order they appear JavaScript 55 Order of Execution Scripts – JavaScript code evaluation occurs as part of the browser’s HTML parsing process JavaScript Thus, if script appears in the <head> portion of an HTML document, none of the <body> of the document will have been defined yet Thus, many JavaScript objects, such as form objects, haven’t as yet been created and cannot be manipulated by this code 56 Order of Execution Functions – Functions shouldn’t be executed before the objects they manipulate exist – Functions should be defined before they are invoked – Can define function to manipulate objects before these objects exist JavaScript 57 Order of Execution Event handlers – May be invoked before a page is fully loaded and parsed In a slow network connection, some links can initially appear and be clicked before page fully loads – Thus, if your event handler invokes functions, you must make sure they are defined JavaScript Put all function definitions in the <head> 58 Order of Execution Event handlers – Also, you must take care that event handlers don’t try to manipulate HTML objects that haven’t been parsed and created JavaScript Can test for manipulated existence of object to be if ((parent.frames[1]) && (parent.frames[1].document) && (parent.frames[1].document.myform)) { … } 59 Order of Execution Event handlers – Also, you must take care that event handlers don’t try to manipulate HTML objects that haven’t been parsed and created Place this small script at very end of document which sets a flag and have event handlers test this flag <script>done_loading=1</script></body></html> JavaScript 60 Order of Execution Event handlers – onLoad( ) and onUnload( ) event handlers In Netscape 3.0, the onLoad( ) handler is executed when document or frameset is fully loaded – When using multiple frames, one doesn’t know in what order the onLoad( ) handler will be invoked for the various frames Handler for child frames can be invoked before handler for parent frame JavaScript 61 Order of Execution Event handlers – onLoad( ) and onUnload( ) event handlers The onUnload( ) handler is executed when user requests the browser to move to some other page and just before the browser leaves current document JavaScript 62 Order of Execution JavaScript URLs – This is not executed when the document containing the URL code is loaded – Only interpreted when the browser tries to load the document to which URL refers JavaScript 63 Order of Execution JavaScript entities – Executed during process of HTML parsing JavaScript 64 JavaScript Object Hierarchy The current window – self, window, Window objects) parent, top (various navigator (navigator object) – plugins[ ] (array of plugin objects) mimeTypes[ ] (array of mimeType objects) var shocked = (navigator.plugins[“Shockwave”] != null); – mimeTypes[ ] (array of mimeType objects) var show_movie=(navigator.mimeTypes[“video/mpeg”] != null); JavaScript 65 JavaScript Object Hierarchy frames[ ] (array of window objects) location (location object) – location.href = “needsjava.html”; history (history object) – <input type=button value = “back” onClick = “history.back( );”> JavaScript 66 JavaScript Object Hierarchy document (document object) – forms[ ] (array of form objects) elements[ ] (array of HTML form element objects) – – – – – – – JavaScript button checkbox fileupload (3.0) hidden password radio reset 67 JavaScript Object Hierarchy document (document object) – forms[ ] (array of form objects) elements[ ] (array of HTML form element objects) – select options[ ] (array of option objects) – submit – text – textarea JavaScript 68 JavaScript Object Hierarchy document (document object) – anchors[ ] (array of anchor objects) – links[ ] (array[ ] of link objects) – images[ ] (array of image objects) (3.0) – applets[ ] (array of JavaObject objects) (3.0) – embeds[ ] (array of JavaObject objects) (3.0) JavaScript 69 JavaScript Object Hierarchy packages (JavaPackage object) – Various JavaPackage objects (3.0) JavaScript and JavaClass 70 JavaScript Objects Built-in objects HTML objects Browser objects JavaScript 71 Built-in Objects string objects date object math object JavaScript 72 string Objects string object formatting methods for HTML – anchor “Bill”.anchor(“anchortext”) – <a name = “anchortext”>Bill</a> – big “Bill”.big( ) – <big>Bill<big> JavaScript 73 string Objects string object formatting methods for HTML – blink “Bill”.blink( ) – <blink>Bill</blink> – bold “Bill”.bold( ) – <b>Bill</b> JavaScript 74 string Objects string object formatting methods for HTML – fixed “Bill”.fixed( ) – <tt>Bill</tt> – fontcolor “Bill”.fontcolor(“blue”) – <font color = “blue”><Bill></font> JavaScript 75 string Objects string object formatting methods for HTML – fontsize “Bill”.fontsize(-1) – <font size = -1>Bill</font> – italics “Bill”.italics( ) – <i>Bill</i> JavaScript 76 string Objects string object formatting methods for HTML – link “Bill”.link(“linktext”) – <a href = “linktext”>Bill</a> – small “Bill”.small( ) – <small>Bill</small> JavaScript 77 string Objects string object formatting methods for HTML – strike “Bill”.strike( ) – <strike>Bill</strike> – sub “Bill”.sub( ) – <sub>Bill</sub> JavaScript 78 string Objects string object formatting methods for HTML – sup “Bill”.sup( ) – <sup>Bill</sup> – toLowerCase “Bill”.toLowerCase( ) – bill JavaScript 79 string Objects string object formatting methods for HTML – toUpperCase “Bill”.toUpperCase( ) – BILL JavaScript 80 string Objects string object methods for displaying subsets of strings – charAt “Bill”.charAt(1) is “i” – indexOf JavaScript “Bill”.indexOf(“il”) is 1 81 string Objects string object methods for displaying subsets of strings – lastIndexOf “Bill”.lastIndexOf(“l”) is 3 – substring “Bill”.substring(1,2) is “il” – length JavaScript “Bill”.length is 4 82 date Object JavaScript See js11.htm 83