1 CS 21A • Beginning JavaScript Programming Project 5 Using Objects to Create a Shopping Cart Application Sonny Huang 2 Project 5 Using Objects to Create a Shopping Cart Application Outline l Use a hidden frame for JavaScript code l Explain why hidden frames are useful l Explain the concept of a JavaScript object l Create an object using the Object data type l Write a method for an object l Use the delete operator to delete an object l Use the With statement to reference an object 3 Project 5 Using Objects to Create a Shopping Cart Application Outline l Use the For-in statement to loop through the elements of an object l Use the history method of the document object to navigate to Web pages l Write to a window object from a document l Refer to windows from other windows l Determine the browser being used with the navigator object l Detect keystrokes in a Web page 4 Introduction Please view the dell web site(www.dell.com) to see the functions of a shopping carts program. Shopping carts allow users to build a list of items they want to purchase from a company’s Web site. We will learn how to create and maintain the list of items that shoppers purchase. We will use hidden frames to place all of our JavaScript in a single location without allowing users to see that frame. 5 Introduction Different browsers will act differently in handling some HTML tags and JavaScript commands. To make sure that all the browser will display what we wants. We will learn to identify the browser a Web page visitor is using. 6 Introduction This allow user to use shortcut key to access the shopping carts 7 Introduction A pop up window will display the information which stored in the hidden frame. Project Five – Val-U Computers Shopping Web Site Requirements: 1. Already has a web page which list all the selling items. Want to have a shopping cart added to the page. 2. After users select their items, they can view their shopping cart on another web page. 3. The web page will allow users to delete items or go back to the shopping page. 8 Project Five – Val-U Computers Shopping Web Site 4. The users can obtain a printable copy of their order by clicking a link on the shopping cart page. 5. When the users click the link, there will have information displayed to show the users how to print the information. 6. The web page will ask the users’ information, so it will be able to display the users’ information on the form. 9 10 Creating an Object in a Hidden Frame Cookies are a place to store information for future use. A hidden frame is an area, that is invisible to the user, to remain in place for use by JavaScript. JavaScript can be placed in hidden frames, so common functions can be accessed from multiple Web pages within the Web site. 11 Creating an Object in a Hidden Frame Advantages of using hidden frames over cookies: 1. The data remain intact in the hidden frame as the user navigates the web site. When reloading a web page, the program has to read and write the cookies. 2. Hidden frames can store complex data, such as objects, more easily than cookies. 3. When users visit another website or close browsers the hidden frame data will be lost. The cookies still stay in the computer. 12 Creating an Object in a Hidden Frame Creating the Hidden Frame: Same as creating any frames, but set the size of the hidden frames to zero. 13 Creating an Object in a Hidden Frame Save the file as valucomp.htm. 14 Creating an Object in a Hidden Frame Creating the ShoppingCart Object 15 Creating an Object in a Hidden Frame Based on the criteria, we will choose to use object and the name of the object is ShoppingCart. 1. Each item will itself be an object. 2. These objects can be added to the shoppingCart object or deleted from the ShoppingCart object. 3. Each item in the shopping cart also will have the capacity of displaying itself using the display method. 16 Creating an Object in a Hidden Frame new operator An operator that lets you create an instance of a user-defined object type or of one of the built-in object types Array, Boolean, Date, Function, Math, Number, or String. Creating a user-defined object type requires two steps: 1. Define the object type by writing a function. 2. Create an instance of the object with new. 17 Creating an Object in a Hidden Frame To define an object type, create a function for the object type that specifies its name, properties, and methods. Syntax objectName = new objectType ( param1 [,param2] ...[,paramN] ) 18 Creating an Object in a Hidden Frame Arguments objectName is the name of the new object instance. objectType is the object type. It must be a function that defines an object type. param1...paramN are the property values for the object. These properties are parameters defined for the objectType function. 19 Creating an Object in a Hidden Frame Example : object type and object instance. Suppose you want to create an object type for cars. You want this type of object to be called car, and you want it to have properties for make, model, and year. To do this, you would write the following function: function car(make, model, year) { this.make = make this.model = model this.year = year } 20 Creating an Object in a Hidden Frame Now you can create an object called mycar as follows: mycar = new car("Eagle", "Talon TSi", 1993) This statement creates mycar and assigns it the specified values for its properties. Then the value of mycar.make is the string "Eagle", mycar.year is the integer 1993, and so on. You can create any number of car objects by calls to new. For example, kenscar = new car("Nissan", "300ZX", 1992) 21 Creating an Object in a Hidden Frame The following code is used to start a new document. This document exists in the hidden frame, name HIDDEN. The addItem( ) function adds an item to the ShoppingCart object. The addItem function contains three properties (Description, Price and ItemNum) and one method(display). 22 Creating an Object in a Hidden Frame The following code is used to start a new document. This document exists in the hidden Declared ShoppingCart frame, name HIDDEN. as JavaScript object Set ShoppingCart object’s properties. Set display method for showing an item. 23 Creating an Object in a Hidden Frame object Indexes: We can use different kinds of variable as an index. 24 Creating an Object in a Hidden Frame The following code is used to add a new item to the shopping cart. Creating a new object and assign it to the ShoppingCart object index. 25 Creating an Object in a Hidden Frame Deleting an Object delete operator: tells JavaScript to delete all of the properties of an object. The syntax is as following: delete objectname 26 Creating an Object in a Hidden Frame 27 Creating an Object in a Hidden Frame Creating the printItem( ) Method with statement The with statement establishes the default object for a set of statements. Within the set of statements, any property references that do not specify an object are assumed to be for the default object. A with statement looks as follows: with (object){ } statements 28 Creating an Object in a Hidden Frame Example. The following with statement specifies that the Math object is the default object. The statements following the with statement refer to the PI property and the cos and sin methods, without specifying an object. JavaScript assumes the Math object for these references. var a, x, y; var r=10 with (Math) { a = PI * r * r x = r * cos(PI) y = r * sin(PI/2) } 29 Creating an Object in a Hidden Frame 30 Creating an Object in a Hidden Frame 31 Creating an Object in a Hidden Frame Writing Object Data to the Web Page for...in statement he for...in statement iterates a specified variable over all the properties of an object. For each distinct property, JavaScript executes the specified statements. A for...in statement looks as follows: for (variable in object) { statements } 32 Creating an Object in a Hidden Frame Example. The following function takes as its argument an object and the object's name. It then iterates over all the object's properties and returns a string that lists the property names and their values. function dump_props(obj, obj_name) { var result = "" for (var i in obj) { result += obj_name + "." + i + " = " + obj[i] + "<BR>" } result += "<HR>" return result } 33 Creating an Object in a Hidden Frame For an object car with properties make and model, result would be: car.make = Ford car.model = Mustang 34 Creating an Object in a Hidden Frame For an object car with properties make and model, result would be: car.make = Ford car.model = Mustang Clear the frame Writing HTML code to frame 35 Creating an Object in a Hidden Frame Check if item is deleted Line 56 will invoke the display method which will cause the printItem() to be called and passed in true and top.Main.document to the function. 36 Creating an Object in a Hidden Frame 37 Creating an Object in a Hidden Frame Calling the viewCart() Function Call viewCart() in the hidden frame 38 Creating an Object in a Hidden Frame Calling the addtoCart() Function Call addtoCart() in the hidden frame 39 Creating an Object in a Hidden Frame 40 Using the History Object history object Object. Contains information on the URLs that the client has visited within a window. This information is stored in a history list and is accessible through the Navigator Go menu. Syntax To use a history object: 1. history.propertyName 2. history.methodName(parameters) 3. [windowReference.]history[index] 41 Using the History Object Parameters propertyName is one of the properties listed below. methodName is one of the methods listed below. windowReference is a valid way of referring to a window index is an integer representing an entry in the history list. 42 Using the History Object Property of window object Description The history object is a linked list of URLs the user has visited, as shown in the Navigator Go menu. To change a window's current URL without generating a history entry, you can use the replace method. This replaces the current page with a new one without generating a history entry. 43 Using the History Object The history array You can reference the history entries by using the history array. This array contains an entry for each history entry in source order; each array entry is a string containing a URL. For example, if the history list contains three named entries, these entries are reflected as history[0], history[1], and history[2]. 44 Using the History Object To use the history array: 1. history[index] 2. history.lengthindex is an integer representing an entry in the history list. To obtain the number of entries in the history list, use the length property: history.length. Elements in the history array are read-only. For example, the statement history[0]="http://home.netscape.com" has no effect. 45 Using the History Object If we access the history array without specifying an array element, Navigator returns a string of HTML which displays a table of URLs, each of which is a hyperlink. Properties The history object has the following properties: current Specifies the URL of the current history entry length Reflects the number of entries in the history list 46 Using the History Object next Specifies the URL of the next history entry previous Specifies the URL of the previous history entry The history array has the following properties: length Reflects the number of history entries in the window. 47 Using the History Object The History object has the following methods: •back :Loads the previous URL in the history list. history.back() •eval :evaluates a string of JavaScript code in the context of the specified object. [objectName.]eval(string) •forward :Loads the next URL in the history list. history.forward() •go :Loads a URL from the history list. history.go(delta | "location") 48 Using the History Object •toString : Returns a string representing the specified object. objectName.toString() •valueOf :Returns the primitive value of the specified object. objectName.valueOf() Examples Example 1. The following example goes to the URL the user visited three clicks ago in the current window. history.go(-3) 49 Using the History Object Example 2. You can use the history object with a specific window or frame. The following example causes window2 to go back one item in its window (or session) history: window2.history.back() Example 3. The following example causes the second frame in a frameset to go back one item: parent.frames[1].history.back() 50 Using the History Object Example 4. The following example causes the frame named frame1 in a frameset to go back one item: parent.frame1.history.back() Example 5. The following example causes the frame named frame2 in window2 to go back one item: window2.frame2.history.back() 51 Using the History Object Example 6. The following code determines whether the first entry in the history array contains the string "NETSCAPE". If it does, the function myFunction is called. if (history[0].indexOf("NETSCAPE") != -1) { myFunction(history[0]) } 52 Using the History Object Example 7. The following example displays the entire history list: document.writeln("<B>history is</B> " + history) This code displays output similar to the following: history is Welcome to Netscape Sun Microsystems http://home.netscape.com/ http://www.sun.com/ SlugVideo at the Dream Inn http://sapphire.cse.ucsc.edu/SlugVideo/dream-inn.html Bad Dog Chronicles http://www.supernet.net/~dugbrown/ 53 Using the History Object 54 Using the History Object Adding the goBack() function In the MAIN frame go back two pages: due to the write() and close() methods add a blank page to the history 55 Using the History Object 56 Using the History Object Calling the goBack() and printOrder() Functions Call goBack() Call printOrder() 57 Writing HTML to Another Window Writing the printOrder() function The printOrder() opens a new window and display the items in the ShoppingCart object. The open(), used to create the window, returns an object for the window that it opened 58 Writing HTML to Another Window 59 Writing HTML to Another Window 60 Writing HTML to Another Window 61 Determining Browsers and Detecting Keystrokes navigator object Contains information about the browser in use. Syntax To use a navigator object: 1. navigator.propertyName 2. navigator.methodName Parameters propertyName is one of the properties listed below. methodName is one of the methods listed below. 62 Determining Browsers and Detecting Keystrokes Description Use the navigator object to determine which version and name of the browser we have, what MIME types the user's browser can handle, and what plug-ins the user has installed. Properties appCodeName :Specifies the code name of the browser appName :Specifies the name of the browser 63 Determining Browsers and Detecting Keystrokes appVersion :Specifies version information for the Navigator mimeTypes :An array of all MIME types supported by the client plugins:An array of all plug-ins currently installed on the client userAgent:Specifies the user-agent header 64 Determining Browsers and Detecting Keystrokes Responding to a Keystroke Based on the Browser Type 65 Determining Browsers and Detecting Keystrokes For the Netscape Navigator: The which property returns the ASCII value of the key. The key.which value is forced to be a numeric value by making the result a new number object. The toString(16) method converts the KeyChar to hexadecimal. The unescape() converts the hexadecimal to a standard character that can be test. 66 Determining Browsers and Detecting Keystrokes 67 Determining Browsers and Detecting Keystrokes For Internet Explorer: IP provides a keyCode property when a key is press in a document. fromCharCode, one of the String methodes, converts the key to a readable character 68 Determining Browsers and Detecting Keystrokes 69 Determining Browsers and Detecting Keystrokes 70 Determining Browsers and Detecting Keystrokes Set MAIN onKeyPress event Send key from the HIDDEN frame Make MAIN as the active frame 71 Determining Browsers and Detecting Keystrokes In the order.html’s body tag put the onKeyPress="JavaScript:top.HIDDEN.keyPressed()“ in. Call keyPressed() event in the hidden frame 72 Determining Browsers and Detecting Keystrokes Using the prompt() Function 73 Determining Browsers and Detecting Keystrokes