Download presentation
Presentation is loading. Please wait.
Published byNicholas Jackson Modified over 9 years ago
1
Copyright (c) 2004 Prentice-Hall. All rights reserved. 1 Why Would I Do This? The document object: represents the HTML code that: exists within an individual window object gives us a way to interact with various elements of the HTML code contains many objects that represent various aspects of the HTML code contained in the document
2
Copyright (c) 2004 Prentice-Hall. All rights reserved. 2 Why Would I Do This? (continued) Objects are represented by arrays An array: is a temporary storage space for information is different from a variable because it takes on multiple elements
3
Copyright (c) 2004 Prentice-Hall. All rights reserved. 3 Why Would I Do This? (continued) In JavaScript: the first element of an array is usually referred to as [0] most HTML tags are represented by an element in the matching array
4
Copyright (c) 2004 Prentice-Hall. All rights reserved. 4 Why Would I Do This? (continued) Many objects exist within the document object, to represent HTML elements such as: image objects to represent tags link objects to represent tags form objects to represent tags
5
Copyright (c) 2004 Prentice-Hall. All rights reserved. 5 Visual Summary The document object contains various objects, methods and properties designed to interact with the HTML document Collectively, this group is referred to as the Document Object Model (DOM) The Document Object Model
6
Copyright (c) 2004 Prentice-Hall. All rights reserved. 6 Visual Summary (continued)
7
Copyright (c) 2004 Prentice-Hall. All rights reserved. 7 Changing Color Properties HTML allows various color properties to be set by the user such as: The background color of a Web page The color of text displayed on that page Other color properties can control the color of hyperlinks This statement changes the default background color to dark blue
8
Copyright (c) 2004 Prentice-Hall. All rights reserved. 8 Changing Color Properties (continued) When color is written as a hexadecimal number which represents RGB color values: The first two digits represent the amount of red The second two digits represent the amount of green The third two digits represent the amount of blue
9
Copyright (c) 2004 Prentice-Hall. All rights reserved. 9 Changing Color Properties (continued) Designers can also choose to represent colors using simple names such as in the following example Color attributes from HTML also have matching representation in JavaScript These attributes can be accessed through properties of the document object
10
Copyright (c) 2004 Prentice-Hall. All rights reserved. 10 Changing Color Properties (continued) Changing Default Link Colors Every Web browser sets default link colors for: links active links visited links Link colors can be set using hexadecimal colors or color names
11
Copyright (c) 2004 Prentice-Hall. All rights reserved. 11 Changing Color Properties (continued) alinkColor The alinkColor property is used to display the active link the active link is the currently active link that will be displayed if you click the mouse on it or press the return key If you wanted to set the alinkColor property to white, you could type the following statement: document.alinkColor="#FFFFFF";
12
Copyright (c) 2004 Prentice-Hall. All rights reserved. 12 Changing Color Properties (continued) linkColor The linkColor property holds the default color used to display hyperlinks Hyperlinks which have not been currently selected and have not been recently visited will appear in the color specified by this property
13
Copyright (c) 2004 Prentice-Hall. All rights reserved. 13 Changing Color Properties (continued) vlinkcolor The vlinkColor property represents links which have been recently visited by the Web browser Every Web browser keeps a history list of URLs or files that have been recently visited If a hyperlink represents a file that is cataloged in the history listed, it will appear in the color represented by the vlinkColor property
14
Copyright (c) 2004 Prentice-Hall. All rights reserved. 14 Changing Color Properties (continued) Changing the background color property The bgColor property allows us to specify the background color of the HTML document This property represents the same value that can be set using the bgcolor attribute of the tag To set the background color to red, we could write the following command document.bgColor="#FF0000";
15
Copyright (c) 2004 Prentice-Hall. All rights reserved. 15 Changing Color Properties (continued) Changing the foreground color property The fgColor property allows us to specify the foreground color of the HTML document The foreground color represents the default text color specified in the tag of an HTML document
16
Copyright (c) 2004 Prentice-Hall. All rights reserved. 16 Changing Color Properties (continued) The following command allows us to set the foreground color property to red. document.fgColor="#FF0000"; This property represents the same value as the text attribute of the HTML tag The following line of HTML code will achieve the same result:
17
Copyright (c) 2004 Prentice-Hall. All rights reserved. 17 Changing Color Properties (continued) Link Color Properties In most browsers, the link colors will change to purple to indicate a link to a site we have previously visited
18
Copyright (c) 2004 Prentice-Hall. All rights reserved. 18 Changing Color Properties (continued) main.html - demonstrates link color properties // change link color properties document.alinkColor="#CC0000";// dark red document.vlinkColor="#666666"; // dark gray document.linkColor="#FF0000";// bright red Main Page Links: Main About Us Products Most links on the main page will appear in dark gray since we have recently visited these pages
19
Copyright (c) 2004 Prentice-Hall. All rights reserved. 19 Changing Color Properties (continued) Set Background and Foreground Colors backgroundcolor.html This page demonstrates various color properties. alert("Hello!"); The background and foreground of the page are set
20
Copyright (c) 2004 Prentice-Hall. All rights reserved. 20 Changing Color Properties (continued) backgroundcolor.html This page demonstrates various color properties. alert("Hello!"); //set background to white document.bgColor="#FFFFFF"; // set text to black document.fgColor="#000000"; The background and foreground colors of the page change
21
Copyright (c) 2004 Prentice-Hall. All rights reserved. 21 Using Properties of the Links Object Many tags in HTML also have matching objects in JavaScript This allows JavaScript to access and control various aspects of HTML JavaScript also creates an array to keep track of each type of object it creates each object is referenced as an element of the array
22
Copyright (c) 2004 Prentice-Hall. All rights reserved. 22 Using Properties of the Links Object (continued) The array that stores information about hyperlinks is referred to as the links array Each object referenced in the array is referred to as a link object
23
Copyright (c) 2004 Prentice-Hall. All rights reserved. 23 Using Properties of the Links Object (continued) The links Array and Link Object Whenever an tag is used in the HTML code to create a link, an entry is made in the links array for the document Aside from creating an entry in the links array, a link object is also created by JavaScript Each link object contains a variety of properties which describe characteristics of each hyperlink in the HTML document
24
Copyright (c) 2004 Prentice-Hall. All rights reserved. 24 Using Properties of the Links Object (continued) HTML documents create hyperlinks with statements such as: Against the Clock Website Assuming this link is the first hyperlink in the HTML document, it can be referred to in JavaScript in the following manner: document.links[0]
25
Copyright (c) 2004 Prentice-Hall. All rights reserved. 25 Using Properties of the Links Object (continued) The link object has number of useful properties: the link.href property specifies the entire hypertext reference specified in a HTML hyperlink the link.pathname property, which includes the path to the file, not including the domain name Commonly used link properties Commonly used link properties
26
Copyright (c) 2004 Prentice-Hall. All rights reserved. 26 Using Properties of the Links Object (continued) PropertyRepresents hrefentire URL entered in hyperlink domaindomain name in a URL hashinternal anchor links in a URL (such as #products). innerHTMLtext between the and tags pathnamepath to the a file, not including the domain name protocolthe protocol in a hyperlink, such as http:,ftp:, or mailto: searcha search string appended to a URL such as ?category=12 targetthe target for the link (such as _blank, _parent, or _self)
27
Copyright (c) 2004 Prentice-Hall. All rights reserved. 27 Using Properties of the Links Object (continued) Properties such as href and target represent the same information as the HTML attributes of the same name Consider the following line of HTML code as an example. Secure, Inc. The target property would be _blank
28
Copyright (c) 2004 Prentice-Hall. All rights reserved. 28 Using Properties of the Links Object (continued) Using Properties of the Links Object linkshref.html Against the Clock document.write("Link object href: " + document.links[0].href); The href property contains the text specified in the href attribute of the tag.
29
Copyright (c) 2004 Prentice-Hall. All rights reserved. 29 Using Properties of the Links Object (continued) Use the Pathname Property linkshref.html Against the Clock document.write("Link object href: " + document.links[0].href); document.write(" "); document.write("Link object pathname: " + document.links[0].pathname); The pathname is the location of the file not including the domain name
30
Copyright (c) 2004 Prentice-Hall. All rights reserved. 30 Using Properties of the Links Object (continued) URL parameters pass information from one page to another by including a question mark and additional info on the end of a URL in a hyperlink: The information starting with the question mark can be accessed using the link.search property href="products.html?product=ovens"
31
Copyright (c) 2004 Prentice-Hall. All rights reserved. 31 Employing the Anchors Array Text anchors are used in HTML to create a link to somewhere else in the HTML document The point to be linked to is known as an anchor an anchor is simply an tag that has a name attribute: We can use the following command in our HTML code to create a link to the "F" section of our glossary page: go to F section
32
Copyright (c) 2004 Prentice-Hall. All rights reserved. 32 Employing the Anchors Array (continued) You can link to a named anchor in an external document by specifying the filename in the link: F The anchors array represents each text anchor as specified in the HTML code: To output the name of the second anchor object to the screen, we could write the following statement: document.write("Anchors object: " + document.anchors[1].name);
33
Copyright (c) 2004 Prentice-Hall. All rights reserved. 33 Employing the Anchors Array (continued) Use the Anchor Object Text anchors can be created in JavaScript as well as HTML Book Index The following code will create the same anchor on a string of text (or variable) called myString var myString = "Book Index"; document.write(myString.anchor("bookanchor"))
34
Copyright (c) 2004 Prentice-Hall. All rights reserved. 34 Assigning the Title Property The title property holds the title specified within the and tags of the HTML document This is the text that appears in the title bar of most browsers Home of the JavaScript Master! We can output the title property to the screen with the following statement: document.write(document.title);
35
Copyright (c) 2004 Prentice-Hall. All rights reserved. 35 Assigning the Title Property (continued) The title property holds the title specified within the and tags of the HTML document This is the text that appears in the title bar of most browsers Home of the JavaScript Master! We can output the title property to the screen with the following statement: document.write(document.title); Example Example
36
Copyright (c) 2004 Prentice-Hall. All rights reserved. 36 Assigning the Title Property (continued) Home of the JavaScript Master! document.write(document.title);
37
Copyright (c) 2004 Prentice-Hall. All rights reserved. 37 Assigning the Title Property (continued) The title property can also be changed by assigning a new text string to the property In newer browsers, this will cause the title bar to change the title message The title of the page can be changed after the page is loaded in Internet Explorer version 5 and above and in Netscape Navigator version 6 and newer
38
Copyright (c) 2004 Prentice-Hall. All rights reserved. 38 Assigning the Title Property (continued) Change the Title of the Page Dynamically My Cool Site Click here to change the title to say: My Hot Site If you choose, the link and your title bar should change to say "My Hot Site"
39
Copyright (c) 2004 Prentice-Hall. All rights reserved. 39 Using the location and URL Properties The Location Property The location property holds the address of the current HTML document Changing the location property forces the Web browser to load the page stored at the new address: document.location="http://www.againsttheclock.com"; As of the writing of this book, the location and URL properties are commonly used in many Web sites
40
Copyright (c) 2004 Prentice-Hall. All rights reserved. 40 Using the location and URL Properties (continued) The URL Property The URL property is almost identical to the location property In Internet Explorer, changing the URL property will force the browser to load the new page In Netscape Navigator, changing the URL property will not change the current page
41
Copyright (c) 2004 Prentice-Hall. All rights reserved. 41 Using the location and URL Properties (continued) Use the Location Property location.html This page will redirect to Against the Clock document.location="http://www. againsttheclock.com"; The page will redirect to the Against The Clock Web site
42
Copyright (c) 2004 Prentice-Hall. All rights reserved. 42 Controlling Document Loading The location property: Is the most useful since it is better supported in most browsers Is also an object in JavaScript, known as the location object the location object allows us to change the browser’s URL or reload the current document
43
Copyright (c) 2004 Prentice-Hall. All rights reserved. 43 Controlling Document Loading (continued) Methods also exist which will allow us to change the current URL Methods of the location object are used for this purpose The primary methods of the location object are: assign() reload() replace()
44
Copyright (c) 2004 Prentice-Hall. All rights reserved. 44 Controlling Document Loading (continued) ASSIGN() The assign() method loads a new HTML document : location.assign("http://www.againsttheclock.com"); If we were using a relative hyperlink the statement would be written in this fashion: location.assign("index.html"); The href property performs the same function in JavaScript as the assign() method: location.href="http://www.againsttheclock.com" ; Performs the same function as location.assign("http://www.againsttheclock.com");
45
Copyright (c) 2004 Prentice-Hall. All rights reserved. 45 Controlling Document Loading (continued) reload() The reload() method: reloads the current HTML document performs the same function as choosing the Reload button in Netscape or the Refresh button in Internet Explorer Using the reload() method without arguments will cause the page to reload if any changes have been made to the file location.reload();
46
Copyright (c) 2004 Prentice-Hall. All rights reserved. 46 Controlling Document Loading (continued) We can specify a Boolean argument of true to force the browser to reload the page even if the page hasn't changed location.reload(true);
47
Copyright (c) 2004 Prentice-Hall. All rights reserved. 47 Controlling Document Loading (continued) replace() The replace() method replaces the currently loaded URL with a different one location.replace("newfile.html");
48
Copyright (c) 2004 Prentice-Hall. All rights reserved. 48 Controlling Document Loading (continued) Use reload() Forcing the browser to reload the page, even if the page hasn't changed might be useful in situations where the page changes based on choices made by the user Example
49
Copyright (c) 2004 Prentice-Hall. All rights reserved. 49 Controlling Document Loading (continued) reload.html relo ad this page This text is new.
50
Copyright (c) 2004 Prentice-Hall. All rights reserved. 50 Controlling Document Loading (continued) Use replace() The replace() method is often useful in e- commerce applications. for security reasons, we may not want a Web surfer to be able to return to the last document when we are gathering sensitive information or processing an e- commerce transaction. Example Example
51
Copyright (c) 2004 Prentice-Hall. All rights reserved. 51 Controlling Document Loading (continued) replace.html location.replace("http://www.ag ainsttheclock.com");
52
Copyright (c) 2004 Prentice-Hall. All rights reserved. 52 Implementing History Methods Browsers were designed to be easy enough for anyone to use Each browser window has a unique history list JavaScript creates a history object for each open browser window The history object allows us to access and manipulate the contents of the browser's history list This is often used to create back or forward buttons within a web interface which will perform the same actions as the back and forward buttons in the browser
53
Copyright (c) 2004 Prentice-Hall. All rights reserved. 53 Implementing History Methods (continued) back() The back() method of the history object allows us to change a browser window to the previous page in the history list history.back(); By incorporating an event handler with the back() method, we can create a button which will perform the same command as the browser's back button:
54
Copyright (c) 2004 Prentice-Hall. All rights reserved. 54 Implementing History Methods (continued) FORWARD() The forward() method of the history object allows us to change a browser window to the next page in the history list history.forward(); go() The go() method allows the browser to jump forward or backward anywhere in the history list history.go(-2);
55
Copyright (c) 2004 Prentice-Hall. All rights reserved. 55 Implementing History Methods (continued) Using the History Object to Create Buttons The history object was originally designed to also hold the names of all URL's in the browser's history list This capability: gave developers the ability to read a list of sites users had recently visited prompted privacy concerns from browser users and was removed from newer browsers Example Example
56
Copyright (c) 2004 Prentice-Hall. All rights reserved. 56 Implementing History Methods (continued) Page 1 Page 1 | Page 2 | Page 3 | Page 4 | Page 5 This is page 1.
57
Copyright (c) 2004 Prentice-Hall. All rights reserved. 57 Recognize Other Methods and Properties The Applets Array The Java programming language can be used to create applets an applet is a self-contained computer program, often used with Web sites Java applets can be inserted into an HTML document by using the tag the applets array in JavaScript creates an element for every use of the tag in the HTML document
58
Copyright (c) 2004 Prentice-Hall. All rights reserved. 58 Recognize Other Methods and Properties (continued) The forms Array Every time the and tag is used in the HTML document, JavaScript creates a corresponding object in the forms array The form object: is a sub-part of the document object has sub-objects associated with each part of the form
59
Copyright (c) 2004 Prentice-Hall. All rights reserved. 59 Recognize Other Methods and Properties (continued) The images Array Whenever an tag is used in HTML, a corresponding entry is made in JavaScript within the images array the entries in the images array can be used to create image rollovers and manipulate images to create animation each element of the images array contains information about an image object each image object represents an image shown on the page
60
Copyright (c) 2004 Prentice-Hall. All rights reserved. 60 Recognize Other Methods and Properties (continued) The Lastmodified Property The lastModified property holds the date when the HTML file was last saved onto a disk document.write("Document last updated: " + document.lastModified); The lastModified property is useful for pages containing time sensitive information
61
Copyright (c) 2004 Prentice-Hall. All rights reserved. 61 Recognize Other Methods and Properties (continued) Document Object Methods open() and close() the open() and close() methods are methods of the window object and methods of the document object write and writeln both methods simply output text to the browser window unlike the write() method, the writeln() method adds a new line character to the end of the text document.writeln("Hi World!");
62
Copyright (c) 2004 Prentice-Hall. All rights reserved. 62 Recognize Other Methods and Properties (continued) Use the lastModified Property lastmodified.html This page is used to demonstrate the lastModified property of the document object. document.write("This document was last modified "+document.lastModified);
63
Copyright (c) 2005 Prentice-Hall. All rights reserved. 63 Using String Methods toUpperCase() – returns string in all uppercase letters toUpperCase() charAt() – returns a single character charAt() indexOf() – returns the position of a substring indexOf() substring() – extracts a substring from another string substring()
64
Copyright (c) 2005 Prentice-Hall. All rights reserved. 64 toUpperCase() Method Returns a string in all upper case toLowerCase() method returns string in all lower case Return
65
Copyright (c) 2005 Prentice-Hall. All rights reserved. 65 charAt() Method Returns a single character Based on specified position in string Required argument – specified position Return
66
Copyright (c) 2005 Prentice-Hall. All rights reserved. 66 indexOf() Method Searches a string for a substring Returns the location where the substring begins Returns –1 if substring is not found lastIndexOf() method begins searching at the end of the string lastIndexOf() Return
67
Copyright (c) 2005 Prentice-Hall. All rights reserved. 67 lastIndexOf() Method Return
68
Copyright (c) 2005 Prentice-Hall. All rights reserved. 68 substring() Method Returns a substring from a larger string Returns a substring Requires one argument, the starting position One optional argument, the ending position Return
69
Copyright (c) 2005 Prentice-Hall. All rights reserved. 69 Returning a Substring Return
70
Copyright (c) 2005 Prentice-Hall. All rights reserved. 70 Creating and Populating Arrays Each element in array represented by an index, placed within a bracket window[1] refers to the second element in the “window” array Array() Constructor method Using numbered array elements Applying named array elements
71
Copyright (c) 2005 Prentice-Hall. All rights reserved. 71 array() Constructor Method Creates a new array Can specify length, or number of elements Can also create object without specifying length Can use constructor to specify elements in array Return
72
Copyright (c) 2005 Prentice-Hall. All rights reserved. 72 Using Numbered Array Elements Populate by specifying index and assigning value. Can be populated at design time or run timepopulated at design time Elements can be used in an output statement or assigned to variables. Return
73
Copyright (c) 2005 Prentice-Hall. All rights reserved. 73 Populate at Design Time Return
74
Copyright (c) 2005 Prentice-Hall. All rights reserved. 74 Applying Named Array Elements Array can contain variables of different data types Populate, update, or output elements by referring to name rather than index Return
75
Copyright (c) 2005 Prentice-Hall. All rights reserved. 75 Sorting Arrays sort() method reorders the contents of an array By default, sorted in ascending order Custom sort order can be specified Older browsers may require that a sort order be specified
76
Copyright (c) 2005 Prentice-Hall. All rights reserved. 76 Incorporating Array Methods pop() method returns last element in array Also removes last element from array push() method adds element to end of array reverse() method reverses the order of all elements in an array shift() method removes first element in array Other elements move up one position in array unShift() method adds element before the first element Other elements move down one position in array
77
Copyright (c) 2005 Prentice-Hall. All rights reserved. 77 Incorporating Array Methods (cont) shift() method removes first element in array Other elements move up one position in array unShift() method adds element before the first element Other elements move down one position in array
78
Copyright (c) 2005 Prentice-Hall. All rights reserved. 78 Splitting and Joining Strings Delimiter – marks the beginning or end of a unit of data Can be a single character or group of characters Commas, tabs, and spaces most commonly used split() method – splits a string into an array split() join() method – joins elements in an array into a string join()
79
Copyright (c) 2005 Prentice-Hall. All rights reserved. 79 split() Method Splits an string into an array Splits an string Each unit of data in string becomes an array element You must specify delimiter Return
80
Copyright (c) 2005 Prentice-Hall. All rights reserved. 80 Splitting a String Return
81
Copyright (c) 2005 Prentice-Hall. All rights reserved. 81 join() Method Joins all text elements in array into a string You must specify the character used to separate elements Return
82
Copyright (c) 2005 Prentice-Hall. All rights reserved. 82 Array Terminology Stack – last item added to array is first to be retrieved A Last In, First Out (LIFO) approach Queue – first item added to array is first to be retrieved A First In, First Out (FIFO) approach
83
Copyright (c) 2005 Prentice-Hall. All rights reserved. 83 Understanding Operators and Precedence Calculations made from left to right, in the following order: Calculations made from left to right Calculations in parentheses, dots, or brackets Increment and decrement operations Multiplication, division, modulus operations Addition and subtraction
84
Copyright (c) 2005 Prentice-Hall. All rights reserved. 84 Precedence Errors Return
85
Copyright (c) 2005 Prentice-Hall. All rights reserved. 85 Assignment Operators Assignment operator (=) assigns a value to a variable Modulus operator (%) finds the remainder left over after division Bitwise operator examines a single bit of computer memory
86
Copyright (c) 2005 Prentice-Hall. All rights reserved. 86 Common Assignment Operators A-=B Equivalent to A = A-B A+=B Equivalent to A = A+B A*=B Equivalent to A = A*B A/=B Equivalent to A=A/B A++ Equivalent to A=A+1 A- - Equivalent to A=A-1
87
Copyright (c) 2005 Prentice-Hall. All rights reserved. 87 Using Math Object methods Math object – built-in JavaScript object Contains constant values Pi is a constant value Methods simplify complex calculations sqrt() method returns square root
88
Copyright (c) 2005 Prentice-Hall. All rights reserved. 88 Common Math Object Methods Math.abs() Math.max() Math.pow() Math.round() Math.sqrt()
89
Copyright (c) 2005 Prentice-Hall. All rights reserved. 89 The Math.abs() Method Returns the absolute value of the number passed to it. Return
90
Copyright (c) 2005 Prentice-Hall. All rights reserved. 90 The Math.max() Method Returns the largest number in a group of numbers Math.min() returns the smallest number Return
91
Copyright (c) 2005 Prentice-Hall. All rights reserved. 91 The Math.pow() Method Returns a number raised to a given power First argument – base number Second argument - exponent Return
92
Copyright (c) 2005 Prentice-Hall. All rights reserved. 92 The Math.round() Method Returns the nearest integer to the number passed to it Requires the number you want to round Cannot be used to round to a given number of decimal places Return
93
Copyright (c) 2005 Prentice-Hall. All rights reserved. 93 The Math.sqrt() Method Returns the square root of the number passed to it. Return
94
Copyright (c) 2005 Prentice-Hall. All rights reserved. 94 Generating Random Numbers Math.random() method returns a random number between 0 and 1. Math.random() This number can be multiplied by another number. For example, multiply by 100 to produce a number between 0 and 99. Use the math.round() method to round to an integer
95
Copyright (c) 2005 Prentice-Hall. All rights reserved. 95 The Math.random() Method Return
96
Copyright (c) 2005 Prentice-Hall. All rights reserved. 96 Incorporating Math Properties Math object properties cannot be changed Referred to as constant property Common properties: Math.E used in many scientific calculations Math.PI returns Pi Math.SQRT2 returns the square root of 2
97
Copyright (c) 2005 Prentice-Hall. All rights reserved. 97 Getting and Setting Time Units Date class used to hold date and time information New constructor creates new instance of date object If no argument passed in, returns current date and time A specific date can be passed to date object Time stored in 24-hour format If time omitted, computer stores midnight as time.
98
Copyright (c) 2005 Prentice-Hall. All rights reserved. 98 Methods of the Date Class Allow programmers to create dates and change existing dates Dates can be output in several ways
99
Copyright (c) 2005 Prentice-Hall. All rights reserved. 99 The getMonth() Method
100
Copyright (c) 2005 Prentice-Hall. All rights reserved. 100 Related Methods getDate() returns the day of the month getDay() returns the day of the week getFullYear() returns the year as a four-digit number getHours() returns the hour of the day getMinutes() returns the minutes of the hour getSeconds() returns the seconds Return
101
Copyright (c) 2004 Prentice-Hall. All rights reserved. 101 Choosing Options with Switch and Break switch statement gives more flexibility than an if statement switch Works well when you have several known possible values Easy to write and understand Interpreter executes very quickly break keyword causes code to jump to end of switch statement
102
Copyright (c) 2004 Prentice-Hall. All rights reserved. 102 The switch Statement Return
103
Copyright (c) 2004 Prentice-Hall. All rights reserved. 103 Performing Actions Using “While” Loops while loop executes a block of statements as long as a statement is true while Very helpful when processing all elements in an array Will never execute if condition is false the first time
104
Copyright (c) 2004 Prentice-Hall. All rights reserved. 104 Using a while loop Return
105
Copyright (c) 2004 Prentice-Hall. All rights reserved. 105 Performing Actions Using “Do While” Loops Similar to while loop, but will always execute at least oncewill always execute Test for condition at end of loop Use when you need to ensure that a block of code is run at least once
106
Copyright (c) 2004 Prentice-Hall. All rights reserved. 106 Using a do while loop Return
107
Copyright (c) 2004 Prentice-Hall. All rights reserved. 107 Incorporating “For” Statements Requires three arguments Setup condition – a variable that creates the beginning state of the loop End-of-loop test – condition evaluated after each iteration to determine when loop stops executing Modify condition – specifies an action performed after each iteration Can be nested inside another for statement
108
Copyright (c) 2004 Prentice-Hall. All rights reserved. 108 Using a for Statement Return
109
Copyright (c) 2004 Prentice-Hall. All rights reserved. 109 Finding Code Errors Syntax errors – errors in the grammatical rules of JavaScript Misspelling method or property names Omitting a closing parenthesis or quotation mark Logic errors – when the code does something other than what it was intended to do. Multiplying two numbers instead of adding them
110
Copyright (c) 2004 Prentice-Hall. All rights reserved. 110 Writing Clean Code Use white space to make your code more readable Place a semicolon at the end of each statement Use comments Break complex problems down into manageable chunks.
111
Copyright (c) 2004 Prentice-Hall. All rights reserved. 111 Writing Clean Code (cont.) If you use a segment of code repeatedly, write it as a function Use variable and function names that are easy to identify and understand Avoid using methods, objects, or properties that aren’t widely supported
112
Copyright (c) 2004 Prentice-Hall. All rights reserved. 112 Identifying Common Scripting Errors Leaving off ending characters Using the assignment operator instead of the equality operator Using the assignment operator Creating infinite loops Using undefined variables Inserting unneeded semicolons
113
Copyright (c) 2004 Prentice-Hall. All rights reserved. 113 Identifying Common Scripting Errors (cont.) Omitting break statements in a switch statement Omitting break statements Calling non-existent methods, functions, or properties Calling non-existent methods Using a form element instead of its value Using a form element Incorrect data type
114
Copyright (c) 2004 Prentice-Hall. All rights reserved. 114 Leaving off Ending Characters Incorrect Versions Correct Versions Return document.write(“Hi everyone!); j=x[32+1; alert(“You chose the luxury option.”; document.write(“Hi everyone!”); j=x[32]+1; alert(“You chose the luxury option.”);
115
Copyright (c) 2004 Prentice-Hall. All rights reserved. 115 Using the Assignment Operator Incorrect Versions Correct Versions Return if (number=32) var number == 32 if (number==32) var number=32
116
Copyright (c) 2004 Prentice-Hall. All rights reserved. 116 Creating Infinite Loops Incorrect Versions Correct Versions Return x=1; while (x<32) { doSomething(x); } x=1; while (x<32) { doSomething(x); x++; }
117
Copyright (c) 2004 Prentice-Hall. All rights reserved. 117 Using Undefined Variables Incorrect Versions Correct Versions Return document.write(firstName);firstName=“Joe”; document.write(firstName);
118
Copyright (c) 2004 Prentice-Hall. All rights reserved. 118 Inserting Unneeded Semicolons Incorrect Versions Correct Versions Return if (paid==true); makePayment(); if (paid==true) makePayment();
119
Copyright (c) 2004 Prentice-Hall. All rights reserved. 119 Omitting Break Statements Incorrect Versions Correct Versions Return switch (payment) { case “cash”: doSomething(); case “credit”: doSomethingElse(); } switch (payment) { case “cash”: doSomething(); break; case “credit”: doSomethingElse(); break; }
120
Copyright (c) 2004 Prentice-Hall. All rights reserved. 120 Calling Non-Existent Methods Incorrect Versions Correct Versions Return window.screenSize; window.makeSmaller(); screen.availWidth; window.resizeBy(-200,-200);
121
Copyright (c) 2004 Prentice-Hall. All rights reserved. 121 Using a Form Element Incorrect Versions Correct Versions Return document.form1.email; document.forms[1].state; document.form1.email.value; document.forms[1].state.value;
122
Copyright (c) 2004 Prentice-Hall. All rights reserved. 122 Incorrect Data Type Incorrect Versions Correct Versions Return x=prompt(“Enter a number”); result = x+32; document.write(“x plus 32 equals” + result); x=prompt(“Enter a number”) result = parseInt(x) + 32; document.write(“x plus 32 equals “ + result);
123
Copyright (c) 2005 Prentice-Hall. All rights reserved. 123 Determining OS and Browser Information navigator object – describes properties of viewer’s browser appName property – identifies browser type appVersion property – identifies version number language property – identifies language the browser displays platform property – displays operating system in use
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.