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.

Slides:



Advertisements
Similar presentations
Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.
Advertisements

Introducing JavaScript
Essentials for Design JavaScript Level One Michael Brooks
JavaScript FaaDoOEngineers.com FaaDoOEngineers.com.
The Web Warrior Guide to Web Design Technologies
1 Outline 13.1Introduction 13.2A Simple Program: Printing a Line of Text in a Web Page 13.3Another JavaScript Program: Adding Integers 13.4Memory Concepts.
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Chapter 16 Dynamic HTML and Animation The Web Warrior Guide to Web Design Technologies.
Javascript Document Object Model. How to use JavaScript  JavaScript can be embedded into your html pages in a couple of ways  in elements in both and.
XP 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial 10.
Information Technology Center Hany Abdelwahab Computer Specialist.
JavaScript, Third Edition
Web Development & Design Foundations with XHTML Chapter 14 Key Concepts.
Create a Web Site with Frames
Introduction to scripting
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
Scripting Languages.
WEEK 3 AND 4 USING CLIENT-SIDE SCRIPTS TO ENHANCE WEB APPLICATIONS.
Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS.
Week 9 PHP Cookies and Session Introduction to JavaScript.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Client Scripting1 Internet Systems Design. Client Scripting2 n “A scripting language is a programming language that is used to manipulate, customize,
 2008 Pearson Education, Inc. All rights reserved Introduction to XHTML.
Chapter 8 Cookies And Security JavaScript, Third Edition.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
1 JavaScript in Context. Server-Side Programming.
XP Tutorial 10New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with JavaScript Creating a Programmable Web Page for North Pole.
Unit 3 Day 6 FOCS – Web Design. Journal Unit #3 Entry #4 Write the source code that would make the following display on a rendered page: Shopping List.
Using Client-Side Scripts to Enhance Web Applications 1.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
Introduction to JavaScript 41 Introduction to Programming the WWW I CMSC Winter 2004 Lecture 17.
Project 9: Exploring the Document Object Essentials for Design JavaScript Level One Michael Brooks.
Chapter 5: Windows and Frames
Dr. Qusai Abuein1 Internet & WWW How to program Chap.(6) JavaScript:Introduction to Scripting.
Sahar Mosleh California State University San MarcosPage 1 JavaScript Basic.
ECA 225 Applied Interactive Programming1 ECA 225 Applied Online Programming basics.
Project 1: Using Arrays and Manipulating Strings Essentials for Design JavaScript Level Two Michael Brooks.
Chapter 2: Variables, Functions, Objects, and Events JavaScript - Introductory.
XP Tutorial 8 Adding Interactivity with ActionScript.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
 2000 Deitel & Associates, Inc. All rights reserved. Outline 8.1Introduction 8.2A Simple Program: Printing a Line of Text in a Web Page 8.3Another JavaScript.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
JavaScript, Fourth Edition
Project 10: Exploring the Window Object Essentials for Design JavaScript Level One Michael Brooks.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
1 JavaScript in Context. Server-Side Programming.
HTML Basics. HTML Coding HTML Hypertext markup language The code used to create web pages.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Eight String Manipulation.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Project 5: Using Pop-Up Windows Essentials for Design JavaScript Level One Michael Brooks.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
1 CSC160 Chapter 1: Introduction to JavaScript Chapter 2: Placing JavaScript in an HTML File.
REEM ALMOTIRI Information Technology Department Majmaah University.
XP Tutorial 10New Perspectives on HTML, XHTML, and DHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties.
JavaScript Tutorial. What is JavaScript JavaScript is the programming language of HTML and the Web Programming makes computers do what you want them to.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
>> Introduction to JavaScript
Chapter 6 JavaScript: Introduction to Scripting
Project 9 Creating Pop-up Windows, Adding Scrolling Messages, and Validating Forms.
Introduction to Scripting
WEB PROGRAMMING JavaScript.
T. Jumana Abu Shmais – AOU - Riyadh
JavaScript CS 4640 Programming Languages for Web Applications
JavaScript: Introduction to Scripting
Web Programming and Design
JavaScript CS 4640 Programming Languages for Web Applications
Presentation transcript:

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

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

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

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

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

Copyright (c) 2004 Prentice-Hall. All rights reserved. 6 Visual Summary (continued)

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

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

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

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

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";

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

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

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";

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

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:

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

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

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

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

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

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

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

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]

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

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 or mailto: searcha search string appended to a URL such as ?category=12 targetthe target for the link (such as _blank, _parent, or _self)

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

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.

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

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"

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

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);

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"))

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);

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

Copyright (c) 2004 Prentice-Hall. All rights reserved. 36 Assigning the Title Property (continued) Home of the JavaScript Master! document.write(document.title);

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

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"

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="  As of the writing of this book, the location and URL properties are commonly used in many Web sites

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

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=" againsttheclock.com"; The page will redirect to the Against The Clock Web site

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

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()

Copyright (c) 2004 Prentice-Hall. All rights reserved. 44 Controlling Document Loading (continued) ASSIGN()  The assign() method loads a new HTML document : location.assign("  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=" ;  Performs the same function as location.assign("

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();

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);

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");

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

Copyright (c) 2004 Prentice-Hall. All rights reserved. 49 Controlling Document Loading (continued) reload.html relo ad this page This text is new.

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

Copyright (c) 2004 Prentice-Hall. All rights reserved. 51 Controlling Document Loading (continued) replace.html location.replace(" ainsttheclock.com");

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

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:

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);

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

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.

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

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

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

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

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!");

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);

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()

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

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

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

Copyright (c) 2005 Prentice-Hall. All rights reserved. 67 lastIndexOf() Method Return

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

Copyright (c) 2005 Prentice-Hall. All rights reserved. 69 Returning a Substring Return

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

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

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

Copyright (c) 2005 Prentice-Hall. All rights reserved. 73 Populate at Design Time Return

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

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

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

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

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()

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

Copyright (c) 2005 Prentice-Hall. All rights reserved. 80 Splitting a String Return

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

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

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

Copyright (c) 2005 Prentice-Hall. All rights reserved. 84 Precedence Errors Return

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

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

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

Copyright (c) 2005 Prentice-Hall. All rights reserved. 88 Common Math Object Methods Math.abs() Math.max() Math.pow() Math.round() Math.sqrt()

Copyright (c) 2005 Prentice-Hall. All rights reserved. 89 The Math.abs() Method Returns the absolute value of the number passed to it. Return

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

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

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

Copyright (c) 2005 Prentice-Hall. All rights reserved. 93 The Math.sqrt() Method Returns the square root of the number passed to it. Return

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

Copyright (c) 2005 Prentice-Hall. All rights reserved. 95 The Math.random() Method Return

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

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.

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

Copyright (c) 2005 Prentice-Hall. All rights reserved. 99 The getMonth() Method

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

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

Copyright (c) 2004 Prentice-Hall. All rights reserved. 102 The switch Statement Return

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

Copyright (c) 2004 Prentice-Hall. All rights reserved. 104 Using a while loop Return

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

Copyright (c) 2004 Prentice-Hall. All rights reserved. 106 Using a do while loop Return

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

Copyright (c) 2004 Prentice-Hall. All rights reserved. 108 Using a for Statement Return

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

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.

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

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

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

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.”);

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

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++; }

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);

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();

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; }

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);

Copyright (c) 2004 Prentice-Hall. All rights reserved. 121 Using a Form Element Incorrect Versions Correct Versions Return document.form1. ; document.forms[1].state; document.form1. .value; document.forms[1].state.value;

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);

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