Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript Advanced Chapter 7 Using Object-Oriented JavaScript.

Similar presentations


Presentation on theme: "JavaScript Advanced Chapter 7 Using Object-Oriented JavaScript."— Presentation transcript:

1 JavaScript Advanced Chapter 7 Using Object-Oriented JavaScript

2 Course Outline 7. Using Object-Oriented JavaScript. 8. Manipulating Data in Strings and Arrays. 9. Managing State Information and Security. 10. Programming for Touchscreens and Mobile Devices. 11. Updating Web Pages with Ajax.

3 JavaScript Advanced Chapter 7 Using Object-Oriented JavaScript

4 JavaScript Advanced4 Objectives When you complete this chapter, you will be able to: Explain basic concepts related to object-oriented programming Use the Date, Number, and Math objects Define your own custom JavaScript objects

5 JavaScript Advanced5 Introduction to Object-Oriented Programming Object-oriented programming –Allows reuse of code without having to copy or recreate it

6 JavaScript Advanced6 Reusing Software Objects Object-oriented programming (OOP) –Creating reusable software objects Easily incorporated into multiple programs Object –Programming code and data treated as an individual unit or component –Also called a component Data –Information contained within variables or other types of storage structures

7 JavaScript Advanced7 Reusing Software Objects (cont’d.) Objects range from simple controls to entire programs Popular object-oriented programming languages –C++, Java, Visual Basic

8 JavaScript Advanced8 Figure 7-1 Programming with objects Reusing Software Objects (cont’d.)

9 JavaScript Advanced9 What Is Encapsulation? Encapsulated objects –Code and data contained within the object itself Encapsulation places code inside a “black box” Interface –Elements required for program to communicate with an object Principle of information hiding –Any methods and properties other programmers do not need to access should be hidden

10 JavaScript Advanced10 What Is Encapsulation? (cont’d.) Advantages of encapsulation –Reduces code complexity –Prevents accidental bugs and stealing of code Programming object and its interface –Compare to a handheld calculator Figure 7-2 Calculator interface

11 JavaScript Advanced11 What Is Encapsulation? (cont’d.) Document object is encapsulated (black box) –getElementById() method Part of the interface JavaScript uses to communicate with the Document object Microsoft Word: example of an object and its interface Figure 7-3 Using the interface for the Document object

12 Understanding Classes Classes –Grouping of code, methods, attributes, etc., making up an object Instance –Object created from an existing class Instantiate: create an object from an existing class Instance of an object inherits its methods and properties from a class Objects in the browser object model –Part of the web browser –No need to instantiate them to use them JavaScript Advanced12

13 JavaScript Advanced13 Using Built-In JavaScript Classes Table 7-1 Built-in JavaScript classes

14 JavaScript Advanced14 Using Built-In JavaScript Classes (cont’d.) Instantiating an object –Some of the built-in JavaScript objects used directly in code –Some objects require programmer to instantiate a new object –Example: Math object’s PI(π) property in a script // calculate the area of a circle based on its radius function calcCircleArea() { var r = document.getElementById("radius").value; var area = Math.PI * Math.pow(r, 2); // area is pi times ↵ radius squared return area; }

15 JavaScript Advanced15 Using Built-In JavaScript Classes (cont’d.) Instantiating an object (cont’d.) –Can instantiate Array object using array literal Example: var deptHeads = []; –Can instantiate empty generic object using object literal Example: var accountsPayable = {}; Generic object literal uses curly braces around value –Can't use object literal for Date object Must use constructor Example: var today = new Date();

16 JavaScript Advanced16 Using Built-In JavaScript Classes (cont’d.) Performing garbage collection –Garbage collection Cleaning up, or reclaiming, memory reserved by a program –Declaring a variable or instantiating a new object Reserves memory for the variable or object –JavaScript knows when a program no longer needs a variable or object Automatically cleans up the memory

17 JavaScript Advanced17 Using the Date, Number, and Math Classes Three of most commonly used JavaScript classes: – Date, Number, and Math

18 JavaScript Advanced18 Manipulating the Date and Time with the Date Class Date class –Methods and properties for manipulating the date and time –Allows use of a specific date or time element in JavaScript programs Table 7-2 Date class constructors

19 JavaScript Advanced19 Manipulating the Date and Time with the Date Class (cont’d.) Example: – var today = new Date(); –Month and year date representation in a Date object –Stored using numbers matching actual date and year Days of the week and months of the year –Stored using numeric representations Starting with zero: similar to an array Example: – var independenceDay = new Date(1776, 6, 4);

20 JavaScript Advanced20 Manipulating the Date and Time with the Date Class (cont’d.) After creating a new Date object –Manipulate date and time in the variable using the Date class methods Date and time in a Date object –Not updated over time like a clock –Date object contains the static (unchanging) date and time Set at the moment the JavaScript code instantiates the object

21 JavaScript Advanced21 Table 7-3 Commonly used methods of the Date class (continues) Manipulating the Date and Time with the Date Class (cont’d.)

22 JavaScript Advanced22 Table 7-3 Commonly used methods of the Date class Manipulating the Date and Time with the Date Class (cont’d.)

23 JavaScript Advanced23 Manipulating the Date and Time with the Date Class (cont’d.) Each portion of a Date object can be retrieved and modified using the Date object methods –Examples: var curDate = new Date(); curDate.getDate(); Displaying the full text for days and months –Use a conditional statement to check the value returned by the getDay() or getMonth() method –Example: if/else construct to print the full text for the day of the week returned by the getDay() method

24 JavaScript Advanced24 var today = new Date(); var curDay = today.getDay(); var weekday; if (curDay === 0) { weekday = "Sunday"; } else if (curDay === 1) { weekday = "Monday"; } else if (curDay === 2) { weekday = "Tuesday"; } else if (curDay === 3) { weekday = "Wednesday"; } else if (curDay === 4) { weekday = "Thursday"; } else if (curDay === 5) { weekday = "Friday"; } else if (curDay === 6) { weekday = "Saturday"; } Manipulating the Date and Time with the Date Class (cont’d.)

25 JavaScript Advanced25 var today = new Date(); var months = ["January","February","March", ↵ "April","May","June", ↵ "July","August","September", ↵ "October","November","December"]; var curMonth = months[today.getMonth()]; Manipulating the Date and Time with the Date Class (cont’d.) Example: include an array named months –12 elements assigned full text names of the months

26 JavaScript Advanced26 Manipulating Numbers with the Number Class Number class –Methods for manipulating numbers and properties containing static values Representing some numeric limitations in the JavaScript language –Can append the name of any Number class method or property To the name of an existing variable containing a numeric value

27 JavaScript Advanced27 Manipulating Numbers with the Number Class (cont’d.) Using Number class methods Table 7-4 Number class methods

28 JavaScript Advanced28 Manipulating Numbers with the Number Class (cont’d.) Using Number class methods (cont’d.) –Primary reason for using any of the “to” methods To convert a number to a string value with a specific number of decimal places –toFixed() method Most useful Number class method –toLocaleString() method Converts a number to a string formatted with local numeric formatting conventions

29 JavaScript Advanced29 Manipulating Numbers with the Number Class (cont’d.) Accessing Number class properties Table 7-5 Number class properties

30 JavaScript Advanced30 Performing Math Functions with the Math Class Math class –Methods and properties for mathematical calculations Cannot instantiate a Math object using a statement such as: var mathCalc = new Math(); –Use the Math object and one of its methods or properties directly in the code Example: var curNumber = 144; var squareRoot = Math.sqrt(curNumber); // returns 12

31 JavaScript Advanced31 Table 7-6 Math class methods Performing Math Functions with the Math Class (cont’d.)

32 JavaScript Advanced32 Table 7-7 Math class properties Performing Math Functions with the Math Class (cont’d.)

33 JavaScript Advanced33 Performing Math Functions with the Math Class (cont’d.) Example: –Use the PI property to calculate the area of a circle based on its radius Code uses the pow() method to raise the radius value to second power, and the round() method to round the value returned to the nearest whole number var radius = 25; var area = Math.PI * Math.pow(radius, 2); var roundedArea = Math.round(area); // returns 1963

34 JavaScript Advanced34 Defining Custom JavaScript Objects JavaScript: not a true object-oriented programming language –Cannot create classes in JavaScript –Instead, called an object-based language Can define custom objects –Not encapsulated –Useful to replicate the same functionality an unknown number of times in a script

35 JavaScript Advanced35 Declaring Basic Custom Objects Use the Object object – var objectName = new Object(); – var objectName = {}; Can assign properties to the object –Append property name to the object name with a period

