javascript browser programming n.
Skip this Video
Loading SlideShow in 5 Seconds..
JavaScript: Browser Programming PowerPoint Presentation
Download Presentation
JavaScript: Browser Programming

JavaScript: Browser Programming

297 Views Download Presentation
Download Presentation

JavaScript: Browser Programming

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. JavaScript: Browser Programming Marek Podgorny, EECS, Syracuse University, and CollabWorx

  2. Outline • Java vs. JavaScript, Interpreters vs. Compilers • JavaScript Basics and Syntax • JavaScript and Document Object Model • JavaScript Methods • JavaScript and HTML reflection CPS606, Fall 2002, EECS SU & CollabWorx

  3. General Remarks • JavaScript is a web scripting language for browsers • Invented by Netscape and “innovated” by Microsoft • Standardized as ECMA language • Netscape server-side JavaScript exists (Livewire) but obsolete • JavaScript facilitates rapid prototyping of Web pages and it takes load off the the server • Particularly useful for processing HTML forms • JavaScript is also enabler of DHTML • References: JavaScript, The Definitive Guide by David Flanagan (O’Reilly, 1998); The JavaScript Bible by Danny Goodman (IDG, 1998); Dynamic HTML, The Definitive Reference by Danny Goodman (O’Reilly, 1998). CPS606, Fall 2002, EECS SU & CollabWorx

  4. Why would you use JavaScript? • Typically JavaScript is invoked from HTML • HTML text and JavaScript text are intertwined • JavaScript allows you to modify Web page after it was downloaded form server • If you need to make a dynamic page from C++, Perl, or Java you must write the HTML from these languages • You can invoke applets from HTML but HTML and applet actions are (typically) not linked • HTML and JavaScript are closely linked • JavaScript can be seen as API to the browser • This is since JavaScript can interact with browser objects CPS606, Fall 2002, EECS SU & CollabWorx

  5. Sun’s Java is fast becoming a broad industry standard Java is well designed and documented Java is object-oriented with (single) inheritance Java is class-based JavaScript is primarily supported by Netscape and Microsoft JavaScript started quite “roughly” but is improving in design -- however some issues connected to browser are totally ill defined as browser ill defined -- e.g. what happens in what order when frames loaded …. JavaScript is object-based with no class structure JavaScript is prototype-based Java vs. JavaScript I CPS606, Fall 2002, EECS SU & CollabWorx

  6. Java classes and instances are distinct A Java class has zero or more constructors Java property inheritance follows class hierarchy In Java, no way to add properties at run-time JS object definition and constructor are identical and defined like methods JavaScript property inheritance follows prototype chain JavaScript properties may be added or removed at run-time So essentially in JS, class structure is totally dynamic (a.k.a. Ill defined) Java vs. JavaScript (2) CPS606, Fall 2002, EECS SU & CollabWorx

  7. Java applets are distinct from HTML Java is strongly typed with static (compile-time) binding Java bytecode is interpreted (or “Just-In-Time” compiled) on the client JavaScript is tightly coupled with HTML JavaScript is loosely typed with dynamic (run-time) binding High-level JavaScript source code is interpreted on the client but is often MUCH faster than Java as integrated into browser Java vs. JavaScript (3) CPS606, Fall 2002, EECS SU & CollabWorx

  8. Java vs. JavaScript (4) • Java applet deployment cycle • Java source --> javac compiler --> JavaVM Universal Machine code in .class file • Store JavaVM .class files on Web Server • Download JavaVM from Server to Client • Interpreter built into browser, reads JavaVM and executes on client • Java event handlers interpret events within applet • JavaScript cycle • JavaScript Source is included in HTML text or special .js files included in HTML files • Combined JavaScript and HTML is downloaded and interpreted by browser on client to produce HTML Page • Events in HTML Page (mouse clicks etc.) are either interpreted by browser default or overridden by user JavaScript code CPS606, Fall 2002, EECS SU & CollabWorx

  9. JavaScript Version History • JavaScript 1.0 debuted in NN 2.0 (Feb 96) • JavaScript 1.1 appeared in NN 3.0 • NN 4.0 (a.k.a. Communicator) supports JavaScript 1.2 • MSIE 3.0 introduced JScript 2.0, a subset of JavaScript 1.1 • JScript 3.x is supported in MSIE 4.0 • JScript 3.0 and later from IE are ECMA-compliant [Standard ECMA-262, June 1997] as is JavaScript 1.1 and following versions from Netscape • JavaScript 1.3 and 1.4 released with modest changes including better exception handling and Java-JavaScript linkage CPS606, Fall 2002, EECS SU & CollabWorx

  10. JavaScript 1.2 • Version 1.2 is the first one “worth using” • New features in JavaScript 1.2 (NN4.0): • Event object and event capturing • Ten new event handlers • Nested functions; new Number() and String() functions • New statements: switch and do…while • Many new methods and properties (especially for Window, String, and Array objects) • Perl4-compatible regular expressions • Signed script security model CPS606, Fall 2002, EECS SU & CollabWorx

  11. JScript 3.1 • JScript 3.1 was released with MS IE v. 4.0: • Conditional execution (meta-statements) • New event handlers (39 in all!) • New statements: switch and do…while • Two new identity operators (=== and !==) which insist on variable types matching (default is to convert types in == and !=) • Perl4-compatible regular expressions • Debugger support • Adequate documentation is lacking, however CPS606, Fall 2002, EECS SU & CollabWorx

  12. ECMAScript • ECMAScript refers to standard ECMA-262 released in June 1997 • Netscape site has ECMAScript standard document • ECMAScript is essentially a definition of JavaScript as programming language, without reference to DOM • Meaning: is the language and not the browser AWT handler • Both Netscape and Microsoft versions are ECMA-compliant but nevertheless mutually incompatible • The HTML and emerging XML Document Object Models (DOMs) will be bound initially to ECMAScript • Hence, one can use ECMAScript in several different domains (HTML, XML, VRML …) by adding support for appropriate domain specific DOMs CPS606, Fall 2002, EECS SU & CollabWorx

  13. JavaScript Basics

  14. JavaScript and HTML <SCRIPT language="javascript"> document.write("This document was last modified on ") document.write(document.lastModified) </SCRIPT> • This example illustrates a few key points: • JavaScript source code can be placed inline with HTML code, contained within the <SCRIPT> and </SCRIPT> tags • JavaScript uses the dot (.) character for object structures • An object may have properties (document.lastModified) and methods (document.write) • JavaScript has many built-in variables and functions for interacting with web page content. CPS606, Fall 2002, EECS SU & CollabWorx

  15. JavaScript and HTML • Besides scripts, JavaScript code can be placed in HTML tags to define event handlers <FORM> <INPUT type="button" value="Push Me" onClick="alert(‘Thank you very much’)"> </FORM> • This HTML creates a button in a form • The mouse click event handler for the button is a single JavaScript statement that displays an alert box with a message • The statement could also be a call to a function you wrote to provide a more useful response CPS606, Fall 2002, EECS SU & CollabWorx

  16. JavaScript URLs <A HREF="JavaScript:JumpTo(dest)"> Go now! </A> • This HTML creates a link that looks like a normal hyperlink • Clicking it runs a JavaScript function called JumpTo, and passes it an argument dest which is presumably a variable that was set by a previous button click or other interaction with the user • The JavaScript:someStatement notation can be used anywhere a normal URL can go • Try interactive console! CPS606, Fall 2002, EECS SU & CollabWorx

  17. JavaScript URLs • A trivial example of a JavaScript URL isjavascript:alert("Hello World!") • A JavaScript URL may appear anywhere an ordinary URL is expected:<A HREF="javascript:history.back()">Previous Page</A> • Note must use <A HREF=”javascript: void(anyoldfunction())”>if you do not want link to be invoked! • Use HREF=“javascript: void(0)” if no action at all -- used if real action from onclick or other event handle for link • Navigator even has a mini-scripting environment invoked by typing javascript: into the browser’s location text field • This is used to display error messages as a console instead of alternative (and clumsy) stream of windows (one per error ….) CPS606, Fall 2002, EECS SU & CollabWorx

  18. Loading scripts from files <SCRIPT SRC=""> alert("Error loading script file.") </SCRIPT> • Please note the alert function that only fires if browser fails to execute the script • Good methodology to store reusable scripts • An external file must have a .js extension and the server must be configured properly CPS606, Fall 2002, EECS SU & CollabWorx

  19. The <SCRIPT> Tag • If you have two versions of a JavaScript script, you can load one or the other: <SCRIPT LANGUAGE="JavaScript1.1"> // Ignored by Navigator 2.0 and higher: location.replace("newVersion.html"); </SCRIPT> <SCRIPT LANGUAGE="JavaScript"> // Read by Navigator 2.0 and above </SCRIPT> CPS606, Fall 2002, EECS SU & CollabWorx

  20. The <SCRIPT> Tag (cont’d) • Multiple <SCRIPT> tags are allowed • Within a single <SCRIPT>, a function may be called before it is defined • Within a single document, a function defined in one <SCRIPT> may not be called from a previous <SCRIPT> • In particular, a function defined in the <BODY> may not be called from the <HEAD> CPS606, Fall 2002, EECS SU & CollabWorx

  21. Data types and declarations • Numbers, strings, true, false, null, and undefined values are known as primitive values • Anything else is an object! • Assigning a primitive to a variable makes a copy, assigning an object makes a reference! • Some objects return primitive values; those that don’t, return the “[object]” string CPS606, Fall 2002, EECS SU & CollabWorx

  22. Variables • Variable is an entity containing data • Variable name must start from a letter or _ • JavaScript is case-sensitive! – but has no fixed type…. • Variable scope • A variable declared inside a function definition using the var keyword, is local to that function • Variables that are not declared inside a function, or that are declared without the var keyword, are global! • A helpful practice is to place all global variable declarations in the <HEAD> section of the HTML • One can reference variables in other windows via win.var syntax CPS606, Fall 2002, EECS SU & CollabWorx

  23. Arrays • Array type is provided for ordered sets of data • Array indexes are represented by expressions in square brackets, such as item[50] • The Array object provides a number of methods for rearranging and converting arrays a = new Array(10) regionName=new Array("North", "Central", "South") regionName.length = 3 row1 = new Array(3) row2 = new Array(3) row3 = new Array(3) grid = new Array(row1, row2, row3) CPS606, Fall 2002, EECS SU & CollabWorx

  24. Arrays with String Indexes var person = new Array() person["firstName"] = "Mary" person["lastName"] = "Jones" person["zipCode"] = 12345 • Arrays with numerical and string indexes are treated separately! – person.length = 0 • person[“firstName”] is equivalent to person.firstname • Ergo, associative arrays are actually objects! CPS606, Fall 2002, EECS SU & CollabWorx

  25. Objects, Properties & Methods • In JavaScript, an object is a structured set of data items, called properties, and code (functions), called methods var person = new Array() person.firstName = "Mary" person.lastName = "Jones" person.age = 34 • Internally, there is no difference between an object and an associative array • However, it is rather inelegant to do it this way… CPS606, Fall 2002, EECS SU & CollabWorx

  26. Constructors • A clearer approach is to write a constructor function for the object, and use the constructor with the new operator: function person(first, last, yrs) { this.firstName = first this.lastName = last this.age = yrs } var Mary = new person("Mary", "Jones", 34) var Bob = new person("Bob", "Lee", 27) Note use of this to access the object by which function is called! Name of the “class” – this is as close as JavaScript gets to the concept of classes CPS606, Fall 2002, EECS SU & CollabWorx

  27. On the fly constructors var girl = {firstName:"Sally", lastName:"Forth", age:16} • These expressions can be nested, as in var family = { dad:{firstName:"George", lastName:"Jones", age:58}, mom: {firstName:"Martha", lastName:"Forth", age:42}, numKids: 2.7 } CPS606, Fall 2002, EECS SU & CollabWorx

  28. Built-in object types (DOM!) All these object types can be used in constructors CPS606, Fall 2002, EECS SU & CollabWorx

  29. External Object • External object types cannot be used in constructors • Browser provides these objects “as needed”, either as a result of reflection process, or the objects are “simply there”: • Anchor, Applet, Area, Button, Checkbox, FileUpload, Form, Frame, Hidden, Link, MimeType, Password, Plugin, Radio, Reset, Select, Submit, Text, Textarea • We will discuss some of these deeper CPS606, Fall 2002, EECS SU & CollabWorx

  30. Values & References • Unlike primitive values, objects are manipulated by references • A reference is a pointer or label that specifies where some actual values are stored var p1 = new person("George", "Smith", 42) p2 = p1 p2.firstName = "Martha" p2.age = 30 • p1 and p2 now refer to the same object, and both now refer to information about Martha! • To create an actual new object, you must use the new operator with a constructor function CPS606, Fall 2002, EECS SU & CollabWorx

  31. More about objects • Objects behave differently from primitive values when used as function arguments • if an argument is an object, a function can modify its properties: function nextYear(p) { p.age++ } This code will actually increment person's age in the object • Deleting Objects • An object can be deleted by setting any variables that reference it to null • To delete specific properties of an object or elements of an array, you can use the delete operator CPS606, Fall 2002, EECS SU & CollabWorx

  32. Properties as objects • A property of an object can itself be an object: • The built-in document object contains a large number of properties pertaining to contents of a web page • Many of these properties are arrays or objects. If your web page contains a form named info, you could refer to it in a script as • Hence, a property of an object can be either a primitive value or another object, and the objects can be nested to an arbitrary depth CPS606, Fall 2002, EECS SU & CollabWorx

  33. Properties as objects • Constructor definition: function job(what, who, yr, mo, dy) { this.title = what this.person = who this.startDate = new Date(yr, mo, dy) } • Object creation: var Joe = new person("Joe", "Zeelane", 46) project1 = new job("Report", Joe, 97, 06, 13) • Resulting object properties: • project1.person, project1.startDate • And primitive values properties: project1.person.firstName CPS606, Fall 2002, EECS SU & CollabWorx

  34. Adding properties to objects • One can add properties to existing objects by using the special prototype property • available for all objects that are created with the new operator, including built-in object types as well as any constructors defined by programmer person.prototype.gender = "" • This statement adds a new property called gender to the person object • All instances of this new property will be set to the specified value • The gender property will be added to person objects that have already been constructed, as well as to any that are created later CPS606, Fall 2002, EECS SU & CollabWorx

  35. Methods • JavaScript methods are functions that are associated with an object. Examples: a.reverse() reverses the order of the elements of an array; string s = a.join(“|") forms a string by combining an array's elements, separated by vertical bars • Methods are always listed at the end of object definition, and followed by (possibly empty) list of arguments in parentheses CPS606, Fall 2002, EECS SU & CollabWorx

  36. Creating a method function personText() { var s = this.firstName+" “+this.lastName +"("+this.age+")" return s } • To make this function a method of person, add a line to your constructor function to assign it: function person(first, last, yrs) { this.firstName = first this.lastName = last this.age = yrs this.formatted = personText } • And use it as follows: document.write(Joe.formatted()) CPS606, Fall 2002, EECS SU & CollabWorx

  37. Universal Methods • There are three methods that are available for all objects: • eval evaluates a string as JavaScript code in the context of the calling object, and returns its value • toString returns a string representing a numeric value in a specified radix • valueOf returns the primitive value of an object • Two other methods are available for large numbers of objects: • constructor() is available for all objects created by constructor functions. It returns the function that created an object • handleEvent() is available for all objects that have event handlers. It calls an event handler for a specific event CPS606, Fall 2002, EECS SU & CollabWorx

  38. JavaScript Entities • One can parameterize HTML using document.write(ln) commands such as: document.writeln(“string1” + Jsvariable + “string2”); • There is another way of achieving this without a <SCRIPT> tag and no document.writeln -- namely <IMG width=“&{JSvar1};” src=“&{JSvar2}” > • where JSvar1 and JSvar2 are JavaScript variables holding width and URL of image • Syntax is modeled on that for special characters where &GT; is > etc. • Such JavaScript Entities can only appear on right hand side of attributes values and cannot appear in HTML text such as titles • document.writeln approach has no such restriction! CPS606, Fall 2002, EECS SU & CollabWorx

  39. Javascript vs. windows • Every script runs in a window • The window object is the "outermost" object in the JavaScript hierarchy • All variables and functions declared in scripts are actually properties and methods of the window • a variable x is actually window.x • The symbol self is equivalent to window • Each window object corresponds to one browser window on the host computer's screen • It is possible to communicate between windows be referring to or setting other window’s variables CPS606, Fall 2002, EECS SU & CollabWorx

  40. Inter-window communication • To open additional windows: var win2 = open("someFile.htm", "newWin", features) • This opens a new browser window, and returns a new window object in the variable win2 • The new window can now be accessed: win2.document.write(someText); win2.toolbar.visible = false; win2.document.close(); • Scripts in win2 can access the original window: opener.win2status = "ready” • Or re-write original window contents: opener.location = “newtext.html”; CPS606, Fall 2002, EECS SU & CollabWorx

  41. Javascript vs. documents • Every window has a documentproperty which manages all text, graphics, and other data displayed in the window • A document object has properties that reflect the HTML elements in the window, like the arrays document.links document.images document.applets document.embeds document.forms CPS606, Fall 2002, EECS SU & CollabWorx

  42. The Image Object • The JavaScript Image object allows scripts to perform some basic operations on images stored in file • Image objects are created automatically when browser encounters <IMG> tags in a document • Scripts can create Image objects and assign them to variables with the new Image() constructor • These objects are not displayed on the screen, but they can be loaded with images from files and later copied to other images that are in the document • Allows you to change an image quickly in response to user actions • You can create simple animation by rapidly sequencing through a series of images CPS606, Fall 2002, EECS SU & CollabWorx

  43. Input/Output • JavaScript provides several types of dialog boxes that can be used with a single statement • These dialogs are all available through methods of the window object • alert(mes) creates an alert box that displays the specified string • confirm(mes) creates a confirm box that displays the specified string and two buttons • Returns true if the user clicks OK, or false if the user clicks Cancel • prompt(mes, default) creates a dialog box displaying string message, a text box and two buttons • The default string is initially displayed in text box; the user may enter other text • If the user clicks OK, prompt returns a string containing the contents of the text box. If the user clicks Cancel, prompt returns null CPS606, Fall 2002, EECS SU & CollabWorx

  44. Forms • HTML forms are a very powerful way to interact with the user of a web page • Originally intended for sending information to servers, but use of JavaScript allows browser to manipulate forms locally in browser • Browser creates Form objects corresponding to all HTML <FORM> tags and stores them as elements of the document.forms array • If the <FORM> tag has a NAME attribute, the Form object can be referenced by its name as a property of document <FORM NAME="userData"> can be referenced as document.userData CPS606, Fall 2002, EECS SU & CollabWorx

  45. Forms 2 • A form contains interactive elements such as buttons and text boxes • Browser creates objects for each type of form element and stores them in elements array • They can be referenced as elements[0], elements[1], and so forth • If the elements' HTML tags have NAME attributes, the objects can be referenced by their names as properties of the form CPS606, Fall 2002, EECS SU & CollabWorx

  46. Forms 3 <FORM NAME="userData“ ACTION=“processForm.cgi”> First name:<INPUT TYPE="text NAME="first"> <BR> Last name:<INPUT TYPE="text" NAME="last"> <BR> Address: <TEXTAREA NAME="addr" ROWS="4" COLS="32"></TEXTAREA> <P> <INPUT TYPE="button" NAME="btn" VALUE="Accept data" ONCLICK="processData(this.form)"> <INPUT TYPE="reset" NAME="rst" VALUE="Start over"> <INPUT TYPE=“hidden” NAME=“fn”> </FORM> • The first text box could be referenced by any of this: document.userData.first document.userData.elements[0] document.forms[0].first document.forms[0].elements[0] CPS606, Fall 2002, EECS SU & CollabWorx

  47. Forms vs. JavaScript • Form objects and all their properties and elements can be referenced by any statements in a script • Some properties are read-only, but many can be modified • Options can be added to or removed from a select box • additional Option objects can be created with the new Option() constructor CPS606, Fall 2002, EECS SU & CollabWorx

  48. Event handlers in forms • processData has been defined as onclick event handler for one of the buttons • processData() can manipulate the Form object and its elements: function processData (fo) { fullName = fo.first.value+" "+fo.last.value; fo.fn.value = fullName; fo.submit(); } • Before the form is submitted to server, the function calculates full name and passes it on along with values of other elements CPS606, Fall 2002, EECS SU & CollabWorx

  49. Types of events • onsubmit onreset • onchange onclick ondblclick • onkeydown onkeypress onkeyup • onmousedown onmousemove onmouseout onmouseover onmouseup • onabort onerror onload onunload • onmove onresize onblur onfocus ondragdrop • etc. CPS606, Fall 2002, EECS SU & CollabWorx

  50. The event object • JavaScript can pass an event object to event handlers • event object contains a number of properties that provide detailed information about the event, such as type of even, mouse button pressed, event coordinates, window size after event, etc document.links[2].onclick = reportEvent……. function reportEvent(ev) { alert("Event of type " + ev.type + " occurred at X=" + ev.pageX + ", Y=" + ev.pageY) } CPS606, Fall 2002, EECS SU & CollabWorx