36 JavaScript Advanced36 Declaring Basic Custom Objects (cont'd.) Add properties using dot syntax –Object name followed by dot followed by property name –Example: InventoryList.inventoryDate = new Date(2017, 11, 31);

37 JavaScript Advanced37 Declaring Basic Custom Objects (cont'd.) Can assign values to the properties of an object when object first instantiated Example: var PerformanceTickets = { customerName: "Claudia Salomon", performanceName: "Swan Lake", ticketQuantity: 2, performanceDate: new Date(2017, 6, 18, 20) };

38 JavaScript Advanced38 Declaring Sub-Objects Value of a property can be another object –called a sub-object –Example– order object with address sub-object: var order = { orderNumber: "F5987", address: { street: "1 Main St", city: "Farmington", state: "NY", zip: "14425" } };

39 Referring to Object Properties as Associative Arrays Associative array –An array whose elements are referred to with an alphanumeric key instead of an index number Can also use associative array syntax to refer to the properties of an object With associative arrays –Can dynamically build property names at runtime JavaScript Advanced39

40 JavaScript Advanced40 Referring to Object Properties as Associative Arrays (cont'd.) Can use associative array syntax to refer to the properties of an object Example: var stopLightColors = { stop: "red", caution: "yellow", go: "green" }; stopLightColors["caution"];

41 JavaScript Advanced41 Referring to Object Properties as Associative Arrays (cont'd.) Can easily reference property names that contain numbers –Example: var order = { item1: "KJ2435J", price1: 23.95, item2: "AW23454", price2: 44.99, item3: "2346J3B", price3: 9.95 };

42 JavaScript Advanced42 Referring to Object Properties as Associative Arrays (cont'd.) Can easily reference property names that contain numbers (cont'd.) –To create order summary: for (var i = 1; i < 4; i++) { document.getElementById("itemList").innerHTML += ↵ " " + order["item" + i] + " "; document.getElementById("itemList").innerHTML += ↵ " " + order["price" + i] + " "; } ;

43 JavaScript Advanced43 Referring to Object Properties as Associative Arrays (cont'd.) Can also write generic code to add new object properties that incorporate numbers –Example—adding items to shopping cart: totalItems += 1; // increment counter of items in order currentItem = document.getElementById("itemName").innerHTML; currentPrice = document.getElementById("itemPrice").innerHTML; newItemPropertyName = "item" + totalItems; // "item4" newPricePropertyName = "price" + totalItems; // "price4" order.newItemPropertyName = currentItem; // order.item4 = (name) order.newPricePropertyName = currentPrice; // order.price4 = (price); Allows for as many items as user wants to purchase

44 JavaScript Advanced44 Creating Methods Object method simply a function with a name within the object Two ways to add method to object –Provide code for method in object –Reference external function

45 JavaScript Advanced45 Creating Methods (cont'd.) Specify method name with anonymous function as value –Example: var order = { items: {}, generateInvoice: function() { // function statements } };

46 JavaScript Advanced46 Creating Methods (cont'd.) Specify method name with existing function as value –Example: –Reference to existing function cannot have parentheses function processOrder() { // function statements } var order = { items: {}, generateInvoice: processOrder };

47 JavaScript Advanced47 Enumerating custom object properties Custom objects can contain dozens of properties To execute the same statement or command block for all the properties within a custom object –Use the for/in statement –Looping statement similar to the for statement Syntax for (variable in object) { statement(s); }

48 JavaScript Advanced48 Enumerating custom object properties (cont'd.) for/in statement enumerates, or assigns an index to, each property in an object Typical use: –validate properties within an object

49 JavaScript Advanced49 var item={ itemNumber: "KJ2435J", itemPrice: 23.95, itemInstock: true, itemShipDate: new Date(2017, 6, 18), }; for (prop in order) { if (order[prop] === "") { order.generateErrorMessage(); } Enumerating custom object properties (cont’d.) Example—checking for empty values:

50 JavaScript Advanced50 Deleting Properties Use the delete operator Syntax delete object.property Example: delete order.itemInStock;

51 JavaScript Advanced51 Defining Constructor Functions Constructor function –Used as the basis for a custom object –Also known as object definition JavaScript objects –Inherit all the variables and statements of the constructor function on which they are based All JavaScript functions –Can serve as a constructor

52 JavaScript Advanced52 Defining Constructor Functions (cont’d.) Example: –Define a function that can serve as a constructor function function Order(number, order, payment, ship) { this.customerNumber = number; this.orderDate = order; this.paymentMethod = payment; this.shippingDate = ship; }

53 JavaScript Advanced53 Adding Methods to a Constructor Function Can create a function to use as an object method –Refer to object properties with this reference –Example: function displayOrderInfo() { var summaryDiv = document.getElementById("summarySection"); summaryDiv.innerHTML += (" Customer: " + ↵ this.customerNumber + " "); summaryDiv.innerHTML += (" Order Date: " + ↵ this.orderDate.toLocaleString()+ " "); summaryDiv.innerHTML += (" Payment: " + ↵ this.paymentMethod + " "); summaryDiv.innerHTML += (" Ship Date: " + ↵ this.shippingDate.toLocaleString() + " "); }

54 JavaScript Advanced54 Using the prototype Property After instantiating a new object –Can assign additional object properties Use a period New property only available to that specific object prototype property –Built-in property that specifies the constructor from which an object was instantiated –When used with the name of the constructor function Any new properties you create will also be available to the constructor function

55 Using the prototype Property (cont’d.) Object definitions can use the prototype property to extend other object definitions –Can create a new object based on an existing object JavaScript Advanced55

56 Summary Object-oriented programming (or OOP) –The creation of reusable software objects Reusable software objects –Called components Object –Programming code and data treated as an individual unit or component Objects are encapsulated Interface represents elements required for a source program to communicate with an object JavaScript Advanced56

57 Summary (cont’d.) Principle of information hiding Code, methods, attributes, and other information that make up an object –Organized using classes Instance –Object created from an existing class An object inherits the characteristics of the class on which it is based Date class contains methods and properties for manipulating the date and time JavaScript Advanced57

58 Summary (cont’d.) Number class contains methods for manipulating numbers and properties Math class contains methods and properties for performing mathematical calculations Can define custom object –object literal Can create template for custom objects –constructor function this keyword refers to object that called function prototype property specifies object's constructor JavaScript Advanced58

59 JavaScript Advanced Chapter 8 Manipulating Data in Strings and Arrays

60 JavaScript Advanced60 Objectives When you complete this chapter, you will be able to: Manipulate strings with properties and methods of the String object Create regular expressions and use them to validate user input Manipulate arrays with properties and methods of the Array object Convert between strings and arrays, and between strings and JSON

61 JavaScript Advanced61 Manipulating Strings String –Text contained within double or single quotation marks –Literal values or assigned to a variable –Begin and end with same type of quotation mark Example: document.getElementById("mainHeading").innerHTML = "24-Hour ↵ Forecast"; var highSurfAdvisory = "Watch out for high waves and strong ↵ rip currents.";

62 JavaScript Advanced62 Manipulating Strings (cont’d.) Parsing –Extracting characters or substrings from a larger string Use String class to parse text strings in scripts –Represents all literal strings and string variables in JavaScript –Contains methods for manipulating text strings

63 JavaScript Advanced63 Formatting Strings Using special characters –For basic types: use escape sequences var mainHead = 'Today\'s Forecast'; –For other special characters: use Unicode Standardized set of characters from many of the world’s languages copyrightInfo = " © 2006-2017 "; // numeric character ref. copyrightInfo = " © 2006-2017 "; // character entity

64 JavaScript Advanced64 Formatting Strings (cont’d.) Using special characters (cont’d.) –fromCharCode() method Constructs a text string from Unicode character codes –Syntax: String.fromCharCode(char1, char2,...) –Examples: String.fromCharCode(74,97,118,97,83,99,114,105,112,116) copyrightInfo = String.fromCharCode(169) + " 2017";

65 JavaScript Advanced65 Formatting Strings (cont’d.) Changing case –toLowerCase() and toUpperCase() methods –Examples: var agency = "noaa"; agencyName.innerHTML = agency.toUpperCase(); // browser displays "NOAA" but value of agency is still "noaa" var agency = "noaa"; agency = agency.toUpperCase(); // value of agency is "NOAA" agencyName.innerHTML = agency; // browser displays "NOAA"

66 JavaScript Advanced66 Counting Characters in a String length property –Returns the number of characters in a string –Example: var country = "Kingdom of Morocco"; var stringLength = country.length; // value of stringLength is 18

67 JavaScript Advanced67 Finding and Extracting Characters and Substrings Table 8-1 Search and extraction methods of the String class (continues)

68 JavaScript Advanced68 Table 8-1 Search and extraction methods of the String class Finding and Extracting Characters and Substrings (cont’d.)

69 JavaScript Advanced69 Figure 8-5 Example uses of String class methods Finding and Extracting Characters and Substrings (cont’d.)

70 JavaScript Advanced70 Finding and Extracting Characters and Substrings (cont’d.) Two types of string search methods –Those that return a numeric position in a text string Character position in text string begins with a value of zero Can pass a second optional argument specifying the position in the string to start searching to the indexOf() method Example: search() method var email = "president@whitehouse.gov"; var atPosition = email.search("@"); // returns 9

71 JavaScript Advanced71 Finding and Extracting Characters and Substrings (cont’d.) Two types of string search methods (cont'd.) –Those that return a numeric position in a text string (cont'd.) Example: indexOf() method var email = "president@whitehouse.gov"; var atIndex = email.indexOf("@", 10); // returns -1

72 JavaScript Advanced72 Finding and Extracting Characters and Substrings (cont’d.) Two types of string search methods (cont’d.) –Those that return a character or substring substring() or slice() method var email = "president@whitehouse.gov"; var nameEnd = email.search("@"); // value of nameEnd is 9 var nameText = email.substring(0, nameEnd); // value of nameText is "president"

73 JavaScript Advanced73 Finding and Extracting Characters and Substrings (cont’d.) Extracting characters from the middle or end of a string –Use the search(), indexOf(), lastIndexOf() methods lastIndexOf() method returns position of the last occurrence of one string in another string –Example: var email = "president@whitehouse.gov"; var startDomainID = email.lastIndexOf("."); // startDomainID value is 20 var domainID = email.substring(startDomainID + 1); // domainID value is "gov"

74 JavaScript Advanced74 Finding and Extracting Characters and Substrings (cont’d.) slice() method allows negative argument values for the index arguments –Specifying a negative value for the starting index slice() method starts at the end of the text string –Specifying a negative value for the ending index Number of characters the slice() method extracts also starts at the end of the text string slice() method does not return the character represented by the ending index –Returns the character immediately before the ending index

75 JavaScript Advanced75 var email = "president@whitehouse.gov"; var nameText = email.slice(0,9); // nameText value is "president" var domain = email.slice(-14,-4); // domain value is "whitehouse" Finding and Extracting Characters and Substrings (cont’d.)

76 JavaScript Advanced76 Replacing Characters and Substrings replace() method –Creates a new string with the first instance of a specified pattern replaced with the value of the text argument –Syntax: string.replace(pattern, text) –Example: var email = "president@whitehouse.gov"; var newEmail = email.replace("president", "vice.president"); // value of newEmail is "vice.president@whitehouse.gov"

77 JavaScript Advanced77 Combining Characters and Substrings Combining strings –Use the concatenation operator (+) and compound assignment operator (+=) –Use the concat() method Creates a new string by combining strings passed as arguments Syntax: string.concat(value1, value2,...) –To combine text strings Easier to use the concatenation operator and the compound assignment operator

78 JavaScript Advanced78 var name = "Theodor Seuss Geisel"; var penName = "Dr. Seuss"; var bio = penName.concat(" was the pen name of ", name); // value of bio is // "Dr. Seuss was the pen name of Theodor Seuss Geisel" var name = "Theodor Seuss Geisel"; var penName = "Dr. Seuss"; var bio = penName + " was the pen name of " + name; // value of bio is // "Dr. Seuss was the pen name of Theodor Seuss Geisel" Combining Characters and Substrings (cont’d.)

79 JavaScript Advanced79 Comparing Strings Comparison operator ( === ) can be used with strings –Compare individual characters according to their Unicode position localeCompare() method –Compares strings according to the particular sort order of a language or country –Performs a case-sensitive comparison of two strings

80 JavaScript Advanced80 Working with Regular Expressions Regular expressions –Patterns used for matching and manipulating strings according to specified rules –With scripting languages, most commonly used for validating submitted form data

81 JavaScript Advanced81 Defining Regular Expressions in JavaScript Regular expressions –Must begin and end with forward slashes –Example: var urlProtocol = /https/; Approaches to creating regular expressions –Use regular expressions with several String class methods –Pass pattern directly to a method –Use the RegExp() constructor Contains methods and properties for working with regular expressions in JavaScript

82 JavaScript Advanced82 Defining Regular Expressions in JavaScript (cont’d.) Approaches to creating regular expressions (cont’d.) –Syntax for creating a regular expression with the RegExp() constructor var regExpName = new RegExp("pattern"[, attributes]); –Example: var urlProtocol = new RegExp("https"); var url = "http://www.cengagebrain.com"; var searchResult = url.search(urlProtocol); // returns -1

83 JavaScript Advanced83 Using Regular Expression Methods RegExp object –Includes two methods test() and exec() test() method: returns a value of true –If a string contains text that matches a regular expression –Otherwise returns false value –Syntax: var pattern = test(string); Real power of regular expressions –Comes from the patterns written

84 JavaScript Advanced84 Writing Regular Expression Patterns Hardest part of working with regular expressions –Writing the patterns and rules –Example: var emailPattern = /^[_a-zA-Z0-9\\-]+(\.[_a-zA-Z0-9\\-]+)* ↵ @[a-zA-Z0-9\\-]+(\.[a-zA-Z0-9\\-]+)*(\.[a-z]{2,6})$/; var email = "president@whitehouse.gov"; var result; if (emailPattern.test(email)) { result = true; } else { result = false; } // value of result is true

85 JavaScript Advanced85 Writing Regular Expression Patterns (cont’d.) Regular expression patterns consist of literal characters and metacharacters –Metacharacters: special characters that define the pattern matching rules in a regular expression

86 JavaScript Advanced86 Table 8-2 JavaScript regular expression metacharacters Writing Regular Expression Patterns (cont’d.)

87 JavaScript Advanced87 Writing Regular Expression Patterns (cont’d.) Matching any character –Period (. ) Matches any single character in a pattern Specifies that the pattern must contain a value where the period located Matching characters at the beginning or end of a string –^ metacharacter Matches characters at the beginning of a string –$ metacharacter Matches characters at the end of a string

88 JavaScript Advanced88 Writing Regular Expression Patterns (cont’d.) Matching characters at the beginning or end of a String (cont’d.) –Anchor Pattern that matches the beginning or end of a line –Specifying an anchor at the beginning of a line Pattern must begin with the ^ metacharacter Matching special characters –Precede the character with a backslash

89 JavaScript Advanced89 Writing Regular Expression Patterns (cont’d.) Specifying quantity –Quantifiers Metacharacters that specify the quantity of a match Table 8-3 JavaScript regular expression quantifiers

90 JavaScript Advanced90 Writing Regular Expression Patterns (cont’d.) Specifying subexpressions –Subexpression or subpattern Characters contained in a set of parentheses within a regular expression Allows determination of the format and quantities of the enclosed characters as a group

91 JavaScript Advanced91 Writing Regular Expression Patterns (cont’d.) Defining character classes –Character classes Used in regular expressions to treat multiple characters as a single item Created by enclosing the characters that make up the class with bracket [] metacharacters –Use a hyphen metacharacter ( - ) to specify a range of values in a character class –To specify optional characters to exclude in a pattern match Include the ^ metacharacter immediately before the characters in a character class

92 JavaScript Advanced92 Writing Regular Expression Patterns (cont’d.) Defining character classes (cont’d.) –Regular expressions include special escape characters in character classes To represent different types of data Table 8-4 JavaScript character class expressions

93 JavaScript Advanced93 Writing Regular Expression Patterns (cont’d.) Defining character classes (cont’d.) –Matching multiple pattern choices –Allow a string to contain an alternate set of substrings Separate the strings in a regular expression pattern with the | metacharacter

94 JavaScript Advanced94 Setting Regular Expression Properties Table 8-5 Properties of the RegExp object

95 JavaScript Advanced95 Setting Regular Expression Properties (cont’d.) Options for setting the values of these properties –Assign a value of true or false to the property By creating a regular expression with the RegExp() constructor –Use the flags when assigning a regular expression to a variable without using the RegExp() constructor

96 JavaScript Advanced96 Manipulating Arrays Use the Array class length property and methods Creating an array –Instantiates an object from the Array class

97 JavaScript Advanced97 Manipulating Arrays (cont'd.) Table 8-6 Methods of the Array class

98 JavaScript Advanced98 Finding and Extracting Elements and Values Primary method for finding a value in an array –Use a looping statement to iterate through the array until a particular value found Extract elements and values from an array –Use the slice() method to return (copy) a portion of an array and assign it to another array Syntax for the slice() method array_name.slice(start, end);

99 JavaScript Advanced99 Figure 8-11 List of states extracted using the slice() method var largestStates = ["Alaska", "Texas", "California", ↵ "Montana", "New Mexico", "Arizona", "Nevada", ↵ "Colorado", "Oregon", "Wyoming"]; var fiveLargestStates = largestStates.slice(0, 5); for (var i = 0; i < fiveLargestStates.length; i++) { var newItem = document.createElement("p"); newItem.innerHTML = fiveLargestStates[i]; document.body.appendChild(newItem); } Finding and Extracting Elements and Values (cont’d.)

100 JavaScript Advanced100 Manipulating Elements Adding and removing elements to and from the beginning of an array –shift() method removes and returns the first element from the beginning of an array –unshift() method adds one or more elements to the beginning of an array

101 JavaScript Advanced101 var colors = ["mauve", "periwinkle", "silver", "cherry", ↵ "lemon"]; colors.shift(); // colors value now // ["periwinkle", "silver", "cherry", "lemon"] colors.unshift("yellow-orange", "violet"); // colors value now ["yellow-orange", "violet", // "mauve", "periwinkle", "silver", "cherry", "lemon"] Manipulating Elements (cont’d.)

102 JavaScript Advanced102 Manipulating Elements Adding and removing elements to and from the end of an array –Use array’s length property to determine the next available index var colors = ["mauve", "periwinkle", "silver", "cherry"]; colors[colors.length] = "lemon"; // colors value now ["mauve", "periwinkle", "silver", // "cherry", "lemon"]

103 JavaScript Advanced103 Manipulating Elements (cont’d.) Adding and removing elements to and from the end of an array (cont’d.) –pop() method removes the last element from the end of an array –push() method adds one or more elements to the end of an array var colors = ["mauve", "periwinkle", "silver", "cherry"]; colors.pop(); // colors value now ["mauve", "periwinkle", "silver"] colors.push("yellow-orange", "violet"); // colors value now ["mauve", "periwinkle", "silver", // "yellow-orange", "violet"]

104 JavaScript Advanced104 Manipulating Elements (cont’d.) Adding and removing elements within an array –Use the splice() method Also renumbers the indexes in the array To add an element, include 0 as second argument var hospitalDepts = ["Anesthesia", "Molecular Biology", ↵ "Neurology", "Pediatrics"]; hospitalDepts.splice(3, 0, "Ophthalmology"); // value now ["Anesthesia", "Molecular Biology", // "Neurology", "Ophthalmology", "Pediatrics"]

105 JavaScript Advanced105 Manipulating Elements (cont’d.) Adding and removing elements within an array (cont'd.) –Use the splice() method (cont'd.) To delete elements, omit third argument Indexes renumbered just like when elements added var hospitalDepts = ["Anesthesia", "Molecular Biology", ↵ "Neurology", "Pediatrics"]; hospitalDepts.splice(1, 2); // value now ["Anesthesia", "Pediatrics"]

106 JavaScript Advanced106 Sorting and Combining Arrays Sorting arrays –Sort elements of an array alphabetically Use the sort() method var scientificFishNames = ["Quadratus taiwanae", ↵ "Macquaria australasica", "Jordania zonope", ↵ "Abudefduf sparoides", "Dactylopterus volitans", ↵ "Wattsia mossambica", "Bagrus urostigma"]; scientificFishNames.sort(); // scientificFishNames value now // ["Abudefduf sparoides", "Bagrus urostigma", // "Dactylopterus volitans", "Jordania zonope", // "Macquaria australasica", "Quadratus taiwanae", // "Wattsia mossambica"]

107 JavaScript Advanced107 Sorting and Combining Arrays (cont'd.) Sorting arrays (cont'd.) –reverse() method Transposes, or reverses, the order of the elements in an array scientificFishNames.reverse(); // scientificFishNames value now // ["Wattsia mossambica", "Quadratus taiwanae", // "Macquaria australasica", "Jordania zonope", // "Dactylopterus volitans", "Bagrus urostigma", // "Abudefduf sparoides"]

108 JavaScript Advanced108 Sorting and Combining Arrays (cont'd.) Combining arrays –Use the concat() method –Syntax array1.contact(array2, array3,...);

109 JavaScript Advanced109 Sorting and Combining Arrays (cont'd.) var Provinces = ["Newfoundland and Labrador", ↵ "Prince Edward Island", "Nova Scotia", ↵ "New Brunswick", "Quebec", "Ontario", ↵ "Manitoba", "Saskatchewan", "Alberta", ↵ "British Columbia"]; var Territories = ["Nunavut", "Northwest Territories", ↵ "Yukon"]; var Canada = []; Canada = Provinces.concat(Territories); // value of Canada now ["Newfoundland and Labrador", // "Prince Edward Island", "Nova Scotia", // "New Brunswick", "Quebec", "Ontario", // "Manitoba", "Saskatchewan", "Alberta", // "British Columbia", "Nunavut", // "Northwest Territories", "Yukon"];

110 JavaScript Advanced110 Converting Between Data Types Common task to convert strings and arrays to different data types –strings to arrays –arrays to strings –objects to strings –strings to objects

111 JavaScript Advanced111 Converting Between Strings and Arrays split() method of the String class –Splits a string into an indexed array Syntax array = string.split(separator[, limit]); To split individual characters in a string into an array –Pass an empty string ( "" ) as the separator argument

112 JavaScript Advanced112 var OPEC = "Algeria, Angola, Ecuador, Iran, Iraq, Kuwait, ↵ Libya, Nigeria, Qatar, Saudi Arabia, ↵ United Arab Emirates, Venezuela"; // The value of OPEC is a string var opecArray = OPEC.split(", "); // The value of opecArray is the following array: // ["Algeria", "Angola", "Ecuador", "Iran", "Iraq", // "Kuwait", "Libya", "Nigeria", "Qatar", "Saudi Arabia", // "United Arab Emirates", "Venezuela"] Converting Between Strings and Arrays (cont’d.)

113 JavaScript Advanced113 Converting Between Strings and Arrays (cont’d.) join() method of the Array class –Combines array elements into a string, separated by a comma or specified characters Syntax array.join(["separator"]); To prevent elements from being separated by any characters in the new string –Pass an empty string ( "" ) as the separator argument

114 JavaScript Advanced114 var OPEC = ["Algeria", "Angola", "Ecuador", "Iran", ↵ "Iraq", "Kuwait", "Libya", "Nigeria", "Qatar", ↵ "Saudi Arabia", "United Arab Emirates", "Venezuela"]; // value of OPEC is an array var opecString = OPEC.join(); // value of opecString is the following string: // "Algeria, Angola, Ecuador, Iran, Iraq, Kuwait, Libya, // Nigeria, Qatar, Saudi Arabia, United Arab Emirates, // Venezuela" Converting Between Strings and Arrays (cont’d.)

115 JavaScript Advanced115 Converting Between Strings and Arrays (cont’d.) join() method does not include a separator argument –Previous example OPEC nations automatically separated by commas Can include a separator argument of ";" var OPEC = ["Algeria", "Angola", "Ecuador", "Iran", ↵ "Iraq", "Kuwait", "Libya", "Nigeria", "Qatar", ↵ "Saudi Arabia", "United Arab Emirates", "Venezuela"]; // value of OPEC is an array var opecString = OPEC.join(";"); // value of opecString is the following string: // "Algeria;Angola;Ecuador;Iran;Iraq;Kuwait;Libya; // Nigeria;Qatar;Saudi Arabia;United Arab Emirates; // Venezuela"

116 JavaScript Advanced116 Converting Between Strings and Arrays (cont’d.) Can also use the toString() and toLocaleString() method –Convert an array to a string – array.toString(); – array.toLocaleString();

117 JavaScript Advanced117 Converting Between Strings and JSON JavaScript Object Notation (JSON) –Represents a JavaScript object as a string –Exchanges data between application and server JSON object –Supported in modern browsers, including IE8 Table 8-7 Methods of the JSON object

118 JavaScript Advanced118 Converting Between Strings and JSON (cont'd.) Converting an Object to a String –stringify() method – string = JSON.stringify(value [, replacer [, space]]); –string is name of variable that will contain string –value represents JavaScript object to be converted

119 JavaScript Advanced119 Converting Between Strings and JSON (cont'd.) Converting an Object to a String (cont'd.) var newUser = { fName: "Tony", lName: "Chu" }, newUserString = JSON.stringify(newUser); // value of newUserString is // '{"fName":"Tony","lName":"Chu"}'

120 JavaScript Advanced120 Converting Between Strings and JSON (cont'd.) Converting a String to an Object –parse() method – object = JSON.parse(string [, function]); –object is namve of variable that will contain object –string represents JSON string to be converted

121 JavaScript Advanced121 Converting Between Strings and JSON (cont'd.) Converting a String to an Object (cont'd.) –JSON string definition: String because enclosed in quotes –To convert string to JavaScript object: var newUser = '{"fName":"Tony","lName":"Chu"}'; var newUserObject = JSON.parse(newUser); // value of newUserObject is // { // fName: "Tony", // lName: "Chu" // };

122 JavaScript Advanced122 Summary Parsing –Act of extracting characters or substrings from a larger string All literal strings and string variables in JavaScript –Represented by the String class fromCharCode() method of the String class –Constructs a text string from Unicode character codes toLowerCase() and toUpperCase() methods –Change the case of letters in a string

123 JavaScript Advanced123 Summary (cont’d.) String class –length property –Methods: replace(), concat(), localeCompare() Regular expressions –Patterns used for matching and manipulating strings according to specified rules RegExp object –Contains methods and properties for working with regular expressions in JavaScript

124 JavaScript Advanced124 Summary (cont’d.) Use the Array class methods and length property to manipulate arrays in scripts –Methods: slice(), shift() and unshift(), pop() and push(), splice(), sort(), reverse(), concat(), and join() split() method of the String class –Splits a string into an indexed array join() method of the Array class –Combines array elements into a string

125 JavaScript Advanced125 Summary (cont’d.) Use the JSON class methods to convert between string values and object values stringify() method of the JSON class –Converts JavaScript object to JSON string parse() method of the JSON class –Converts JSON string to JavaScript object

126 JavaScript Advanced Chapter 9 Managing State and Information Security

127 JavaScript Advanced127 Objectives When you complete this chapter, you will be able to: Save state information with query strings, hidden form fields, and cookies Describe JavaScript security issues and employ coding practices designed to address them

128 JavaScript Advanced128 Understanding State Information State information –Information about individual visits to a Web site HTTP original design: stateless –No persistent data about site visits stored Reasons for maintaining state information –Customize individual web pages –Store information within a multipart form –Provide shopping carts

129 JavaScript Advanced129 Saving State Information with Query Strings Query string –Set of name-value pairs Appended to a target URL –Consists of a single text string Contains one or more pieces of information Passes information from one web page to another

130 JavaScript Advanced130 Saving State Information with Query Strings (cont’d.) Passing data with a query string –Add a question mark (?) immediately after a URL Followed by the query string (in name-value pairs) for the information to preserve –Ampersands (&) Separates individual name-value pairs within the query string –Example: <a href="http://www.example.com/ ↵ addItem.html?isbn=9780394800165&quantity=2">Order Book

131 JavaScript Advanced131 Saving State Information with Query Strings (cont’d.) –Passed query string assigned to target web page Location object search property search property of the Location object contains a URL’s query or search parameters From preceding example: –Query string "?isbn=9780394800165&quantity=2" –Available as the value of the search property of the Location object After addItem.html document opens

132 JavaScript Advanced132 Saving State Information with Query Strings (cont’d.) Remove the question mark –Using the substring() method combined with the length property –Example: // Assign the query string to the queryData variable var queryData = location.search; // Remove the opening question mark from the string queryData = queryData.substring(1, queryData.length);

133 JavaScript Advanced133 Saving State Information with Query Strings (cont’d.) Convert individual pieces of information into array elements –Using the split() method –Example: Convert the information in the queryData variable into an array named queryArray[] // split queryData into an array var queryArray = queryData.split("&");

134 JavaScript Advanced134 Saving State Information with Hidden Form Fields Hidden form field –Special type of form element –Not displayed by web browser –Allows information to be hidden from users –Created with the input element –Temporarily stores data sent to a server along with the rest of a form –No need for user to see hidden data Syntax

135 JavaScript Advanced135 Saving State Information with Hidden Form Fields (cont’d.) Figure 9-7 Submitting data from multiple forms using hidden fields

136 JavaScript Advanced136 Saving State Information with Cookies Query strings and hidden form fields temporarily maintain state information Cookies –Small pieces of information about a user –Stored by a web server in text files –Stored on the user’s computer When Web client visits a web server –Saved cookies sent from client to the server Temporary cookies –Available only for current browser session

137 JavaScript Advanced137 Storing State Information Query strings and hidden form fields temporarily maintain state information Two methods of storing state information on user's computer –cookies –Web Storage

138 JavaScript Advanced138 Storing State Information with Cookies Cookies –Small pieces of information –Stored in text files Temporary cookies –Remain available only for current browser session Persistent cookies –Remain available beyond current browser session Stored in a text file on a client computer

139 JavaScript Advanced139 Storing State Information with Cookies (cont'd.) Limitations on the use of cookies –Server or domain can store a maximum of 20 cookies –Total cookies per browser cannot exceed 300 –Largest cookie size is 4 kilobytes Not enforced by all browsers

140 JavaScript Advanced140 Creating and Modifying Cookies Use the cookie property of the Document object –Creates cookies in name-value pairs –Syntax document.cookie = name + "=" + value; –Cookie property created with a required name attribute and four optional attributes: expires, path, domain, secure

141 JavaScript Advanced141 Creating and Modifying Cookies (cont’d.) Table 9-1 Cookie attributes

142 JavaScript Advanced142 Creating and Modifying Cookies (cont’d.) name attribute –Only required parameter –Specifies cookie’s name-value pair –Cookies created with only the name attribute: Temporary cookies –cookie property adds another entry to a list of cookies

143 JavaScript Advanced143 Creating and Modifying Cookies (cont’d.) –Example: build a list of cookies document.cookie = "username=mw101"; document.cookie = "member=true"; document.cookie = "audio=false"; –Resulting value of cookie property: username=mw101; member=true; audio=false

144 JavaScript Advanced144 Creating and Modifying Cookies (cont’d.) –Cookies cannot include semicolons or special characters Can use special characters in cookies if using encoding –Encoding involves converting special characters in a text string To corresponding hexadecimal ASCII value preceded by a percent sign

145 JavaScript Advanced145 Creating and Modifying Cookies (cont’d.) –encodeURIComponent() function Used for encoding the individual parts of a URI Converts special characters in the individual parts of a URI to corresponding hexadecimal ASCII value Syntax: encodeURIComponent(text) –decodeURIComponent() function Counterpart of encodeURIComponent() function Syntax: decodeURIComponent(text)

146 JavaScript Advanced146 Creating and Modifying Cookies (cont’d.) Testing Applications That Use Cookies –Browsers open local documents without HTTP –Some browsers don't support setting cookies when HTTP protocol not used –Can focus testing on browsers that support cookies on files opened without HTTP –More robust option run local web server open files using HTTP protocol some code editors include built-in testing server

147 JavaScript Advanced147 Creating and Modifying Cookies (cont’d.) expires attribute –Determines how long a cookie can remain on a client system before being deleted –Cookies created without this attribute Available current browser session only –Syntax: expires=date name-value pair and the expires=date pair separated by a semicolon –Do not encode expires attribute

148 JavaScript Advanced148 Creating and Modifying Cookies (cont’d.) –Can manually type a string in UTC format or: Can create string with the Date object –Use the toUTCString() method to convert the Date object to a string –Example: var expiresDate = new Date(); var username = document.getElementById("username").value; expiresDate.setFullYear(expiresDate.getFullYear() + 1); document.cookie = "username=" + ↵ encodeURIComponent(username) + "; expires=" + ↵ expiresDate.toUTCString();

149 JavaScript Advanced149 Creating and Modifying Cookies (cont’d.) Configuring availability of cookies to other web pages on the server –use path attribute Default: cookie available to all web pages in the same directory To make cookie available to all directories on a server –Use a slash

150 JavaScript Advanced150 Creating and Modifying Cookies (cont’d.) –Example: var username = document.getElementById("username").value; document.cookie = "username=" + ↵ encodeURIComponent(username + "; path=/advertising"); –Example: document.cookie = "username=" + ↵ encodeURIComponent(username + "; path=/"); –Cookies from other programs stored in the same directory Can cause JavaScript program to run erratically

151 JavaScript Advanced151 Creating and Modifying Cookies (cont’d.) Sharing cookies across a domain –use domain attribute Example: var username = document.getElementById("username").value; document.cookie = "username=" + ↵ encodeURIComponent(username + ↵ "; domain=.example.com"); Cannot share cookies outside of a domain

152 JavaScript Advanced152 Creating and Modifying Cookies (cont’d.) Securing cookie transmissions –secure attribute Indicates cookie can only be transmitted across a secure Internet connection –Using HTTPS or another security protocol Example: var username = document.getElementById("username").value; document.cookie = "username=" + ↵ encodeURIComponent(username + "; secure=true");

153 JavaScript Advanced153 Reading Cookies with JavaScript Parsing a cookie –Decode it using decodeURIComponent() function –Use the String object methods to extract individual name-value pairs –Similar to parsing query strings Do not need to remove the question mark at the beginning of the string Individual cookies separated by a semicolon and a space instead of ampersands

154 JavaScript Advanced154 Reading Cookies with JavaScript (cont’d.) –Example: Create three encoded cookies Read them from the cookie property, decode them Use the split() method to copy each name-value pair into cookieArray[] array elements Determine which cookie holds needed value –for loop to cycle through array elements –if statement to check name portion of each name-value pair

155 JavaScript Advanced155 document.cookie = "username=" + ↵ encodeURIComponent(username); document.cookie = "member=" + ↵ encodeURIComponent(member); document.cookie = "audio=" + ↵ encodeURIComponent(audio); var cookieString = decodeURIComponent(document.cookie); var cookieArray = cookieString.split("; "); Reading Cookies with JavaScript (cont’d.)

156 JavaScript Advanced156 var currentUsername; var unBox = document.getElementById("username"); for (var i = 0; i < 3; i++) { currentUsername = cookieArray[i]; if ↵ (currentUsername.substring(0,currentUsername.indexOf("=")) ↵ === "username") { unBox.value = ↵ currentUsername.substring(currentUsername. ↵ indexOf("=") + 1,currentUsername.length); break; } Reading Cookies with JavaScript (cont’d.)

157 JavaScript Advanced157 Deleting Cookies with JavaScript Not intuitive –Must set cookie expiration to a date in the past Example: –Delete username cookie by setting its expires attribute to one week ago var expiresDate = new Date(); var username = document.getElementById("username").value; expiresDate.setDate(expiresDate.getDate() - 7); document.cookie = "username=" + ↵ encodeURIComponent(username) + "; expires=" + ↵ expiresDate.toUTCString();

158 JavaScript Advanced158 Deleting Cookies from Your Browser Persistent cookies can interfere with testing Good idea to delete cookies periodically Table 9-2 Steps to delete cookies in IE, Firefox, and Chrome

159 JavaScript Advanced159 Storing State Information with the Web Storage API Common uses of cookies never originally planned Web Storage –Draft specification of W3C –Not supported by some older browsers –Cookies are still the standard –Web Storage offers additional features –Applications targeted at specific browsers can use Web Storage

160 JavaScript Advanced160 Storing State Information with the Web Storage API (cont'd.) Two Web Storage properties of Window object –localStorage Remains until you run code to delete it Similar to persistent cookies –sessionStorage Removed automatically when user closes browser tab or window Like temporary cookies

161 JavaScript Advanced161 Storing State Information with the Web Storage API (cont'd.) Storing/reading Web Storage easier than cookies –Example: var firstName = document.getElementById("fname").value; localStorage.fName = firstName; To use a method –Preface it with localStorage or sessionStorage

162 JavaScript Advanced162 Storing State Information with the Web Storage API (cont'd.) Table 9-3 Methods of the Web Storage API

163 JavaScript Advanced163 Understanding Security Issues Security threats –Viruses, worms, data theft by hackers Consider web server security and secure coding issues Web server security technologies –Firewalls –Secure Socket Layer (SSL) JavaScript programs downloaded and execute locally

164 JavaScript Advanced164 Secure Coding with JavaScript Secure coding or defensive coding –Writing code to minimize any intentional or accidental security issues All code: insecure unless proven otherwise No magic formula for writing secure code

165 JavaScript Advanced165 JavaScript Security Concerns Security areas of most concern: –Protection of a web page and JavaScript program against malicious tampering –Privacy of individual client information –Protection of the local file system of the client or web site from theft or tampering Code injection attack –Program or user enters JavaScript code that changes function of web page Validating forms helps prevent this Escaping characters also important

166 JavaScript Advanced166 JavaScript Security Concerns Another security concern –Privacy of individual client information in the web browser window Important JavaScript security feature –Lack of certain types of functionality File manipulation Create a network connection Cannot run system commands or execute programs on a client

167 JavaScript Advanced167 The Same Origin Policy Restricts how JavaScript code access between windows/tabs/frames To view and modify elements in other windows and frames –They must have the same protocol and exist on the same web server Same origin policy applies to: –The domain name –The server on which a document located

168 JavaScript Advanced168 The Same Origin Policy (cont’d.) Policy prevents: –Malicious scripts from modifying content of other windows and frames –Theft of private browser information and information displayed on secure web pages Policy protects integrity of web page design

169 JavaScript Advanced169 The Same Origin Policy (cont’d.) domain property of the Document object –Changes origin of a document to its root domain name –Allows documents from different origins in the same domain to access each other’s elements and properties

170 JavaScript Advanced170 Using Third-Party Scripts Sometimes you want to run scripts from other domains –Known as third-party scripts –Examples: Widgets that run from provider's server Using Content Delivery Network (CDN) To enable third-party script –Include script element with src value pointing to third-party content –Exception to same origin policy

171 JavaScript Advanced171 Summary State information –Information about individual visits to a web site HTTP originally designed to be stateless Most common tools for maintaining state information: –Query strings, hidden form fields, cookies, Web Storage Query string –Set of name-value pairs appended to a target URL Can hide information from users in a hidden form field

172 JavaScript Advanced172 Summary (cont’d.) Cookies –Small pieces of information about a user –Stored by a web server –Can be temporary or persistent Cookie property created with a required name attribute Can use special characters in cookies if using encoding encodeURIComponent() function encodes the individual parts of a URI

173 JavaScript Advanced173 Summary (cont’d.) When reading a cookie or other text string encoded –Must first decode it with the decodeURIComponent() function Cookies: one continuous string that must be parsed Web Storage similar to cookies –Offers more features, but not as widely supported “Secure coding” or “defensive coding” –Writing code to minimize any intentional or accidental security issues

174 JavaScript Advanced Chapter 10 Programming for Touchscreens and Mobile Devices

175 JavaScript Advanced175 Objectives When you complete this chapter, you will be able to: Integrate mouse, touch, and pointer events into a web app Obtain and work with a user's geolocation information Optimize a mobile web app to accommodate the common constraints experienced by mobile users

176 JavaScript Advanced176 Using Touch Events and Pointer Events On touchscreen device without a moust –browsers fire click event when user touches screen Other events don't translate neatly for touchscreens

177 JavaScript Advanced177 Creating a Drag-and Drop Application with Mouse Events Mouse events –events based on actions of mouse or touchpad Table 10-1 Mouse events

178 JavaScript Advanced178 Understanding Mouse Events on a Touchscreen Device On a touchscreen device –Some web page elements respond to mouse events –div element not considered clickable doesn't fire mouse events on touchscreen –links and form elements are clickable browsers respond to touch Touch cascade –Browser checks a touched element for an event handler for multiple events Including some mouse events

179 JavaScript Advanced179 Understanding Mouse Events on a Touchscreen Device (cont'd.) Figure 10-5 Touch cascade order

180 JavaScript Advanced180 Understanding Mouse Events on a Touchscreen Device (cont'd.) Touchscreen devices fire touchscreen-specific events for some elements –Touch events created by Apple Used on Apple iOS and Google Android –Pointer events created by Microsoft Used on Windows Phone and Windows 8 and higher

181 JavaScript Advanced181 Implementing Touch Events Respond to user's finger touches on a touchscreen Table 10-2 Touch events

182 JavaScript Advanced182 Implementing Touch Events (cont'd.) touchstart event –analogous to mousedown mouse event touchmove event –corresponds to mousemove touchend event –similar to mouseup touchcancel event –unique to touchscreen

183 JavaScript Advanced183 Implementing Touch Events (cont'd.) Working with Touch Coordinates –Mouse events can work with event properties clientX property = x coordinate of event clientY property = y coordinate of event –Touch events support multitouch devices Allow for multiple touches on screen at once Don't support clientX or clientY properties as direct children Each touch event has array properties

184 JavaScript Advanced184 Implementing Touch Events (cont'd.) Table 10-3 Array properties of touch events

185 JavaScript Advanced185 Implementing Touch Events (cont'd.) Distinguishing Between App and Device Interaction –Touchscreen devices use touch events for more than one purpose Can interact via touch with an app Use touch to perform gestures –Browser and device interactions like scrolling –Use preventDefault() method Ensures that OS interface doesn't respond to events when users interact with your app

186 JavaScript Advanced186 Implementing Touch Events (cont'd.) Figure 10-7 Multiple uses of a single touch event

187 JavaScript Advanced187 Implementing Pointer Events Touchscreens on new types of devices –Tablets –Notebook computers Makes coding for touch and mouse events more complicated –Some devices support stylus input –Some devices have trackpads

188 JavaScript Advanced188 Implementing Pointer Events (cont'd.) Microsoft pointer events –Aim to handle input from mouse, finger, or stylus with each event –Incorporate other event properties Pressure on screen Angle of stylus Only IE Mobile and IE 10 and later support pointer events Some versions of IE do not recognize touch events –Use mouse+touch+pointer for max. compatibility

189 JavaScript Advanced189 Implementing Pointer Events (cont'd.) Table 10-4 Pointer events

190 JavaScript Advanced190 Implementing Pointer Events (cont'd.) Identifying pointer screen coordinates –clientX and clientY properties like mouse events Stopping OS gestures –Requires setting msTouchAction CSS property Set value to none

191 JavaScript Advanced191 Using Programming Interfaces for Mobile Devices APIs available to access information provided by mobile device hardware Table 10-5 Selected hardware APIs for mobile devices

192 JavaScript Advanced192 Using the Geolocation API Provides access to user's latitude & longitude Accessed using geolocation property of Navigator object Table 10-5 Selected hardware APIs for mobile devices

193 JavaScript Advanced193 Using the Geolocation API (cont'd.) Callbacks –Arguments that contain/reference executable code getCurrentPosition() method –Request user's position a single time

194 JavaScript Advanced194 Using the Geolocation API (cont'd.) Table 10-7 Properties passed on a successful geolocation request

195 JavaScript Advanced195 Using the Geolocation API (cont'd.) Basic example: navigator.geolocation.getCurrentPosition(showLocation); function showLocation(position) { console.log("Longitude: " + position.coords.longitude); console.log("Latitude: " + position.coords.latitude); }

196 JavaScript Advanced196 Using the Geolocation API (cont'd.) Enhanced example –Handle failed request, set 10-second timeout: navigator.geolocation.getCurrentPosition(showLocation, fail, ↵ {timeout: 10000}); function showLocation(position) { console.log("Longitude: " + position.coords.longitude); console.log("Latitude: " + position.coords.latitude); } function fail() { var content = document.getElementById("mainParagraph"); content.innerHTML = " Geolocation information not ↵ available or not authorized. "; }

197 JavaScript Advanced197 Using the Geolocation API (cont'd.) Need to fail gracefully in older browsers if (navigator.geolocation { navigator.geolocation.getCurrentPosition(createDirections, ↵ fail, {timeout: 10000}); } else { fail(); }

198 JavaScript Advanced198 Using the Geolocation API (cont'd.) Need to clear geolocation history for testing Table 10-9 Steps to clear saved geolocation history

199 JavaScript Advanced199 Using the Geolocation API (cont'd.) Sometimes users don't notice or ignore geolocation request –Request neither fails or succeeds –Any dependent code not executed

200 JavaScript Advanced200 Using the Geolocation API (cont'd.) Figure 10-10 Flowchart illustrating flow of current geolocation code

201 JavaScript Advanced201 Using the Geolocation API (cont'd.) Can handle lack of yes/no response from user –setTimeout() method –Start countdown before request If timeout expires, stop waiting and trigger failure code If user responds, cancel timeout

202 JavaScript Advanced202 Using the Geolocation API (cont'd.) Figure 10-11 Flowchart illustrating geolocation code that incorporates setTimeout()

203 JavaScript Advanced203 Using the Geolocation API (cont'd.) Code complete to acquire geolocation information –Then you can integrate with databases Using the Google Maps API –Can display a map centered on user's location –Can show route/directions between two locations –Includes 2 constructors Map() creates a map object var name = new google.maps.Map(element, options); LatLng() creates an object containing coordinates center: new google.maps.LatLng(latitude, longitude)

204 JavaScript Advanced204 Using the Geolocation API (cont'd.) Using the Google Maps API (cont'd.) –Example—create new map centered on current position with zoom of 11: var currPosLat = position.coords.latitude; var currPosLng = position.coords.longitude; var mapOptions = { center: new google.maps.LatLng(currPosLat, currPosLng), zoom: 11 }; var map = new google.maps.Map(document.getElementById("map"), ↵ mapOptions);

205 JavaScript Advanced205 Using the Geolocation API (cont'd.) Using the Google Maps API (cont'd.) –Can also create map centered on specified point –Geocoding Converting physical address to latitude/longitude coordinates

206 JavaScript Advanced206 Using the Battery Status API Adds a battery property to Navigator object Table 10-11 Events of the battery object Table 10-10 Properties of the battery object

207 JavaScript Advanced207 Using the Device Orientation API Provides access to changes in position and speed –Gyroscope Device hardware that detects orientation in space deviceorientation event –alpha, beta, and gamma coordinate properties –Accelerometer Device hardware that detects changes in speed devicemotion event –reports values for acceleration and rotation

208 JavaScript Advanced208 Using the WebRTC API Short for web real-time communication Enables apps to –receive data from device camera and microphone –send and receive audio/video/data in real time Should eventually allow text/video chat using only HTML and JavaScript

209 JavaScript Advanced209 Enhancing Mobile Web Apps Testing tools –Often impractical to collect many mobile devices –Online services available for testing –Free testing apps from mobile OS makers: Table 10-12 Software used to simulate mobile devices

210 JavaScript Advanced210 Enhancing Mobile Web Apps (cont'd.) Minimizing Download Size –Mobile speeds usually slower –Mobile users often have data caps

211 JavaScript Advanced211 Enhancing Mobile Web Apps (cont'd.) Minimizing Download Size (cont'd.) –Loading Scripts Responsively Figure 10-14 Implementing responsive script loading for oaktop.htm

212 JavaScript Advanced212 Enhancing Mobile Web Apps (cont'd.) Minifying Files –Removes comments, indents, and line breaks –Tweaks code in other ways to make it smaller –Online minifying services available

213 JavaScript Advanced213 Summary Touch events focus on responding to a user's finger touches on a touchscreen To ensure OS interface doesn't respond to gestures –Use the preventDefault() method Pointer events are different than touch events –Aim to handle input from mouse, finger, or stylus Geolocation API provides access to a user's latitude and longitude coordinates A number of tools exist for testing mobile web apps virtually

214 JavaScript Advanced214 Summary (cont'd.) Important to minimize download size of mobile web app –Load scripts responsively –Minify files

215 JavaScript Advanced Chapter 11 Updating Web Pages with Ajax

216 JavaScript Advanced216 Objectives When you complete this chapter, you will be able to: Describe the steps involved in using Ajax to update data Create an HTTP request and interpret an HTTP response Request and receive server data using the XMLHttpRequest object Process data received from a web service and add it to the DOM Update app data using JSON-P

217 JavaScript Advanced217 Introduction to Ajax Allows client web pages to quickly interact and exchange data with a web server Without reloading entire web page Relies on –Programming language such as JavaScript –Data interchange format such as JSON or XML

218 JavaScript Advanced218 Introduction to Ajax (cont’d.) XMLHttpRequest object (XHR object) –Uses HTTP to exchange data between a client computer and a web server –Can be used to request and receive data without reloading a web page

219 JavaScript Advanced219 Introduction to Ajax (cont’d.) Combining XMLHttpRequest with DHTML –Allows update and modification to individual portions of a web page With data received from a web server Google search suggestions –One of the first commercial Ajax applications Figure 11-1 Google search suggestions provided using Ajax

220 JavaScript Advanced220 Figure 11-2 Standard HTTP request Introduction to Ajax (cont’d.)

221 JavaScript Advanced221 Figure 11-3 HTTP request with the XHR object Introduction to Ajax (cont’d.)

222 JavaScript Advanced222 Understanding the Limitations of Ajax Data requested can be located on a third-party server –Not all web servers or browsers support this Can use a server-side script as a proxy to access data from another domain Proxy –Server that acts for or performs requests for other clients and servers

223 JavaScript Advanced223 Accessing Content on a Separate Domain Web service –Data source made available on one domain for use on other domains across web –Does not contain graphical user interface or command-line interface –Simply provides services and data in response to requests Up to the client to provide an implementation for a program calling a web service –Often requires API key Unique identifier assigned by service to each person/organization that wants access

224 JavaScript Advanced224 Accessing Content on a Separate Domain (cont'd.) Proxy scripts often written in PHP –Language specifically designed to run on web servers

225 JavaScript Advanced225 Running Ajax from a Web Server Must open Ajax files from a web server –With the HTTP (http://) or HTTPS (https://) protocol Can install server software on any computer Popular web server software –Apache HTTP Server –Nginx ("engine-ex") –Microsoft Internet Information Services (IIS)

226 JavaScript Advanced226 Working with HTTP Using Ajax to update data involves 4 steps: 1.Instantiate an XMLHttpRequest object for the web browser where the script will run. 2.Use the XMLHttpRequest object to send a request to the server. 3.Receive the response from the server containing the requested data. 4.Process the data returned from the server, and incorporate the data into the app.

227 JavaScript Advanced227 Working with HTTP (cont'd.) Figure 11-6 Using Ajax to update data

228 JavaScript Advanced228 Working with HTTP (cont'd.) Figure 11-7 Using Ajax with a proxy server to update data

229 JavaScript Advanced229 Working with HTTP (cont'd.) Request –Process of asking for a web page from a web server Response –Web server’s reply Uniform Resource Locator (URL) –A web page's unique address –Consists of two parts Protocol (usually HTTP) Web server’s domain name or a web server’s Internet Protocol address

230 JavaScript Advanced230 Working with HTTP (cont’d.) Hypertext Transfer Protocol (HTTP) –Set of rules defining how requests made by an HTTP client to an HTTP server –Defines how responses returned from an HTTP server to an HTTP client HTTP client –Refers to an application (web browser) making the request HTTP server (another name for a web server) –Refers to a computer that receives HTTP requests and returns responses to HTTP clients

231 JavaScript Advanced231 Working with HTTP (cont’d.) Host –Computer system being accessed by a remote computer W3C and Internet Engineering Task Force jointly develop HTTP –Version 1.1: most recent version of HTTP commonly used today –Version 2.0: in development Modern browser already support some features

232 JavaScript Advanced232 Understanding HTTP Messages HTTP messages –HTTP client requests and server responses HTTP client opens a connection to the server –Submits a request message –Web server returns a response message appropriate to the request type Format: Start line (request method or status returned) Header lines (zero or more) Blank line Message body (optional)

233 JavaScript Advanced233 Understanding HTTP Messages (cont’d.) Headers –Define information about the request or response message and about the contents of the message body 47 HTTP 1.1 headers –generic headers used in request or response messages –headers specific to a request, response, or message body Format for using a header header: value

234 JavaScript Advanced234 Understanding HTTP Messages (cont’d.) Cache-Control header –Specifies how a web browser should cache any server content it receives Caching –Temporary storage of data for faster access –Web browser attempts to locate any necessary data in its cache Before making a request from a web server –Goes against the reason for using Ajax Include Cache-Control: no-cache

235 JavaScript Advanced235 Understanding HTTP Messages (cont’d.) Blank line always follows last header line –Optional: message body can follow the blank line in the messages Most common types of HTTP requests –GET and POST Other HTTP request methods –HEAD, DELETE, OPTIONS, PUT, and TRACE Can use browser tools to examine HTTP headers

236 JavaScript Advanced236 Sending HTTP Requests GET method –Used for standard web page requests –Can have a query string or form data appended to the URL POST request –Similar to a GET request except that any submitted data is included in the message body Immediately following the blank line after the last header

237 JavaScript Advanced237 Table 11-1 Common request headers Sending HTTP Requests (cont’d.)

238 JavaScript Advanced238 Table 11-2 Common message body headers Sending HTTP Requests (cont’d.)

239 JavaScript Advanced239 Receiving HTTP Responses HTTP response messages –Take the same format as request messages –Return protocol and version of the HTTP server Along with a status code and descriptive text Status codes format –1xx: (informational) - Request received –2xx: (success) - Request successful –3xx: (redirection) - Request cannot be completed without further action –4xx: (client error) - Request cannot be fulfilled due to a client error

240 JavaScript Advanced240 Receiving HTTP Responses (cont’d.) –5xx: (server error) - Request cannot be fulfilled due to a server error Table 11-3 Common response codes

241 JavaScript Advanced241 Receiving HTTP Responses (cont’d.) Zero or more response headers follow the status line Response returned from a server –Can be much more involved than original request that generated it Table 11-4 Common response headers

242 JavaScript Advanced242 Requesting Server Data XMLHttpRequest object –Key to incorporating Ajax in JavaScript code –Allows use of use JavaScript and HTTP to exchange data between a web browser and a web server

243 JavaScript Advanced243 Table 11-5 XMLHttpRequest object methods Requesting Server Data (cont’d.)

244 JavaScript Advanced244 Table 11-6 XMLHttpRequest object properties Requesting Server Data (cont’d.)

245 JavaScript Advanced245 Instantiating an XMLHttpRequest Object Use the XMLHttpRequest constructor var httpRequest = new XMLHttpRequest(); Originally created specifically to request XML data –Name hasn't changed, but now capable of more Most JavaScript programmers use a series of nested try/catch statements Opening and closing HTTP connections is a bottleneck in page loading –HTTP/1.1 automatically keeps the client-server connection open unless it is specifically closed Can make Ajax programs faster by reusing an instantiated XMLHttpRequest object

246 JavaScript Advanced246 Instantiating an XMLHttpRequest Object (cont’d.) var curRequest = false; var httpRequest; function getRequestObject() { try { httpRequest = new XMLHttpRequest(); } catch (requestError) { document.getElementById("main").innerHTML = "Your ↵ browser does not support this content"; return false; } return httpRequest; } if (!curRequest) { curRequest = getRequestObject(); }

247 JavaScript Advanced247 Opening and Sending a Request Use the open() method with the instantiated XMLHttpRequest object –To specify the request method ( GET or POST ) and URL open() method accepts three optional arguments –async, username, password abort() method –Used to cancel any existing HTTP requests before beginning a new one

248 JavaScript Advanced248 Opening and Sending a Request (cont’d.) send() method –Submit the request to the server –Accepts a single argument containing the message body POST requests more involved –Must manually build name-value pairs to submit –Must submit at least Content-Type header before send() method –Also should submit Content-Length header and Connection header

249 JavaScript Advanced249 Receiving Server Data responseXML property –Contains the HTTP response as an XML document –Only if server response includes the Content-Type header with a MIME type value of text/xml responseText property –Contains the HTTP response as a text string

250 JavaScript Advanced250 Processing XML Data in a Response Assign property values to document nodes –Assign value of responseXML property to a variable –Use innerHTML and node properties to assign values of XML document stored in variable to appropriate elements

251 JavaScript Advanced251 Processing Text Data in a Response responseText value almost always a JSON string –First use JSON.parse() to convert to object –Then access property values of new object and add to DOM elements

252 JavaScript Advanced252 Sending and Receiving Synchronous Requests and Responses Synchronous request –Stops the processing of the JavaScript code until a response returned from the server Check XMLHttpRequest object’s status property value –Ensure response received successfully

253 JavaScript Advanced253 Sending and Receiving Synchronous Requests and Responses (cont’d.) Synchronous responses –Easier to handle Drawback –Script will not continue processing until the response is received Use asynchronous requests with the send() method

254 JavaScript Advanced254 Sending and Receiving Asynchronous Requests and Responses Asynchronous request –Allows JavaScript to continue processing while it waits for a server response Create an asynchronous request –Pass a value of true as the third argument of the open() method Or omit the argument altogether Receive a response –Use the XMLHttpRequest object’s readyState property and onreadystatechange event

255 JavaScript Advanced255 Sending and Receiving Asynchronous Requests and Responses (cont’d.) Example: stockRequest.abort(); stockRequest.open("get","StockCheck.php?" + "checkQuote=" + ↵ tickerSymbol, true); stockRequest.send(null); stockRequest.onreadystatechange = fillStockInfo;

256 JavaScript Advanced256 Sending and Receiving Asynchronous Requests and Responses (cont’d.) Value assigned to the readyState property –Updated automatically According to the current statement of the HTTP request If property assigned a value of 4 –Response finished loading

257 JavaScript Advanced257 Sending and Receiving Asynchronous Requests and Responses (cont’d.) Example: function fillStockInfo() { if (stockRequest.readyState === 4 && stockRequest.status ↵ === 200) { var stockValues = stockRequest.responseText; document.getElementById("ticker").innerHTML = ↵ stockValues.ticker;... }

258 JavaScript Advanced258 Refreshing Server Data Automatically Automatically refresh data obtained from an HTTP server –Use JavaScript’s setTimeout() or setInterval() methods Send request to the server Read and process the data returned from the server

259 JavaScript Advanced259 Creating Cross-Domain Requests Without a Proxy Server Two alternatives to proxies for working around same-origin policy –JSON-P (JSON with padding) Requests JSON content using a script element rather than an XHR object –CORS (Cross-Origin Resource Sharing) Server sends special response header that indicates data may be used on other domains

260 JavaScript Advanced260 Creating Cross-Domain Requests Without a Proxy Server (cont'd.) Table 11-7 Comparison of XHR proxy, JSON-P, and CORS

261 JavaScript Advanced261 Updating Content with JSON-P script element not subject to same-origin policy Program running on web server returns content –JSON object treated as parameter for function call –Called function processes JSON object

262 JavaScript Advanced262 Updating Content with JSON-P (cont'd.) Figure 11-14 Using JSON-P to update data

263 JavaScript Advanced263 Updating Content with JSON-P (cont'd.) JSON-P URL generally consists of 2 parts: –Request information URL of service, parameters –Callback query string Keyword (usually "callback") & name of function to call

264 JavaScript Advanced264 Updating Content with JSON-P (cont'd.) JSON-P opens a security hole in your website –If data source compromised, content you receive is a potential attack route on your site –Use JSON-P only with web service you trust JSON-P exposes API key or password to end users –Use only with trusted users, such as employees

265 JavaScript Advanced265 Updating Content with CORS Cross-domain request within an XHR object Part of XMLHttpRequest2 specification –Additional properties, methods, and events for XHR object Enables content provider to convey permission –Access-Control-Allow-Origin HTTP response header Value includes requesting domain –XDomainRequest object (Microsoft) Must check first if browser defines this object

266 JavaScript Advanced266 Summary Ajax allows data exchange with web server without reloading page XMLHttpRequest object –Uses HTTP to exchange data between a client computer and a web server Proxy is common technique for working around same-origin policy with Ajax HTTP defines rules for requests and responses between client and server

267 JavaScript Advanced267 Summary (cont’d.) Use methods and properties of an instantiated XMLHttpRequest object with JavaScript First step to exchange data between an HTTP client and a web server –Instantiate an XMLHttpRequest object To improve performance –Call the abort() method of the XMLHttpRequest object Use the send() method with the instantiated XMLHttpRequest object to submit the request to the server

268 JavaScript Advanced268 Summary (cont’d.) Server response assigned to responseXML or responseText property Synchronous request stops the processing of the JavaScript code until a response returned Asynchronous request allows JavaScript to continue processing while waiting for a server response readystatechange event fires when value assigned to readyState property changes

269 JavaScript Advanced269 Summary (cont’d.) JSON with padding (JSON-P) requests JSON content using script element rather than XHR object Cross-Origin Resource Sharing (CORS) –Server sends HTTP response header indicating data may be used on other domains


Download ppt "JavaScript Advanced Chapter 7 Using Object-Oriented JavaScript."

Similar presentations


Ads by Google