javascript tutorial - 4730-5

301
TM IDG BOOKS IDG BOOKS ® From & IDG Books Worldwide, Inc. An International Data Group Company Foster City, CA • Indianapolis • Chicago • New York TM JavaScript Your visual blueprint for building dynamic Web pages by Kelly L. Murdock

Upload: api-3835536

Post on 10-Apr-2015

495 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Javascript Tutorial - 4730-5

TM

IDGBOOKSIDGBOOKS

®

From

&IDG Books Worldwide, Inc.

An International Data Group Company

Foster City, CA • Indianapolis • Chicago • New York

TM

JavaScript™Your visual blueprint for

building dynamic Web pages

by Kelly L. Murdock

Page 2: Javascript Tutorial - 4730-5

Published byIDG Books Worldwide, Inc.An International Data Group Company919 E. Hillsdale Blvd., Suite 400Foster City, CA 94404

www.idgbooks.com (IDG Books Worldwide Web Site)

Text and Illustrations Copyright © 2000 IDG Books Worldwide, Inc. Certain textand illustrations © 1992-2000 maranGraphics, Inc., used with maranGraphics'permission.

Design Copyright© 1992-2000 by maranGraphics Inc. 5755 Coopers AvenueMississauga, Ontario, Canada L4Z 1R9

All rights reserved. No part of this book, including interior design, cover design, and icons, may be reproduced or transmitted in any form, by any means (electronic, photocopying, recording, or otherwise) without prior written permission.

Library of Congress Catalog Card No.: 00-000000ISBN: 0-7645-4730-5 Printed in the United States of America10 9 8 7 6 5 4 3 2 1

1V/TR/QY/QQ/IN

Distributed in the United States by IDG Books Worldwide, Inc.Distributed by CDG Books Canada Inc. for Canada; by Transworld PublishersLimited in the United Kingdom; by IDG Norge Books for Norway; by IDG SwedenBooks for Sweden; by IDG Books Australia Publishing Corporation Pty. Ltd. forAustralia and New Zealand; by TransQuest Publishers Pte Ltd. for Singapore,Malaysia, Thailand, Indonesia, and Hong Kong; by Gotop Information Inc. forTaiwan; by ICG Muse, Inc. for Japan; by Intersoft for South Africa; by Eyrolles for France; by International Thomson Publishing for Germany, Austria andSwitzerland; by Distribuidora Cuspide for Argentina; by LR International for Brazil; by Galileo Libros for Chile; by Ediciones ZETA S.C.R. Ltda. for Peru; by WS Computer Publishing Corporation, Inc. for the Philippines; byContemporanea de Ediciones for Venezuela; by Express Computer Distributors for the Caribbean and West Indies; by Micronesia Media Distributor, Inc. forMicronesia; by Chips Computadoras S.A. de C.V. for Mexico; by Editorial Norma de Panama S.A. for Panama; by American Bookshops for Finland.For corporate orders, please call maranGraphics at 800-469-6616.For general information on IDG Books Worldwide’s books in the U.S., please call our Consumer Customer Service department at 800-762-2974.For reseller information, including discounts and premium sales, please call our Reseller Customer Service department at 800-434-3422.For information on where to purchase IDG Books Worldwide’s books outside the U.S., please contact our International Sales department at 317-572-3993 or fax 317-572-4002.For consumer information on foreign language translations, please contact our Customer Service department at 800-434-3422, fax 317-572-4002, or e-mail [email protected] information on licensing foreign or domestic rights, please phone 650-653-7098.For sales inquiries and special prices for bulk quantities, please contactour Order Services department at 800-434-3422.For information on using IDG Books Worldwide’s books in the classroom or for ordering examination copies, please contact our Educational Sales department at 800-434-2086 or fax 317-572-4005.For press review copies, author interviews, or other publicity information, please contact our Public Relations department at 650-653-7000 or fax 650-653-7500.For authorization to photocopy items for corporate, personal, or educational use, please contact Copyright Clearance Center, 222 Rosewood Drive,Danvers, MA 01923, or fax 978-750-4470.Screen shots displayed in this book are based on pre-released software and aresubject to change.

JavaScript™: Your visual blueprint for building dynamic Web pages

LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND AUTHOR HAVE USED THEIR BEST EFFORTS IN PREPARING THIS BOOK. THE PUBLISHER AND AUTHORMAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS BOOK AND SPECIFICALLYDISCLAIM ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR APARTICULAR PURPOSE. THERE ARE NO WARRANTIES WHICH EXTEND BEYOND THEDESCRIPTIONS CONTAINED IN THIS PARAGRAPH. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES REPRESENTATIVES OR WRITTEN SALES MATERIALS. THE ACCURACY AND COMPLETENESS OF THE INFORMATION PROVIDED HEREIN AND THE OPINIONS STATED HEREIN ARE NOT GUARANTEED OR WARRANTED TO PRODUCE ANYPARTICULAR RESULTS, AND THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOTBE SUITABLE FOR EVERY INDIVIDUAL. NEITHER THE PUBLISHER, NOR AUTHOR SHALL BELIABLE FOR ANY LOSS OF PROFIT OR ANY OTHER COMMERCIAL DAMAGES, INCLUDINGBUT NOT LIMITED TO SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR OTHER DAMAGES.

U.S. Trade Sales

Contact IDG Booksat (800) 434-3422or (650) 655-3000.

U.S. Corporate Sales

Contact maranGraphicsat (800) 469-6616 orfax (905) 890-9434.

Trademark Acknowledgments

JavaScript is a trademark of Sun Microsystems, Inc. ThemaranGraphics logo is a trademark of maranGraphics, Inc.. TheIDG Books Worldwide logo is a registered trademark underexclusive license to IDG Books Worldwide, Inc., from InternationalData Group, Inc.. Visual, the Visual logo, Teach Yourself VISUALLY,Master VISUALLY, Simplified, and related trade dress are registeredtrademarks or trademarks of IDG Books Worldwide, Inc., in theUnited States and other countries, and may not be used withoutwritten permission. All other trademarks are the property of theirrespective owners. IDG Books Worldwide, Inc. andmaranGraphics, Inc. are not associated with any product orvendor mentioned in this book.

is a registered trademark under exclusive license to IDG Books Worldwide, Inc. from International Data Group, Inc.

Page 3: Javascript Tutorial - 4730-5

Eleventh AnnualComputer PressAwards 1995Tenth Annual

Computer PressAwards 1994

Ninth AnnualComputer PressAwards 1993

Eighth AnnualComputer PressAwards 1992

Welcome to the world of IDG Books Worldwide.

IDG Books Worldwide, Inc., is a subsidiary of International Data Group, the world’s largest publisher of computer-relatedinformation and the leading global provider of information services on information technology. IDG was founded more than 30years ago by Patrick J. McGovern and now employs more than 9,000 people worldwide. IDG publishes more than 290 computerpublications in over 75 countries. More than 90 million people read one or more IDG publications each month.

Launched in 1990, IDG Books Worldwide is today the #1 publisher of best-selling computer books in the United States. We areproud to have received eight awards from the Computer Press Association in recognition of editorial excellence and three fromComputer Currents’ First Annual Readers’ Choice Awards. Our best-selling ...For Dummies® series has more than 50 million copiesin print with translations in 31 languages. IDG Books Worldwide, through a joint venture with IDG’s Hi-Tech Beijing, becamethe first U.S. publisher to publish a computer book in the People’s Republic of China. In record time, IDG Books Worldwide hasbecome the first choice for millions of readers around the world who want to learn how to better manage their businesses.

Our mission is simple: Every one of our books is designed to bring extra value and skill-building instructions to the reader. Ourbooks are written by experts who understand and care about our readers. The knowledge base of our editorial staff comes fromyears of experience in publishing, education, and journalism — experience we use to produce books to carry us into the newmillennium. In short, we care about books, so we attract the best people. We devote special attention to details such as audience,interior design, use of icons, and illustrations. And because we use an efficient process of authoring, editing, and desktop publishingour books electronically, we can spend more time ensuring superior content and less time on the technicalities of making books.

You can count on our commitment to deliver high-quality books at competitive prices on topics you want to read about. At IDGBooks Worldwide, we continue in the IDG tradition of delivering quality for more than 30 years. You’ll find no better book on asubject than one from IDG Books Worldwide.

John Kilcullen Steven BerkowitzChairman and CEO President and PublisherIDG Books Worldwide, Inc. IDG Books Worldwide, Inc.

IDG is the world’s leading IT media, research and exposition company. Founded in 1964, IDG had 1997 revenues of $2.05 billion and hasmore than 9,000 employees worldwide. IDG offers the widest range of media options that reach IT buyers in 75 countries representing 95%of worldwide IT spending. IDG’s diverse product and services portfolio spans six key areas including print publishing, online publishing,expositions and conferences, market research, education and training, and global marketing services. More than 90 million people read oneor more of IDG’s 290 magazines and newspapers, including IDG’s leading global brands — Computerworld, PC World, Network World,Macworld and the Channel World family of publications. IDG Books Worldwide is one of the fastest-growing computer book publishers inthe world, with more than 700 titles in 36 languages. The “...For Dummies®” series alone has more than 50 million copies in print. IDG offersonline users the largest network of technology-specific Web sites around the world through IDG.net (http://www.idg.net), which comprisesmore than 225 targeted Web sites in 55 countries worldwide. International Data Corporation (IDC) is the world’s largest provider of informationtechnology data, analysis and consulting, with research centers in over 41 countries and more than 400 research analysts worldwide. IDGWorld Expo is a leading producer of more than 168 globally branded conferences and expositions in 35 countries including E3 (ElectronicEntertainment Expo), Macworld Expo, ComNet, Windows World Expo, ICE (Internet Commerce Expo), Agenda, DEMO, and Spotlight.IDG’s training subsidiary, ExecuTrain, is the world’s largest computer training company, with more than 230 locations worldwide and 785training courses. IDG Marketing Services helps industry-leading IT companies build international brand recognition by developing globalintegrated marketing programs via IDG’s print, online and exposition products worldwide. Further information about the company can befound at www.idg.com. 1/24/99

Page 4: Javascript Tutorial - 4730-5

maranGraphics is a family-run business located near Toronto, Canada.

At maranGraphics, we believe in producing greatcomputer books — one book at a time.

maranGraphics has been producing high-technologyproducts for over 25 years, which enables us to offer thecomputer book community a unique communicationprocess.

Our computer books use an integrated communicationprocess, which is very different from the approach usedin other computer books. Each spread is, in essence, aflow chart — the text and screen shots are totallyincorporated into the layout of the spread. Introductorytext and helpful tips complete the learning experience.

maranGraphics’ approach encourages the left and rightsides of the brain to work together — resulting in fasterorientation and greater memory retention.

Above all, we are very proud of the handcrafted natureof our books. Our carefully-chosen writers are experts

in their fields, and spend countless hours researchingand organizing the content for each topic. Our artistsrebuild every screen shot to provide the best claritypossible, making our screen shots the most precise andeasiest to read in the industry. We strive for perfection,and believe that the time spent handcrafting each elementresults in the best computer books money can buy.

Thank you for purchasing this book. We hope youenjoy it!

Sincerely,

Robert MaranPresidentmaranGraphicsRob@maran.comwww.maran.comwww.idgbooks.com/visual

Page 5: Javascript Tutorial - 4730-5

General and Administrative

IDG Books Worldwide, Inc.: John Kilcullen, CEO

IDG Books Technology Publishing Group: Richard Swadley, Senior Vice President and Publisher; Walter R. Bruce III, Vice President andPublisher; Joseph Wikert, Vice President and Publisher; Mary Bednarek, Vice President and Director, Product Development; Andy Cummings, Publishing Director, General User Group; Mary C. Corder, Editorial Director; Barry Pruett, Publishing Director

IDG Books Consumer Publishing Group: Roland Elgey, Senior Vice President and Publisher; Kathleen A. Welton, Vice President andPublisher; Kevin Thornton, Acquisitions Manager; Kristin A. Cocks, Editorial Director

IDG Books Internet Publishing Group: Brenda McLaughlin, Senior Vice President and Publisher; Sofia Marchant, Online MarketingManager

IDG Books Production for Branded Press: Debbie Stailey, Director of Production; Cindy L. Phipps, Manager of Project Coordination,Production Proofreading, and Indexing; Tony Augsburger, Manager of Prepress, Reprints, and Systems; Shelley Lea, Supervisor ofGraphics and Design; Debbie J. Gates, Production Systems Specialist; Robert Springer, Supervisor of Proofreading; Trudy Coler, Page Layout Manager; Kathie Schutte, Senior Page Layout Supervisor; Janet Seib, Page Layout Supervisor; Michael Sullivan, ProductionSupervisor

Packaging and Book Design: Patty Page, Manager, Promotions Marketing

The publisher would like to give special thanks to Patrick J. McGovern, without whom this book would not have been possible.

Acquisitions, Editorial, and Media Development

Project EditorDana Rhodes Lesh

Acquisitions EditorMartine Edwards

Associate Project CoordinatorLindsay Sandman

Copy EditorTim Borek

Proof EditorDwight Ramsey

Technical EditorAngela Murdock

Permissions EditorCarmen Krikorian

Associate Media DevelopmentSpecialist

Megan DecraeneEditorial Manager

Rev MengleMedia Development Manager

Heather Heath DismoreEditorial AssistantCandace Nicholson

ProductionBook Design

maranGraphics™

Project CoordinatorCindy Phipps

LayoutBarry Offringa, Jill Piscitelli, Kathie

Schutte, Erin ZeltnerProofreaders

Corey Bowen, Vicki BroylesIndexer

York Production Services, Inc.Special Help

Megan Decraene, Mark Harris, Jill Johnson, Beth Parlon,

Marisa E. Pearman, Maureen Spears

CREDITS

ACKNOWLEDGMENTS

Page 6: Javascript Tutorial - 4730-5

About the AuthorKelly Murdock has been involved in numerous Internet-related titles, including most recently, Master Visually HTML andXHTML, HTML Unleashed, Using FrontPage, and the FrontPage Bible. He also works full-time managing a Web development teamfor Big Planet and is the creative force behind the children’s Web site at www.animabets.com, which features a variety ofJavaScript games.

Author’s AcknowledgmentsThere are several individuals that I’d like to thank for their support on this project. First of all is my family. Thanks to Angela forhelping me in the most stressful times during the development of this work and for her continual encouragement. Thanks toEric and Thomas for being understanding while Dad was so busy.

Thanks to Chris Murdock for his work on the Animabets characters that are feature prominently throughout the book.

Thanks to Martine Edwards for directing me to this project and a big thanks to Dana Lesh for her expert editing and projectguidance. Thanks also to all other IDG employees who were responsible for copy editing, proofreading, indexing, designing thecover, and producing the CD-ROM.

Thanks also to all the contributors who added value to the book’s CD-ROM.

Page 7: Javascript Tutorial - 4730-5

DedicationNever underestimate the power of a good game.

To Eric, 2000

Page 8: Javascript Tutorial - 4730-5

viii

TABLE OF CONTENTS

1) INTRODUCING JAVASCRIPT

Understand Scripting ..................................................................................................2

Enter JavaScript Statements in the URL Field ..............................................................4

Embed JavaScript within an HTML Document ............................................................6

Link to an External JavaScript File ................................................................................8

Present Content to Non-JavaScript Browsers ............................................................10

Add Comments to JavaScript ....................................................................................12

2) USING VARIABLES AND ARRAYS

Understand Variable Types ........................................................................................14

Declare Variables ......................................................................................................16

Assign Values to Variables ..........................................................................................17

Using Integers ..........................................................................................................18

Using Floating-Point Numbers ..................................................................................19

Using Booleans ..........................................................................................................20

Using Strings ............................................................................................................21

Determine Variable Type ..........................................................................................22

Convert Strings to Numbers ......................................................................................24

Convert Numbers to Strings ......................................................................................26

Declare an Array ........................................................................................................28

Determine the Number of Elements of an Array ......................................................30

Convert an Array into a String ..................................................................................32

Sort an Array ..............................................................................................................34

Page 9: Javascript Tutorial - 4730-5

ix

3) CREATING EXPRESSIONS

Using Arithmetic Operators ......................................................................................36

Increment and Decrement Variables ........................................................................38

Create Comparison Expressions ................................................................................40

Create Logical Expressions ........................................................................................42

Use Conditional Operators ........................................................................................44

Understand Precedence ............................................................................................46

Evaluate String Expressions ......................................................................................47

Identify Numbers ......................................................................................................48

4) CONTROLLING PROGRAM FLOW

Using if-else Statements ............................................................................................50

Using for Loops ........................................................................................................52

Using while Loops ....................................................................................................54

Break Loops ..............................................................................................................56

Continue Loops ........................................................................................................57

Using JavaScript Timers ............................................................................................58

Set Regularly Timed Intervals ....................................................................................60

Clear Timeouts and Intervals ....................................................................................62

JAVASCRIPT:Your visual blueprint for

building dynamic Web pages

Page 10: Javascript Tutorial - 4730-5

x

5) WORKING WITH FUNCTIONS

Declare a Function ....................................................................................................64

Call a Function ..........................................................................................................65

Understand Global and Local Variables ....................................................................66

Pass Parameters to a Function ..................................................................................68

Return Values from a Function ..................................................................................70

Call a Function from an HTML Link ..........................................................................72

6) HANDLING EVENTS

Using JavaScript Events ............................................................................................74

Detect a Mouse Click ................................................................................................76

Detect a Double-Click ..............................................................................................78

Create Rollover Buttons ............................................................................................80

Detect a Key Press ....................................................................................................82

Set Focus ..................................................................................................................84

Detect a Pull-Down Menu Selection ........................................................................86

Create Page Loading and Unloading Messages ..........................................................88

7) USING OBJECTS

Understand Objects, Properties, and Methods ........................................................90

Using Web Page Element Objects ............................................................................92

Using Subobjects ......................................................................................................94

Using Predefined Objects ..........................................................................................96

Create New Objects ..................................................................................................98

TABLE OF CONTENTS

Page 11: Javascript Tutorial - 4730-5

xi

Refer to the Current Object ....................................................................................100

View Object Properties ............................................................................................102

Using the Array Object ............................................................................................104

Using the image Object ..........................................................................................106

Preload Images ........................................................................................................107

Change Images ........................................................................................................108

Using the link and anchor Objects ..........................................................................110

Change Links ..........................................................................................................113

Using the history Object ........................................................................................115

8) WORKING WITH WINDOWS

Using the window and document Objects ..............................................................116

Display Text on a Browser’s Status Bar ..................................................................118

Change Background Colors ....................................................................................120

Change Text and Link Colors ..................................................................................122

Change the Document Title ....................................................................................124

Display the Modification Date ................................................................................125

View the URL of the Current Document ................................................................126

View the Referring Page ..........................................................................................127

Open a New Browser Window ................................................................................128

Close a Remote Window ........................................................................................130

Print a Window ......................................................................................................132

Move a Window ......................................................................................................134

Resize a Window ....................................................................................................136

Inform the User with an Alert Dialog Box ..............................................................138

Accept Input with a Prompt Dialog Box ..................................................................140

Enable User Decisions with a Confirm Dialog Box ..................................................142

JAVASCRIPT:Your visual blueprint for

building dynamic Web pages

Page 12: Javascript Tutorial - 4730-5

xii

TABLE OF CONTENTS

9) WORKING WITH STRINGS

Using the string Object ..........................................................................................144

Work with Substrings ..............................................................................................146

Concatenate Strings ................................................................................................148

Format String Variables ............................................................................................150

Build Anchors and Links ..........................................................................................152

Determine String Length ........................................................................................154

Change Case ..........................................................................................................155

Search within a String ..............................................................................................156

Locate Characters in a String ..................................................................................158

Replace Text in a String ..........................................................................................160

Split a String ............................................................................................................162

10) WORKING WITH DATES AND TIMES

Using the date Object ............................................................................................164

Display the Local Time and Date ............................................................................166

Get Time and Date Values ......................................................................................168

Set Time and Date Values ........................................................................................170

Work with Time ......................................................................................................172

Work with Time Zones ............................................................................................174

Page 13: Javascript Tutorial - 4730-5

xiii

11) USING THE MATH OBJECT

Using the Math Object ............................................................................................176

Generate Random Numbers ....................................................................................178

Using Mathematical Constants ................................................................................180

Using Trigonometric Functions ................................................................................182

Using Logarithmic and Exponential Methods ..........................................................184

Using the Square Root Method ..............................................................................185

Round Numbers ......................................................................................................186

Raise Numbers to a Power ......................................................................................187

Find Minimum and Maximum Values ......................................................................188

Using Absolute Values ............................................................................................189

12) WORKING WITH FORMS

Using Text Boxes ....................................................................................................190

Work with Password Boxes ....................................................................................192

Work with Hidden Fields ........................................................................................193

Work with Textarea Boxes ......................................................................................194

Using Buttons ..........................................................................................................196

Using a Reset Button ..............................................................................................198

Using a Submit Button ............................................................................................199

JAVASCRIPT:Your visual blueprint for

building dynamic Web pages

Page 14: Javascript Tutorial - 4730-5

xiv

TABLE OF CONTENTS

Using Check Box Buttons ........................................................................................200

Using Radio Buttons ................................................................................................202

Work with Selection Lists ........................................................................................204

Work with Separate Selection List Items ................................................................206

Work with a Multiple-Selection List ........................................................................208

Disable Form Elements ............................................................................................210

Reset and Submit a Form ........................................................................................212

Validate Forms ........................................................................................................214

Control Form Focus ................................................................................................216

Using Focus Events ................................................................................................218

13) WORKING WITH FRAMES

Work with the frame Object ....................................................................................220

Access Frames by Name ..........................................................................................222

Find the Number of Frames ....................................................................................224

Reference the Current Frame ..................................................................................225

Reference across Frames ........................................................................................226

Write to a Separate Frame ......................................................................................228

Detect Frame Resizing ............................................................................................229

Set the Target Frame ................................................................................................230

Print a Frame ..........................................................................................................231

Page 15: Javascript Tutorial - 4730-5

xv

14) DETERMINING ENVIRONMENT PROPERTIES

Using the navigator Object ......................................................................................232

Detect a User’s Browser ........................................................................................234

Detect the Browser’s Version ..................................................................................235

Detect a User’s Operating System ..........................................................................236

Understand a User Agent ........................................................................................237

Determine Whether Java Is Enabled ........................................................................238

Determine the Code Name ....................................................................................239

Using the location Object ........................................................................................240

Using Cookies ........................................................................................................242

Encode Characters ..................................................................................................244

15) DEBUGGING JAVASCRIPT

Detect JavaScript Errors ..........................................................................................246

Debug with Comments ..........................................................................................248

Output Values to Text Boxes ..................................................................................250

Common JavaScript Errors ......................................................................................251

JAVASCRIPT:Your visual blueprint for

building dynamic Web pages

Page 16: Javascript Tutorial - 4730-5

xvi

TABLE OF CONTENTS

HTML 4.01 REFERENCE ...................................................................................254

WHAT'S ON THE CD-ROM ..............................................................................264

USING THE E-VERSION OF THE BOOK.........................................................286

Page 17: Javascript Tutorial - 4730-5

xvii

JAVASCRIPT:Your visual blueprint for

building dynamic Web pages

Page 18: Javascript Tutorial - 4730-5

22

UNDERSTAND SCRIPTING

Web page files, written in the HypertextMarkup Language (HTML), define howelements such as text, tables, and

images will appear when viewed in a browser.HTML deals only with static elements.

JavaScript is a scripting language that can co-exist with HTML in a Web page file. It can beused to add interactivity to a Web page.

This interactivity enables the Web page creatorto dynamically control the Web page elements.You can also use JavaScript to change Webpage elements as the user interacts with theWeb page. For example, you can set the textdisplayed in a form’s text box to update whenthe user clicks a button.

JavaScript can run in a browser without anyadditional tools.

UNDERSTAND SCRIPTING

⁄ Open a Web page that includes JavaScript, such as www.animabets.com/activities/qballs/balls.html, in a browser.

¤ Click one of the buttons. ■ The text box displays the answer result, and a new image is displayed.

Note: The HTML file for this Web page includes JavaScript syntax that defines how the text boxes and images are updated.

‹ Click another button.

UNDERSTAND SCRIPTING

JAVASCRIPT

Page 19: Javascript Tutorial - 4730-5

3

■ Again the text box displays the result, and a new image is displayed.

Note: The text box is logically updated depending on the answer.

› Choose View➪ Source to view the page’s source code.

ˇ Scroll down until you find the <script> tag.

■ Notice that the language attribute is set to javascript.

JavaScript is the most popular client-basedWeb scripting language because it issupported on both Netscape Navigator andInternet Explorer, but you can use otherscripting languages to add interactivity to aWeb page. Setting the language attributefor the <script> tag to VBScriptspecifies that VBScript is used as thescripting language. VBScript is similar insyntax to Visual Basic, but it is onlysupported on the Internet Explorer browser.

VBScript is very similar to the Visual Basicprogramming language, so the advantage ofusing it if you are familiar with Visual Basic isthat VBScript may be easier for you to learnthan JavaScript. The disadvantage is thatVBScript works only in the Microsoft InternetExplorer browser.

INTRODUCING JAVASCRIPT 1

Page 20: Javascript Tutorial - 4730-5

ENTER JAVASCRIPT STATEMENTS INTHE URL FIELD

JavaScript is composed of statements that whenexecuted perform a desired function. Forexample, the JavaScript statement

document.write(“hello”) displays theword hello in the browser.

Browsers can interpret and execute JavaScriptstatements. These statements can be found withina Web page file or entered directly into thebrowser’s URL box.

To have the browser execute a JavaScriptstatement, type the javascript: keyword in the

Address box of the browser, type the JavaScriptstatement, and then press the Enter key toexecute the statement.

A semicolon (;) should be placed at the end ofthe JavaScript statement. Several differentstatements can be included together in theAddress box by separating them with semicolons.

For example, if you enter javascript:document.write(“hello”); the browserdisplays the text “hello” when you press theEnter key.

ENTER JAVASCRIPT STATEMENTS INTHE URL FIELD

⁄ Open a browser. ¤ In the Address box, type the javascript: keyword.

4

ENTER JAVASCRIPT STATEMENTS IN THE URL FIELD

JAVASCRIPT

Page 21: Javascript Tutorial - 4730-5

‹ After the javascript: keyword, type document.write (“<h1>Hesitation Kills</h1>“);.

› Also enter the statement document.bgColor=“blue”;

ˇ Press the Enter key.

■ The JavaScript statements are executed in the browser.

If a keyword is entered in the Address box,the browser normally searches for Web pagesbased on the keyword. If you want thebrowser to search for JavaScript Web pagesinstead of executing a JavaScript statement,just omit the colon after javascript: If youtype the javascript: keyword in thebrowser’s Address box without including acolon (:), the browser searches for Webpages that match the javascript keyword.The colon symbol tells the browser that thefollowing text should be interpreted asJavaScript statements.

If you forget to include the javascript:keyword, the browser will think that theJavaScript statement you type is a Web pageaddress. It will try to locate a Web page withthat address, which it won’t be able to find.

5

INTRODUCING JAVASCRIPT 1

Page 22: Javascript Tutorial - 4730-5

EMBED JAVASCRIPT WITHIN AN HTML DOCUMENT

JavaScript can be included in a Web page within<script> tags. The JavaScript statements includedwithin the <script> tags are executed when the

Web page loads in a browser.

The <script> tags can appear anywhere within the<head> or <body> tags. A single Web page caninclude several sets of <script> tags.

The <script> tag accepts the type and languageattributes. The type attribute can be set to arecognized MIME type, such as text/javascript.The language attribute is another way to specify the

scripting language to use. For JavaScript, it can besimply set to javascript.

If a JavaScript statement displays any text to the browser,the location of the text will be at the <script> tag’slocation in the Web page file. For example, if an HTMLfile has a heading followed by a <script> tag thatoutputs some text, then the JavaScript text will comeimmediately after the HTML heading.

This example uses the skeleton.html file found onthe book’s CD-ROM, but you can apply these steps toany file.

EMBED JAVASCRIPT WITHIN AN HTML DOCUMENT

⁄ Open the skeleton.html file.

¤ Add a set of <script> tags within the <body> tags.

‹ Add the language attribute to the <script> tag.

› Set the language attribute equal to javascript.

ˇ Save the file as js-skeleton.html.

Note: This skeleton page can be used to easily create a Web page that includes JavaScript.

Á Within the <script> tags, add a JavaScript statement to change the background color.

‡ Add a semicolon (;) to the end of the JavaScript statement.

° Save the file as changebg.html.

Note: JavaScript statements placed within the <script> tags are executed when the file is loaded.

6

EMBED JAVASCRIPT WITHIN AN HTML DOCUMENT

JAVASCRIPT

Page 23: Javascript Tutorial - 4730-5

· Add another JavaScript statement to output a phrase.

■ The output statement can include HTML tags.

‚ Add a semicolon (;) to the end of the JavaScript statement.

— Save the file as output.html.

± Open the output.html file in a browser.

■ Notice how the background color has changed and text is displayed.

7

INTRODUCING JAVASCRIPT 1

Using JavaScript, you can personalize a Webpage for your visitors. The following snippetof code opens a dialog box in which userscan enter their names. This name is thendisplayed on the Web page using anotherJavaScript statement:

temp = window.prompt(“What is yourname?”);

document.write(“Welcome, “ + temp+ “ to this Web page. I hope youenjoy your visit.”);

To make this script work, you simply need toinclude it within a set of <script> tags andopen the file within a browser.

Page 24: Javascript Tutorial - 4730-5

LINK TO AN EXTERNAL JAVASCRIPT FILE

Another attribute that can be used withthe <script> tag is the src attribute.This attribute can be set to the URL of an

external file that contains the JavaScript script.

The external file does not need to include the<script> tags, only the JavaScriptstatements. It also doesn’t need to include thehtml extension. External JavaScript filestypically will have a js extension.

The external JavaScript file can be anywhere onthe Web and referenced using the http://

protocol keyword followed by the Web addressfor the external file.

For example, the statement, <scriptsrc=”myfile.js”> would access theexternal JavaScript file named myfile.jslocated in the same directory as the HTML file.

This example uses the output.html filefound on the book’s CD-ROM (or which youmay have created in the section “EmbedJavaScript within an HTML Document”), butyou can apply these steps to any file.

LINK TO AN EXTERNAL JAVASCRIPT FILE

⁄ Open the output.html file in Notepad.

¤ Cut the contents of <script> tags out of the file.

‹ Save the file as external.html.

CREATING A FILE TO LINK TO

⁄ Open a new file in Notepad.

¤ Paste the <script> tag contents you cut from the output.html file into this new file.

‹ Save the file as external.js.

8

LINK TO AN EXTERNAL JAVASCRIPT FILE

JAVASCRIPT

Page 25: Javascript Tutorial - 4730-5

LINKING TO AN EXTERNAL FILE

⁄ Open the external.html file in Notepad.

¤ Add the src attribute to the <script> tag.

‹ Set the src attribute to external.js.

› Save the file as external.html, saving over the original external.html file.

ˇ Open the external.html file in a browser.

■ The JavaScript statements still work as an external file.

JavaScript is case-sensitive. If you type aJavaScript variable with a capital letter, youneed to include that same capital letter whenyou call the variable. So the variables hello,Hello, and HELLO are all different. If yourJavaScript statement isn’t being recognizedcorrectly, check for a misspelled keyword.

You can execute JavaScript statementsmultiple times by placing them withinstructures called functions. Functions arecovered in Chapter 5.

Any JavaScript statements included within the<head> tags are executed before the remainingHTML tags. For example, if there are <script>tags within the <head> tags that contain aJavaScript statement that outputs some text, thattext appears above the rest of the Web page.

9

INTRODUCING JAVASCRIPT 1

Page 26: Javascript Tutorial - 4730-5

PRESENT CONTENT TO NON-JAVASCRIPT BROWSERS

Users have the option as part of thebrowser configuration to disable JavaScriptsupport. If a user has disabled JavaScript

support, her browser will not display anyJavaScript that you include in your Web page.

You can handle a browser that has JavaScriptsupport disabled using the <noscript> tags.If the JavaScript cannot be processed, thecontent included within the <noscript> tagsis displayed.

This content can explain to the users withJavaScript disabled on their browser what theywould see if JavaScript were enabled.

For example, if a Web page includes thesentence “This page uses JavaScript” within<noscript> tags, this sentence will appear ifJavaScript is disabled.

This example uses the output.html filefound on the book’s CD-ROM, but you canapply these steps to any file.

PRESENT CONTENT TO NON-JAVASCRIPT BROWSERS

ADDING <noscript> TAGS TO A WEB PAGE

⁄ Open the output.html file.

¤ After the <script> tags, add a set of <noscript> tags.

‹ Between the <noscript> tags, add some explanation text.

› Save the file as noscript.html.

DISABLING JAVASCRIPT IN NETSCAPE NAVIGATOR

⁄ Open Netscape Navigator.

Note: In the Internet Explorer browser, you can’t disable JavaScript specifically.

¤ Choose Edit➪ Preferences to open the Preferences dialog box.

‹ Select the Advanced category from the list at the left.

10

PRESENT CONTENT TO NON-JAVASCRIPT BROWSERS

JAVASCRIPT

Page 27: Javascript Tutorial - 4730-5

› Deselect the Enable JavaScript option ( changes to ).

ˇ Click the OK button. VIEWING YOUR WEB PAGE IN A

JAVASCRIPT-DISABLED

BROWSER

⁄ Open the noscript.html file in Netscape Navigator.

■ The text contained within the <noscript> tag is displayed.

You cannot control a user’s browserconfiguration, so there is no way to altersomeone’s configuration to enable JavaScriptsupport. The best you can do is to tell theuser how to enable it and encourage him orher to do so. You can, however, detectwhether the Java programming language isenabled.

Many different Web page enhancements can beenabled or disabled using the browserpreference settings. Using Netscape Navigator’sPreferences dialog box, you can disable Java,JavaScript, style sheets, and cookies. UsingInternet Explorer’s Options dialog box, youcan disable Java, ActiveX controls, scripting,and cookies.

11

INTRODUCING JAVASCRIPT 1

Page 28: Javascript Tutorial - 4730-5

ADD COMMENTS TO JAVASCRIPT

The JavaScript syntax can be difficult tofollow if you are new to the language. Oneway to document what a section of code

does is to include blocks of comments. Thesecomments will be ignored by the browser andwill only be visible in the actual file.

A single-line comment can be designated withtwo forward slashes (//). Multiple-linecomments start with a forward slash and anasterisk (/*) and end with the opposite (*/).You cannot nest multiple sets of comments. Allstatements included within the commentsymbols will be ignored.

Comments can appear anywhere within a setof <script> tags.

Besides documenting your code, you can alsouse comments for debugging JavaScript.Multiple-line comments can be used to quicklydisable sections of your code withoutremoving them. This ability is handy when youare trying to debug sections that aren’tworking properly.

This example uses the noscript.html filefound on the book’s CD-ROM (or which youmay have created in the section “PresentContent to Non-JavaScript Browsers”), but youcan apply these steps to any file.

ADD COMMENTS TO JAVASCRIPT

⁄ Open the noscript.html file in Notepad.

¤ Add a single-line comment in front of the first JavaScript statement.

‹ Add a multiple-line comment in front of the second JavaScript statement.

› Save the file as comments.html.

ˇ Open the comments.html file in a browser.

■ Notice how the comments added to the file don’t appear in the browser.

12

ADD COMMENTS TO JAVASCRIPT

JAVASCRIPT

Page 29: Javascript Tutorial - 4730-5

Á Open the comments.html file in Notepad.

‡ Move the closing comment block after the second JavaScript statement.

° Save the file as comments2.html.

· Open the comments2.html file in a browser.

■ Notice that the first JavaScript statement was executed, but not the second, because the second statement is now a comment.

13

INTRODUCING JAVASCRIPT 1

Many scripts can benefit from an explanatoryheader. This header can include informationabout the script, including the author, thedate, and a description of what the scriptdoes. Such a header could be marked as acomment block like so:

/* Personalize Script

developed by KLM on May 16, 2000

description: The purpose of thisscript is to accept the user’s nameusing a prompt box, save the name ina variable, and display the name tothe browser as part of a welcomemessage. */

Page 30: Javascript Tutorial - 4730-5

UNDERSTAND VARIABLE TYPES

One of the first concepts that you needto understand in JavaScript is how towork with variables. Variables are like a

temporary holding container for values. Asvalues change, the variable can be updated tohold the new value.

Variables can also hold constant values.Constant values are values that don’t change.For example, you could create a variablenamed hoursPerDay and set it to 24; withinyour code, you can refer to the number ofhours per day using the variablehoursPerDay. Although simply typing thevalue 24 in the code would be easier, if youuse a variable, the equation will have meaningwhen you examine it. Using variables to holdconstants thus makes debugging and workingwith your code easier.

Variable names must meet severalrequirements. For example, 24 is not a goodvariable name because it is easily confusedwith a value. Variable names can includeupper- and lowercase letters, numbers, andthe underscore character (_). No otherpunctuation marks may be used. Variablenames must not begin with a number andcannot include any spaces.

Variable names in JavaScript are case-sensitive.So, the variable names Hello, hello, andHeLLo are all different. It’s a good idea to usevariable names that describe the data theyhold. If you consistently name variables,understanding your code when you look at itlater will be easier. For example, you couldconsistently capitalize all constant values as away of identifying that they will not change.

UNDERSTAND VARIABLE TYPES

14

Several different types of variables exist,depending on the type of data that they hold.The various variable types can hold anassortment of numbers and words as values.Specifically, these types include the following:

• Integer numbers

• Floating-point numbers

• String

• Boolean

A good coding technique is to start the variablenames with a letter that indicates the type ofvariable. This technique helps as you work withthe code. For example, an integer variablewould be named iVar, a floating-point variablewould be fVar, a string variable would besVar, and a Boolean variable would be bVar.This technique for naming variables isn’trequired, only suggested.

JAVASCRIPT

Page 31: Javascript Tutorial - 4730-5

15

FLOATING-POINT VARIABLES

Floating-point variables can hold fractionalnumbers that include a decimal point. Thesevariables can also be used with the standardarithmetic operators.

Examples of floating-point values include 2.5,-34.56, and 3.121.

USING VARIABLES AND ARRAYS

INTEGER VARIABLES

Integer variables can hold the basic countingnumbers, either positive or negative. Thesevalues can be operated on using arithmeticoperators such as addition, subtraction,multiplication, and division.

Examples of integer values include 2, 345,and -34.

TYPES OF VARIABLES

STRING VARIABLES

String variables are simply words andsentences. These variables can hold singlecharacters or entire paragraphs. String valuesare usually designated with a set ofquotation marks.

Examples of string values include “hello”,“abc”, and “This is a test”.

BOOLEAN VARIABLES

Boolean variables are a unique variable typethat can hold only the words true or false.These variables can be used to test thecondition of a statement. The number 0 isalso used to represent the value false, and1 represents the value true.

2

Page 32: Javascript Tutorial - 4730-5

JavaScript is a loosely typed language. Thismeans that you don’t need to explicitlydeclare each variable type, and different

variable types can be combined without anerror.

Being a loosely typed language also means thatyou don’t need to specify the variable typewhen creating a new variable. All you need todo is type a variable name, and its type isautomatically set based on the type of value itholds.

You can also specifically state variable namesusing the var keyword. This keyword, whenplaced in front of a variable name, identifies itas a variable. You can declare several variablesat once by separating them with commas.

For example, var int1, int2, str1,str2 declares four variables.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a heading for the page within the <body> tags.

‹ Add the var keyword within the <script> tags followed by a variable name.

› Add a semicolon (;) to the end of the line.

ˇ Save the file as var.html.

Á Add several additional variable names separated with commas.

‡ Save the file as var2.html.

16

DECLARE VARIABLES

JAVASCRIPT

DECLARE VARIABLESDECLARE VARIABLES

Page 33: Javascript Tutorial - 4730-5

ASSIGNING A VALUE TO A VARIABLE

⁄ Open the file var.html in Notepad.

¤ Below the variable declaration, type the variable name and set it equal to a value.

‹ Save the file as assign.html.

ASSIGNING VALUES TO MULTIPLE VARIABLES

⁄ Open the file var2.html in Notepad.

¤ Below the variable declaration, set the value for each variable name.

‹ Save the file as assign2.html.

17

After a variable is declared, you can assignvalues to it using the equals sign (=). Thevalue should always be placed on the

right side of the equals sign with the variablename on the left.

For example, the statement temp1 = 56;places the value 56 within the variable namedtemp1. You can then refer to this value at anytime using the temp1 variable name.

Strings can be assigned to a variable name ifthey are included in quotation marks (“ ”).Any string without quotation marks isconsidered a variable name.

For example, the statement str1 = “HelloEverybody”; places the string “HelloEverybody” in the variable str1.

This example uses the var.html andvar2.html files found on the book’sCD-ROM (or which you may have created inthe section “Declare Variables”), but you canapply these steps to any file.

ASSIGN VALUES TO VARIABLESASSIGN VALUES TO VARIABLES

USING VARIABLES AND ARRAYS 2

ASSIGN VALUES TO VARIABLES

Page 34: Javascript Tutorial - 4730-5

USING INTEGERS

Integers are values without a decimal point.These are typically referred to as the“counting numbers” and may be either

positive or negative. Negative integer valueshave a minus sign (–) in front of them.

Integer values may be either decimal,hexadecimal, or octal. The difference betweenthese types is the base of the number system.Decimal integers are base 10. Hexadecimalintegers are base 16 with the numbers above 9

being represented with the letters a–f.Hexadecimal integers have a 0x in front ofthem. Octal integers are base 8 and include aleading 0.

For example, 24 is a decimal number, 024 is anoctal number, and 0x24 is a hexadecimalnumber.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING INTEGERS

JAVASCRIPT

⁄ Open the js-skeleton.html file in Notepad.

¤ Within the <script> tags, declare three variables with the var keyword.

‹ Set each variable name to a value.

› Use document.write statements to display the values of each variable.

ˇ Save the file as integer.html.

Á Open the integer.html file in a browser.

■ The variable values are displayed. Notice how each value is displayed as its decimal equivalent.

18

USING INTEGERS

Page 35: Javascript Tutorial - 4730-5

USING VARIABLES AND ARRAYS

⁄ Open the js-skeleton.html file in Notepad.

¤ Within the <script> tags, declare four variables with the var keyword.

‹ Set each variable name to floating-point values, two large and two small.

› Use document.write statements to display the values of each variable.

ˇ Save the file as floating-point.html.

Á Open the floating-point.html file in a browser.

■ The variable values are displayed. Notice how some of them are displayed in scientific notation.

19

Floating-point values are fractional numbers thatinclude a decimal point. These numbers can beeither positive or negative.

Very large or very small numbers can be expressedin scientific notation. Scientific notation places theletter E within the number followed by the numberof places the decimal point is moved. Positivevalues move the decimal to the right, and negativevalues move the decimal to the left.

For example, 5.14E6 represents the number5,140,000, and 6.023E-4 represents the number0.0006023.

This example uses the js-skeleton.html filefound on the book’s CD-ROM, but you can applythese steps to any file.

USING FLOATING-POINT NUMBERSUSING FLOATING-POINT NUMBERS

USING FLOATING-POINT NUMBERS

It depends on the size of a floating-pointnumber whether it is displayed in scientificnotation. Floating-point numbers that aresmaller than 1.0E-7 are displayed inscientific notation, but large numbers canbe as large as 1.0E20 before beingdisplayed in scientific notation.

2

Page 36: Javascript Tutorial - 4730-5

USING BOOLEANS

Boolean values can be either true orfalse. In addition to the actual words,the values can be set to 0 or 1 with 0

representing false and 1 representing true.

Because Boolean values can only be true orfalse, they make good conditionalstatements. A conditional statement can beused to determine the flow of the program.

In Chapter 4, program-flow statements likeif-else are introduced. Boolean variableswork very well for these statements. Forexample, for a Boolean variable namedfinished, the statement if (finished

== “true”) can be used to control whetherone set of statements gets executed or another.You can also just use the Boolean variablename such as if (finished).

This example uses the var2.html file foundon the book’s CD-ROM (or which you mayhave created in the section “DeclareVariables”), but you can apply these steps toany file.

USING BOOLEANS

⁄ Open the var2.html file in Notepad.

¤ Within the <script> tags, assign Boolean values to each variable.

‹ Use document.write statements to display the values of each variable.

› Save the file as boolean.html.

ˇ Open the boolean.html file in a browser.

■ The variable values are displayed.

20

USING BOOLEANS

JAVASCRIPT

Page 37: Javascript Tutorial - 4730-5

⁄ Open the js-skeleton.html file in Notepad.

¤ Within the <script> tags, declare two variables with the var keyword.

‹ Set each variable name to a string value.

› Use document.write statements to display the values of each variable.

ˇ Save the file as string.html.

Á Open the string.html file in a browser.

■ The string values are displayed.

21

String values are composed of words andcharacters specified within a set ofquotation marks.

Strings can be contained within singlequotation marks (‘) or within double-quotationmarks (“), but the beginning and ending marksmust be the same.

If you want to include quotation marks within thestring value, you should include the backslashsymbol (\) in front of the quotation mark. Thiscauses the quotation mark to be displayed. Youcan also use the backslash symbol to displaybackslash characters in the string.

For example, if a string is assigned to a variablelike this, str1 = “\”Hello, my name isWaldo.\””, the quotation marks surroundthe string value.

When string values are displayed using thedocument.write() method, the text isdisplayed in the browser and is subject to theHTML display engine. This means that you caninclude HTML tags within your string valuesand they will be interpreted and used todisplay the text in the browser.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING STRINGSUSING STRINGS

USING VARIABLES AND ARRAYS 2

USING STRINGS

Page 38: Javascript Tutorial - 4730-5

DETERMINE VARIABLE TYPE

Variables are often combined with oneanother. For example, if you include anequation within your code, two variables

are combined to produce a result. If you try tocombine two variables that are different types,you may run into trouble. In cases like this,you may want to determine the variables’ type.

JavaScript includes a keyword that you can useto check a variable’s type — typeof. Whenthe typeof keyword is placed in front of avariable name, the variable type is returned asa string.

When the typeof keyword is placed in frontof a variable, it returns number for integer and

floating-point variables, string for stringvariables, boolean for Boolean variables, andundefined if the variable type cannot bedetermined.

For example, if the variable int1 is assignedto 24, the statement typeof int1; wouldreturn number.

This example uses the assign2.html andvar2.html files found on the book’sCD-ROM (or which you may have created inthe sections “Assign Values to Variables” and“Declare Variables”), but you can apply thesesteps to any file.

DETERMINE VARIABLE TYPE

JAVASCRIPT

⁄ Open the assign2.html file in Notepad.

¤ Use document.write statements to display the values of each variable.

‹ Add the typeof keyword to each document.write statement followed by the variable name.

› Save the file as typeof.html.

ˇ Open the typeof.html file in a browser.

■ The variable type for each variable is displayed.

22

DETERMINE VARIABLE TYPE

Page 39: Javascript Tutorial - 4730-5

⁄ Open the var2.html file in Notepad.

¤ Use document.write statements to display the type of each unassigned variable.

‹ Save the file as typeof2.html.

› Open the file typeof2.html in a browser.

■ The variable type for each unassigned variable is displayed as undefined.

23

USING VARIABLES AND ARRAYS 2

DETERMINE UNASSIGNED VARIABLE T

The typeof keyword can also be used toidentify other types of elements: objects,forms, and functions. Each form, function,and object has a name. Using the typeofkeyword with these names returns theelement’s type.

If the undefined value is returned as a resultof the typeof keyword, the variable doesn’texist or hasn’t been defined yet. If you misspellthe variable name, it isn’t recognized and theundefined value is returned. Another case inwhich the undefined value is returned is ifyou use typeof before the variable getsassigned a value: If the typeof keywordappears in the script before the variable orfunction is encountered, the typeof keywordreturns undefined.

Page 40: Javascript Tutorial - 4730-5

CONVERT STRINGS TO NUMBERS

Before you can perform arithmeticoperations between numbers, you haveto make sure that you are dealing with

number variable types and not strings. If anumber is included within quotes when it isassigned to a variable, it is a string and not anumber, which will cause problems if you tryto add this number to another number.

JavaScript includes a couple of functions thatcan be used to strip the numbers off the frontof a string and convert them to a numbervariable type.

Strings that begin with numbers can beconverted into a number variable type usingparseInt() for integers andparseFloat() for floating-point numbers.The variable name that holds the string shouldbe placed within the parentheses.

For example, to convert the string “256” inthe variable named temp to a number, you usethe parseInt(temp); statement.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

CONVERT STRINGS TO NUMBERS

JAVASCRIPT

⁄ Open the js-skeleton.html file in Notepad.

¤ Add two new variables and assign the first one to be a string that starts with a number.

‹ Use the parseInt() function to convert the string to a number.

› Use document.write statements to display the values and type of each variable.

ˇ Save the file as parseint.html.

Á Open the file parseint.html in a browser.

■ The variable type for each variable is displayed.

24

CONVERT STRINGS WITH INTEGERS TO NUMBERS

Page 41: Javascript Tutorial - 4730-5

■ Open the js-skeleton.html file in Notepad.

¤ Add two new variables and assign the first one to be a string that starts with a floating-point number.

‹ Use the parseFloat() function to convert the string to a number.

› Use document.write statements to display the values and type of each variable.

ˇ Save the file as parsefloat.html.

Á Open parsefloat.html in a browser.

■ The variable type for each variable is displayed.

If the variable starts with a character that isn’ta number, the parseInt() function returnsNaN, which stands for “not a number.”

JavaScript includes a simple method that candetermine if a variable is a number. TheisNaN() function returns true if thevariable is “not a number” or false if it is.

A string value can be assigned to a variable andlater an integer value assigned to the samevariable without causing an error: BecauseJavaScript is loosely scripted, you can assigndifferent values to a variable at any time withoutan error.

25

USING VARIABLES AND ARRAYS

CONVERT STRINGS WITH FLOATING POINT VALUES TO NUMBERS

2

Page 42: Javascript Tutorial - 4730-5

CONVERT NUMBERS TO STRINGS

In Chapter 9, many string-specific methodsare covered, such as formatting strings andworking with substrings. If these methods

are used with a variable that contains anumber instead of a string, they will result inan error. If you convert a variable containingnumbers to a string, however, these methodswill work.

Numbers can be easily converted to strings byadding quotation marks or a space in front ofthe number. For example, if a variable namedtemp1 holds the value 36, the statement “”+ temp1; would automatically convert tempto a string.

Another way to convert numbers to strings iswith the toString() method. To use thismethod, you simply need to attach the methodname to the end of the variable name with aperiod in between. For example, to convert avariable named temp2 holding the value 36 toa string, you can use the statementtemp2.toString();.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

CONVERT NUMBERS TO STRINGS

⁄ Open the js-skeleton.html file in Notepad.

¤ Add two new variables and assign the first one to be a number.

‹ Convert the second variable to a string by adding it to ““.

› Use document.write statements to display the values and type of each variable.

ˇ Save the file as tostring.html.

Á Open tostring.html in a browser.

■ The variable type for each variable is displayed.

26

ADD A SPACE BEFORE THE NUMBER

JAVASCRIPT

Page 43: Javascript Tutorial - 4730-5

USING VARIABLES AND ARRAYS

⁄ Open the js-skeleton.html file in Notepad.

¤ Add two new variables and assign the first one to be a number.

‹ Change the second variable to a string by using the toString() method.

› Use document.write statements to display the values and type of each variable.

ˇ Save the file as tostring2.html.

Á Open tostring2.html in a browser.

■ The variable type for each variable is displayed.

27

Converting a number to a string by addingquote marks in front of it is a quick trick, but themore correct way to convert a number to astring is to use the toString() method. Usingthis method makes it easy to spot exactly whatyou are doing, and it is good code practice.

If the toString() method is used with avariable that already holds a string value,nothing happens and the resulting variable isa string.

Variables can be changed at any timebetween strings and numbers, so you canconvert variables from a number to a stringand back several times. But remember thatsome string information may be truncatedusing the parseInt() and parseFloat()functions.

2

USING THE TOSTRING() METHOD

Page 44: Javascript Tutorial - 4730-5

DECLARE AN ARRAY

Several variables can be grouped togetheras a numbered index called an array. Allvariables within the array are referenced

with the same name, but have a different indexvalue. The index number is placed after thearray name in square brackets ([]).

Arrays can be created by assigning a variablename to new Array() where the number ofelements in the array are included within theparentheses.

After an array is created, you can referenceindividual elements of the array using the array

name followed by the index number in squarebrackets. Array index values always start with 0.

For example, array1 = new Array(10)would create an array that can hold ten values.The first element would be array1[0] andthe final element of the array would bearray1[9].

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

DECLARE AN ARRAY

⁄ Open the js-skeleton.html file in Notepad.

¤ Add a new variable name and assign it to new Array() with the number of elements in the array within the parentheses.

‹ Assign each array element to a string.

› Use a document.write statement to display the value of each array element.

ˇ Save the file as array.html.

Á Open array.html in a browser.

■ A string made from all the individual array elements is displayed.

28

CREATE AN ARRAY OF STRING VARIABLES

JAVASCRIPT

Page 45: Javascript Tutorial - 4730-5

USING VARIABLES AND ARRAYS

⁄ Open the js-skeleton.html file in Notepad.

¤ Add a new variable name and assign it to new Array() with the number of elements in the array within the parentheses.

‹ Assign each array element to an integer.

› Use a document.write statement to display the value of each array element.

ˇ Save the file as array2.html.

Á Open array2.html in a browser.

■ The value contained within each array element is displayed.

29

2

CREATE AN ARRAY OF INTEGER VARIABLES

JavaScript supports two-dimensional arrays. Youcan create a two-dimensional array by creatingan array of an array. The way this works is tocreate a single one-dimensional array and thento create an array of the existing array. It can beconfusing when you try to refer to an array of anarray, but for the right application, it is worththe effort.

All the elements of a JavaScript array don’thave to contain the same variable type. Theelements of an array can hold severaldifferent types of variables. For example, thefirst element in an array could be an integer,the second element could be a string, and thethird element could be a floating-pointnumber. Each array element is independent ofthe other elements. However, if you try tomultiply array elements of different types, anerror occurs.

Page 46: Javascript Tutorial - 4730-5

DETERMINE THE NUMBER OFELEMENTS OF AN ARRAY

If an array is created and filled with elementsas the script is executed, you may lose trackof the number of elements contained within

the array. Knowing the number of elementscontained within the array tells you how oftenyou need to loop through the array in order toprocess all the data in the array.

An array is an object. Objects include propertiesthat describe them and methods, which canexecute a built-in function specific to the object.Chapter 7 covers objects in more detail.

The array object includes a property namedlength that can be used to return the numberof elements in an array. The length propertyis a statement just like a variable. It is createdby placing the length property name with aperiod after the array name. For example, if anarray named array1 is declared, the length ofthe property can be returned using thearray1.length statement.

This example uses the array.html and js-skeleton.html files found on the book’sCD-ROM, but you can apply these steps to any file.

DETERMINE THE NUMBER OFELEMENTS OF AN ARRAY

⁄ Open the array.html file in Notepad.

¤ Add + “<br/> document.write statement to add a line break.

‹ Add a new document.write statement to display the length of the array.

› Save the file as length.html.

ˇ Open length.html in a browser.

■ The browser displays the number of elements in the array.“

30

DETERMINE THE LENGTH OF A PREDEFINED ARRAY

JAVASCRIPT

Page 47: Javascript Tutorial - 4730-5

⁄ Open the js-skeleton.html file in Notepad.

¤ Add a new variable name and assign it to new Array() without specifying the number of elements in the array.

‹ Assign several array elements a value.

› Use document.write statements to display the array values and the number of array elements.

ˇ Save the file as length2.html.

Á Open length2.html in a browser.

■ The number of array elements is displayed.

What happens if the array elements are filledintermittently depends on whether the arraysize is specified. If the array size is specified,the length property always returns thespecified size. This is the number of places ofmemory that has been set aside for the array.If the size isn’t specified, the lengthproperty is determined by the array elementwith the greatest index value. For example, ifonly the second and fourth elements of anarray are filled, the length property willidentify four elements in the array even if thefirst and third elements contain no data.

The length property is a read-only property,which means that it can return informationabout the object, but it cannot be used to setthe object’s property. The length property,therefore, cannot be used to set an array’s size.

31

USING VARIABLES AND ARRAYS 2

DETERMINE THE NUMBER OF ELEMENTS IN AN ARRAY

Page 48: Javascript Tutorial - 4730-5

CONVERT AN ARRAY INTO A STRING

Arrays can be large and can contain manydifferent elements. To display all theelements of an array, you may find it

easiest to convert the array to a string.

The array object includes a method thatconverts the array elements to a string. Thismethod is join(). The join() methodaccepts a single string as a parameter. Thisstring is inserted between each separate arrayelement as it is converted to a string. Thedefault separator is a comma (,), but you canuse a different separator if you specify one. For

example, if you have an array of numberscalled array1, the statement str1 =array1.join(“ “) places a space betweeneach array element (instead of a comma). Thevariable str1 will then contain a string ofnumbers with a space placed between eachelement.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

CONVERT AN ARRAY INTO A STRING

JAVASCRIPT

⁄ Open js-skeleton.html in Notepad.

¤ Add a new variable name and assign it to new Array().

‹ Assign several array elements a value.

› Convert the array to a string with the join() method and assign the value to a string variable.

ˇ Use a document.write statement to display the string variable.

Á Save the file as join.html.

‡ Open join.html in a browser.

■ The converted array is displayed separated by commas.

32

CONVERT AN ARRAY TO A STRING

Page 49: Javascript Tutorial - 4730-5

⁄ Open the join.html file in Notepad.

¤ Add a string with a space as a parameter to the join() method.

Note: In Step 2, you are specifying to use a space as a separator rather than the default comma, so a space will appear in between each array element.

‹ Save the file as join2.html.

› Open join2.html in a browser.

■ The converted array is displayed separated by spaces.

These statements declare an array of elements,convert the array of elements into a string calledstr1, and then set the variable beginCharequal to the position in the string where thevalue “123” starts. Using these statements, youcan locate specific elements within the array.After you locate these elements, you can parseout the data by using other string objectmethods. Chapter 9 covers string objectmethods in detail.

33

USING VARIABLES AND ARRAYS

SPECIFY A UNIQUE SEPARATOR

2

Large arrays can be difficult to search throughto find specific pieces of data. An easier wayto search through an array is to convert theentire array to a single string and then use theindexOf() method to locate the specificdata:.

Example:

array1 = new Array(“hello”,“123”, “senior”, “blank”,“fixed”);

str1 = array1.join(“ ”);

beginChar = str1.indexOf(“123”);

Page 50: Javascript Tutorial - 4730-5

SORT AN ARRAY

An array full of elements can be converted to a string using the join() method, as shown in the section “Convert an Array

into a String.” The array object also includesanother method that sorts the array elementsin ascending alphabetical order beforeconverting them into strings — sort().

For example, if you have an array of wordsnamed array1, you can sort the words andconvert them to a string using the str1 =array1.sort() statement.

When the sort() method is used on an arrayof numbers, the numbers are sortedalphabetically instead of in numerical order. Forexample, an array containing 1, 2, 10, 12would be sorted as 1, 10, 12, 2.

This example uses the join.html file foundon the book’s CD-ROM (or which you mayhave created in the section “Convert an Arrayinto a String”), but you can apply these stepsto any file.

SORT AN ARRAY

JAVASCRIPT

⁄ Open the join.html file in Notepad.

¤ Change the join() method to the sort() method.

‹ Save the file as sort.html.

› Open sort.html in a browser.

■ The array is alphabetically sorted.

34

SORT AN ARRAY OF WORDS

Page 51: Javascript Tutorial - 4730-5

⁄ Open the sort.html file in Notepad.

¤ Change the array elements from strings to numbers.

‹ Save the file as sort2.html.

› Open sort2.html in a browser.

■ The array is sorted, but not in numerical order.

When the sort() method is executed, thefunction numSort is called. This functionaccepts two parameters and returns thedifference between them. This difference is usedby the sort() method to sort the numbers innumerical order. As the sort() methodtraverses the array elements, the numSortfunction is called as often as needed tocomplete the sorting.

35

USING VARIABLES AND ARRAYS 2

SORT AN ARRAY OF NUMBERS

The sort() method can accept a functionname as a parameter. The function name cancontain an alternative way to sort the array.This parameter can be used to sort an array ofnumbers numerically instead of alphabetically.The statements for this would look like this:

function numSort(var1, var2) {

return var1 – var2;

}

array1 = new Array(“1”, “2”,“12”, “34”, “72”);

str1 = array1.sort(numSort);

Page 52: Javascript Tutorial - 4730-5

JAVASCRIPT

36

⁄ Open the js-skeleton.html file in Notepad.

¤ Create two new variables and assign a number to each.

‹ Create four new variables and assign each to an arithmetic expression created using the first two variables.

› Use several document.write statements to display the value of each variable.

ˇ Save the file as arithmetic.html.

Á Open arithmetic.html in a browser.

■ The values of each evaluated arithmetic expression are displayed.

3636

USING ARITHMETIC OPERATORS

Expressions are used to composemathematical equations. These equationscan compute a desired result, which can

then be displayed in a browser.

Expressions are created with variables orliterals on either side of an operator. Literalscan be numerical or string values.

The easiest expressions to create use arithmeticoperators. The four standard arithmetic operatorsare addition (+), subtraction (–), multiplication(*), and division (/). These operators only workif the variables on both sides of the operator arenumbers. However, the addition operator canalso be used to combine strings.

The subtraction operator can be used as anegation operator if it is placed in front of avariable or number. For example, temp1 = -var1; makes the value of var1 negative andplaces the result in temp1.

Another less popular arithmetic operator is themodulus operator (%). This operator returns thevalue of the remainder after dividing twonumbers. For example, 11%5 would return avalue of 1, because 5 goes into 11 two timeswith a remainder of 1.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING ARITHMETIC OPERATORS

USING ARITHMETIC OPERATORS

Page 53: Javascript Tutorial - 4730-5

CREATING EXPRESSIONS

37

⁄ Open the arithmetic.html file in Notepad.

¤ Create a new variable and assign it to a modulus expression using the first two variables.

‹ Use a document.write statement to display the value of the modulus expression.

› Save the file as modulus.html.

ˇ Open the file modulus.html in a browser.

■ The value of the modulus expression is displayed.

The addition operator can be used tocombine strings, but all other arithmeticoperators return a NaN value if they are usedon strings. NaN stands for “not a number.” Ifthe string is a number and it doesn’t includeany letters, JavaScript automatically convertsthe string to a number and evaluates theexpression. See Chapter 9 for more detailson using strings.

USING THE MODULUS OPERATOR

3

You can define a factorial as subtracting onefrom the current value and multiplying it timesthe result. For example, 3 factorial would be 3 × 2 × 1 for a result of 6. A function tocompute factorials would look like this:

function factorial(num) {

for (j=num;j>0;j—)

result *= num;

return result

}

This function uses several expressions toevaluate the factorial result. The result is thenreturned.

Page 54: Javascript Tutorial - 4730-5

INCREMENT AND DECREMENTVARIABLES

One of the simplest expressions to createis one that increments or decrements avariable. Incrementing expressions are

useful as counters and for loops.

Variables can be incremented by adding 1 withthe variable and assigning it to the same variablelike this, var = var + 1. JavaScript, however,offers an easier way to increment values withtwo plus symbols (++) attached to the variable.

For example, var++ automatically increases thevalue of the variable named var when evaluated.

Variables can in a like manner be decrementedusing two minus signs (--). This character setcauses the variable to be decreased by 1. Forexample, var-- automatically reduces thevalue of var by 1.

The increment and decrement operators areboth unary operators, which means that theyrequire only a single operand instead of twolike the arithmetic operators.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

INCREMENT AND DECREMENTVARIABLES

INCREMENT VARIABLES

JAVASCRIPT

⁄ Open js-skeleton.html in Notepad.

¤ Create a new variable and assign it a number.

‹ Use a document.write statement to display the value of the variable.

› Increment the variable with the ++ symbols.

ˇ Add another document.write statement to again display the value of each variable.

Á Save the file as inc.html.

‡ Open inc.html in a browser.

■ The values of each variable are displayed before and after the increment and decrement expressions.

3838

Page 55: Javascript Tutorial - 4730-5

CREATING EXPRESSIONS 3

⁄ Open the inc.html file in Notepad.

¤ Create another variable and assign it a number.

‹ Add a document.write statement to display the value of each variable.

› Decrement the variable with the -- symbols.

ˇ Add another document.write statement to again display the value of the variables.

Á Save the file as dec.html.

‡ Open dec.html in a browser.

■ The values of each variable are displayed before and after the increment and decrement expressions.

The increment or decrement operator doesn’talways have to follow the variable: Theincrement or decrement operator can comebefore or after the variable, but subtledifferences distinguish the two when usedwith an assignment operator (=). If theincrement or decrement operator comesbefore the variable, like var1 = ++var2,var2 gets incremented before the value isassigned to var1. If, however, the operatorcomes after the variable, the value of var2gets assigned to var1 before it is incrementedor decremented.

You can use the similar expression x = x +1 instead of the simpler x++. The incrementoperator is used often enough, however, tomake it worth having.

39

DECREMENT VARIABLES

Page 56: Javascript Tutorial - 4730-5

CREATE COMPARISON EXPRESSIONS

Comparison expressions are used tocompare the values of two variables.When evaluated, comparison

expressions result in a Boolean value of eithertrue or false.

These statements are typically used to controlthe program flow and are covered in moredetail in Chapter 4. For example, an ifstatement uses comparison expressions todecide whether to execute certain statements.

The comparison operator is designated withtwo equals signs (==). It is used to determine iftwo values are equal and is different from theassignment symbol (=). Using a single equals

sign in a comparison expression is a commonerror in JavaScript.

Another common comparison operatorcompares if two variables are not equal. Thisoperator is specified with an exclamation pointin front of an equals sign (!=).

You can also check to see if two variables aregreater than (>), less than (<), greater than orequal to (>=), or less than or equal to (<=)each other.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

CREATE COMPARISON EXPRESSIONS

CREATE COMPARISON EXPRESSIONS

JAVASCRIPT

4040

⁄ Open the js-skeleton.html file in Notepad.

¤ Create a new variable and assign it a number.

‹ Create a comparison expression as part of an if statement. Within the if

statement, assign another variable a value.

› Use document.write statements to display the value of each variable.

ˇ Save the file as comp.html.

Á Open the file comp.html in a browser.

■ The values of each variable are displayed.

Page 57: Javascript Tutorial - 4730-5

CREATING EXPRESSIONS 3

‡ Open comp.html in Notepad.

° Reset the variable’s value.

· Create a comparison expression like Step 3’s.

‚ Create another comparison expression using the greater

than operator within an if statement. Within the if statement, assign another variable a value.

— Use document.write statements to display the value of each variable.

± Save the file as comp2.html.

¡ Open comp2.html in a browser.

■ The values of each variable are displayed.

Although it is relatively easy to determine theresults of a comparison expression whennumbers are used, comparison operators canalso use strings. When comparing strings tobe equal such as (“happy birthday” ==“Happy Birthday”), the result would befalse because JavaScript is case sensitive.

The less than and greater than operators canalso be used with strings. When strings arecompared, their ASCII values are compared.ASCII values associate a number to eachcharacter on the keyboard. The computer canrecognize these numbers and use them todisplay the proper characters on the screen.The comparison results in A being less than aand a being less than b, because the ASCIIvalue for A is less than the ASCII value for a.

41

Page 58: Javascript Tutorial - 4730-5

CREATE LOGICAL EXPRESSIONS

Another type of operator is a logicaloperator. Logical operators can be usedto combine several different comparison

expressions together into a single complexstatement. They also result in a Boolean valueand are often used to control program flow.

The logical operators include and, which isexpressed as two ampersand symbols (&&);or, which is expressed as two bar symbols(||); and not, expressed as an exclamationpoint (!).

The and operator produces a true value ifboth sides of the expression are true. The or

operator produces a true value if either sideof the expression is true. The not operatorsimply reverses the Boolean value.

These logical operators when used shouldappear in between statements and should besurrounded with parentheses.

This example uses the comp.html file foundon the book’s CD-ROM (or which you mayhave created in the section “CreateComparison Expressions”), but you can applythese steps to any file.

CREATE LOGICAL EXPRESSIONS

CREATE LOGICAL EXPRESSIONS

JAVASCRIPT

⁄ Open the comp.html file in Notepad.

¤ Add a logical operator to the comparison statement.

■ The document.write statements display the value of each variable.

‹ Save the file as logical.html.

› Open logical.html in a browser.

■ The values of each variable are displayed.

4242

Page 59: Javascript Tutorial - 4730-5

CREATING EXPRESSIONS

To get a better idea of all the variations ofusing the logical operators, consider thefollowing examples. First, the and operator:

true && true = true

true && false = false

false && true = false

false && false = false

For the or operator, the following apply:

true || true = true

true || false = true

false || true = true

false || false = false

For the not operator, only two possibilities exist:

!true = false

!false = true

Logical operators evaluate the expression oneach side of the logical operator first and thenevaluate the logical operator. For example, thestatement (var1 > 17 && var1 < 25)combines the two statements in comparingwhether the variable is greater than 17 and lessthan 25. If the value of var1 equals 18, theresult of this expression is true.

43

3

ˇ Open the logical.html file in Notepad.

Á Create another logical expression as part of an if statement.

‡ Add document.write statements to display the value of the variables.

° Save the file as logical2.html.

· Open the file logical2.html in a browser.

■ The values of each variable are displayed.

Page 60: Javascript Tutorial - 4730-5

USING CONDITIONAL OPERATORS

A conditional operator is a single operatorused as a shortcut for a single if-elsestatement. if-else statements are

covered in Chapter 4. This operator consists ofa question mark (?) and a colon (:).

A conditional statement appears to the left ofthe question mark. If the conditional statementis true, the expression to the immediate left ofthe question mark is evaluated. Following thefirst expression comes the colon symbol andanother expression. If the conditionalstatement is false, JavaScript evaluates thestatement that follows the colon.

For example, the statement (var1 == 23)? (str2 = ‘yes’) : (str2 = ‘no’)would compare the value of var1. If this valueequals 23, the variable str2 is assigned thevalue of yes; if the value does not equal 23,str2 would be assigned no.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING CONDITIONAL OPERATORS

USING CONDITIONAL OPERATORS

JAVASCRIPT

⁄ Open the js-skeleton.html file in Notepad.

¤ Create new variables and assign them values.

‹ Use a conditional expression to determine the value of a variable.

› Use a document.write statement to display the value of each variable.

ˇ Save the file as conditional.html.

Á Open the file conditional.html in a browser.

■ The browser displays the values of each variable.

4444

Page 61: Javascript Tutorial - 4730-5

CREATING EXPRESSIONS

‡ Open the js-skeleton.html file in Notepad again.

° Create several new variables and assign each a value.

· Use a conditional expression to determine which expression to evaluate.

‚ Use a document.write statement to display the value of each variable.

— Save the file as conditional2.html.

± Open the file conditional2.html in a browser.

■ The values of each variable are displayed.

45

3

The value of the conditional expression isbest seen when compared with the structurethat it replaces. Consider the following code:

if (condition1 == true) {

expression1;

}

else {

expression2;

}

This is a simple if-else structure thatevaluates expression1 if condition1 is trueor expression2 if condition1 is false. Thissame structure can be replaced with a singleconditional statement that looks like this:

(condition1 == true) ? expression1 :expression2;

Some examples of a conditional expressioninclude the following:

(flipCoin) ? result=“heads” :result=“tails”;

(today=birthday) ? document.write(“Happy Birthday”) :document.write(“Happy Un-birthday”);

Page 62: Javascript Tutorial - 4730-5

The order of operator precedence afterparentheses is as follows:

1. Unary operators: ++, --, –, !

2. Arithmetic operators: *, /, %, +, –

3. Comparison operators: >, <, >=, <=

4. Logical operators: &&, ||

5. Conditional operator: ?:

6. Assignment operator: =

JavaScript evaluates operators in a specificorder. This order is known as operatorprecedence. The operators with the highest

precedence get evaluated first.

Parentheses have the highest precedence. Ifyou are ever in doubt of which expression is tobe evaluated first, include the separateexpressions within parentheses.

If the operators have the same level ofprecedence, such as an expression full ofaddition operators, JavaScript evaluates theoperators from left to right.

UNDERSTAND PRECEDENCE

JAVASCRIPT

⁄ Open the js-skeleton.html file from the CD-ROM in Notepad.

¤ Create several variables and assign each an expression with the same type of operators.

‹ Add pairs of parentheses to the expressions in different places.

› Use document.write statements to display the results of each expression.

ˇ Save the file as precedence.html.

Á Open precedence.html in a browser.

■ Notice how the values of each expression are different.

4646

UNDERSTAND PRECEDENCEUNDERSTAND PRECEDENCE

Page 63: Javascript Tutorial - 4730-5

CREATING EXPRESSIONS

⁄ Open the js-skeleton.html file in Notepad.

¤ Create a new variable and assign it an expression as a string in quotation marks.

‹ Use a document.write statement to display the value of the string variable.

› Use another document.write statement and the eval() keyword to evaluate and display the result of the string variable.

ˇ Save the file as eval.html.

Á Open the file eval.html in a browser.

■ The string variable is shown before and after it has been evaluated.

47

3

EVALUATE STRING EXPRESSIONS

EVALUATE STRING EXPRESSIONS

Sometimes expressions are contained within astring, such as when enabling the user to input toan expression into a form field. Using the eval()

function, you can instruct JavaScript to evaluate thestring as an expression.

For example, if a string variable called str1 wasassigned an expression such as 128 + 62, displayingthis variable value would be “128 + 62”. On theother hand, if you were to display eval(str1), theexpression would be evaluated and the value of 190would be displayed.

This example uses the js-skeleton.html file foundon the book’s CD-ROM, but you can apply these stepsto any file.

EVALUATE STRING EXPRESSIONS

You can use the eval() function toevaluate JavaScript commands in aroundabout way: When theeval() function is called, theJavaScript interpreter attempts toevaluate any string that is passedto it; you can save a JavaScriptstatement within a string andevaluate it using the eval()function.

Page 64: Javascript Tutorial - 4730-5

JAVASCRIPT

4848

IDENTIFY NUMBERS

JavaScript includes a unique method that canbe used to identify variables as numbers.This functionality is useful when you accept

input from the user and want to verify that thevalues entered are actually numbers. Trying toevaluate a numerical expression with a stringvalue causes an error.

The method to verify if a variable is a numberactually checks to see if it is not a number.This method is isNaN(), which accepts asingle parameter that is checked. If the variablesent to the method is a number, the methodreturns a false value; if the variable is not anumber, a true value is returned.

For example, if a statement is defined as var1= 23, the expression isNaN(var1) returns afalse value because the value of var1 is anumber (23).

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

IDENTIFY NUMBERS

IDENTIFY NUMBERS

⁄ Open the js-skeleton.html file in Notepad.

¤ Create a new variable and assign it a numeric value.

‹ Add a conditional expression based on the isNaN method.

› Include some document.write statements to display the results of the conditional statement.

ˇ Save the file as isNaN.html.

Á Open the file isNaN.html in a browser.

■ The browser determines that the variable is a number.

Page 65: Javascript Tutorial - 4730-5

CREATING EXPRESSIONS 3

49

‡ Open the isNaN.html file in Notepad again.

° Change the variable to a string.

· Save the file as isNaN2.html.

‚ Open the file isNaN.html in a browser.

■ The browser detects that this variable is not a number.

One of the best ways to use the isNaN()method is to validate data entered into aform. For example, if you accept numericalvalues in a form field that you are using tocompute an equation, you can cause an alertbox to appear if the user enters some inputthat is not a number. The code for this lookslike this:

<form name=“form1”>

Enter the circle radius.<inputtype=“text” name=“text1”onchange=”(isNaN(this.value))?window.alert(‘This is not a number. Pleaseenter a numerical value.’):document.form1.text2.value = (document.form1.text1.value*document.form1.text1.value*Math.PI)”/>

Area: <input type=“text”name=“text2”/>

</form>

This form includes two text fields. The first textfield is where the user enters the radius of acircle. The onchange event executes theconditional statement when a number is enteredand the focus of the text field is lost. Theconditional statement checks the isNaN()method to see whether the text entered is anumber. If it is, the area of the circle is computed.If not, an alert dialog box is displayed.

Page 66: Javascript Tutorial - 4730-5

JAVASCRIPT

FinderFinder FinderFinder

AppleWorksAppleWorks

■ Open js-skeleton.html in Notepad.

¤ Add two variables and assign each a value.

‹ Create an if statement with a conditional expression that checks a variable.

› Use a document.write statement to display some text if the if statement is true.

ˇ Create an else statement that uses a document.write statement if the statement is false.

Á Save the file as if-else.html.

‡ Open the file if-else.html in a browser.

■ The displayed text is determined by the conditional expression.

Note: If you had set the variable’s values to those other than what the if statement tested for, the text for the else statement would have been displayed.

50

USING IF-ELSE STATEMENTS

As you write scripts, you may sometimeswant to execute certain statementsdepending on a condition. For example, if

a user submits a form with no data, you willwant to respond differently than if he or shesubmitted the form correctly. One way tocontrol this type of program flow is with if-else statements.

The syntax of an if statement includes the ifkeyword followed by a conditional statementwithin parentheses. If only a single statementneeds to be executed, it can be positioneddirectly after the conditional statement andshould end with a semicolon. If severalstatements need to be executed, they can be

contained within a set of brackets.

An alternative statement is positioned below theif statement in an else statement. The elsestatement can also hold a set of bracketscontaining several JavaScript statements.

If the if condition statement is false, thestatements in the else statement are executed.

A single if statement can be followed by severalelse if statements, but the final elsestatement should not include the if keyword.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING IF-ELSE STATEMENTS

USING IF-ELSE

Page 67: Javascript Tutorial - 4730-5

CONTROLLING PROGRAM FLOW 4

⁄ Open if-else.html in Notepad.

¤ Change the values of the variables.

‹ In between the if and else statements, add two else if statements with different conditional expressions.

› Add statements to be executed under the else if statements.

Note: The final else statement should not include the if keyword.

ˇ Save the file as elseif.html.

Á Open the file elseif.html in a browser.

■ The displayed text is determined by the conditional expression.

This simple function compares successivedifferent attributes of a car. If each criteria ismet, the cool car! statement is displayed. Ifany of the criteria isn’t met, an alternativemessage is displayed.

51

USING MULTIPLE ELSE STATEMENTS

if loops can be nested one within another.This enables you to drill down from generalconditions to more specific ones. Each levelof a nested if-else structure could containsome statements. Using this structure, youcan pinpoint the exact criteria for yourstatements. For example, look how this codeworks:

function coolCar() {if (car == “Mustang”)

if (year == 1965)if (parts == “original”)

document.write(“cool car!”);else

document.write(“at least itruns.”);}

Page 68: Javascript Tutorial - 4730-5

USING FOR LOOPS

Another common program flow method isused to execute a statement orstatements a given number of times. This

can be efficiently done using a for loop.

A for statement consists of three distinctparts within parentheses that are separated bysemicolons. The first part defines the loop’sinitial condition, the second part defines theloop’s terminating condition, and the final partdefines how the loop is incremented.

The for loop begins at the defined initialcondition and continually executes thestatement or statements that follow the for

statement until the termination condition ismet. The for loop variable is incrementedeach time through the loop.

For example, the statement for(i=1;i<10;i++) begins with the loopvariable i set equal to 1 and loops through thestatements that follow nine times beforeexiting the loop.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING FOR LOOPS

USING FOR LOOPS

JAVASCRIPT

52

⁄ Open js-skeleton.html in Notepad.

¤ Add a for loop that starts at 1 and counts to 10.

Note: The three parts of this example’s for loop are as follows: count=1 defines the loop’s initial condition to be 1; count<=10 sets the loop’s

terminating condition as 10; and count++ determines that the variable is incremented by 1.

‹ Use a document.write statement to display the value of the variable.

› Save the file as forloop.html.

ˇ Open forloop.html in a browser.

■ The value at each step in the loop is displayed.

Page 69: Javascript Tutorial - 4730-5

CONTROLLING PROGRAM FLOW 4

Á Open the forloop.html file in Notepad.

‡ Change the expressions in the for statement.

Note: This example uses count=count*count, which multiplies the current value of the count variable by itself.

° Save the file as forloop2.html.

· Open the forloop2.html file in a browser.

■ The value at each step in the loop is displayed.

53

Although the example in this sectionincrements the loop variable, you can just aseasily cause the loop variable to decrement.For example, consider the following loop:

function countdown(start) {

for (j=1start;j>0;j--)

document.write(j + “<br/>”);

}

This function counts down from the numberpassed in as a parameter. The loop begins atthe start value and decreases by one eachtime through the loop until the loop value isno longer greater than 0.

Page 70: Javascript Tutorial - 4730-5

54

USING WHILE LOOPS

Another type of loop used in JavaScript isthe while loop. This loop is different fromthe for loop because it doesn’t count to

an end result. It simply continues to loopthrough the statements contained within thebrackets until a conditional expression evaluatesto false. This loop includes only a conditionalexpression after the while keyword.

When using a while loop, you need to besure that the conditional statement willeventually become false or the loop willcontinue indefinitely. You should also makesure that all variables in the conditionalstatement are defined.

For example, the statement while (var1<= 100) executes the statements that followuntil the variable, var1, is greater than 100. Ifthe statements within the loop never changethe value of var1, then the loop will continueindefinitely.

The while loop can also execute multiplestatements by including statements withinbrackets.

This example uses the forloop.html andforloop2.html files found on the book’sCD-ROM (or which you may have created inthe section “Using for Loops”), but you canapply these steps to any file.

USING WHILE LOOPS

USING WHILE LOOPS

JAVASCRIPT

⁄ Open the forloop.html file in Notepad.

¤ Add a count variable and assign it a value.

‹ Replace the for loop with a while loop.

› Add a count variable incrementing the statement within the loop.

ˇ Save the file as while.html.

Á Open while.html in a browser.

■ The values of the loop variable are displayed.

54

Page 71: Javascript Tutorial - 4730-5

CONTROLLING PROGRAM FLOW

Open the forloop2.html file in Notepad.

° Add a count variable and assign it a value.

· Replace the for loop with a while loop.

‚ Add a count incrementing statement within the loop.

— Save the file as while2.html.

± Open while2.html in a browser.

■ The count variable values are displayed as the loop progresses.

There are many ways to think about how toconstruct your loops; there will be timeswhen you want to use a while loop andothers when you want to use a for loop. Thetwo different ways of looping are similar, butthe for loop requires all the informationabout the loop to be part of the forstatement. The while loop can use variablesthat have been declared elsewhere.

If a while loop doesn’t include brackets,only the first statement that follows thewhile statement will be executed. If multiplestatements need to be executed, all statementsshould be included within brackets.

To exit a loop that appears to be loopingindefinitely, besides using the conditionalstatement as part of the while loop, you canuse the break statement. The section “BreakLoops” discusses this in detail.

55

4

Page 72: Javascript Tutorial - 4730-5

BREAK LOOPS

Sometimes you can get stuck in a loop.This scenario is called an infinite loop. Tobreak out of an infinite loop, you can use

the break keyword.

When JavaScript encounters the breakkeyword within a loop, it automaticallyterminates the loop and executes the firststatement that comes after the loop.

For example, if a while loop included aconditional expression that was always true,such as while (true), you could break outof this loop with the break statement.

This example uses the while.html file foundon the book’s CD-ROM (or which you mayhave created in the section “Using whileLoops”), but you can apply these steps to anyfile.

BREAK LOOPS

BREAK LOOPS

JAVASCRIPT

⁄ Open the while.html file in Notepad.

¤ Within the while loop, add an if statement to check for a variable.

‹ Add a break statement to execute if the if condition is true.

› Move the document.write statement to the bottom of the loop.

ˇ Save the file as break.html.

Á Open break.html in a browser.

■ When the condition of the if statement is true, the loop is terminated.

56

After you break out of a loop, you cannotreturn to it. The break statement exits theloop and doesn’t enable you to return to it. Allvariables remain in the same state they are inwhen the loop is broken.

Page 73: Javascript Tutorial - 4730-5

CONTROLLING PROGRAM FLOW 4

■ Open the break.html file in Notepad.

¤ Change the break statement to a continue statement.

‹ Save the file as continue.html.

› Open continue.html in a browser.

■ All values in the loop are displayed except for where the continue statement was executed.

57

CONTINUE LOOPSCONTINUE LOOPS

CONTINUE LOOPS

Another keyword that works with loops is thecontinue statement. This statement stops theexecution of a loop and returns to the top ofthe loop as if all the statements had beenexecuted. Any statements that follow thecontinue statement will not be executed forthis time through the loop.

This enables you to check for special exceptionswithin the loop and skip them withoutinterrupting the normal flow of the loop.

For example, if a while loop were to continueuntil var1 == 100, you could skip the

execution of the number 50 with the statementif (var1 == 50) continue;.

This example uses the break.html file foundon the book’s CD-ROM (or which you mayhave created in the section “Break Loops”), butyou can apply these steps to any file.

A single loop can include both break andcontinue statements, but after a breakstatement is executed, the loop is finished.

Page 74: Javascript Tutorial - 4730-5

USING JAVASCRIPT TIMERS

JAVASCRIPT

⁄ Open js-skeleton.html.

¤ Add a function that uses a document.write() statement to display a heading and an image.

‹ Add onload to the <body> tag and set it equal to window.setTimeout().

› Add the function name as the first parameter of setTimeout() and a time value, in milliseconds, as the second parameter.

ˇ Add a single heading to the <body> tags.

Á Save the file as timeout.html.

‡ Open the timeout.html file in a browser.

■ The <body> tags’ heading is displayed in the browser.

58

USING JAVASCRIPT TIMERS

JavaScript can be used to set up timers thatlet certain scripts be executed at differenttimes. These can be useful for timing

different actions on the Web page.

The function that makes timers possible is thewindow.setTimeout() function. Thisfunction accepts two parameters. The firstparameter is a JavaScript statement to execute.This can be a single statement, such asdocument.bgcolor = ‘blue’, or thename of a function that is defined elsewhere inthe Web page. The statement to execute caneven be several statements separated withsemicolons. The statements that make up this

first parameter need to be enclosed withinquotation marks.

The second parameter accepted by thewindow.setTimeout() function is thetime value to wait before the JavaScriptstatement is executed. This value is measuredin milliseconds. For example, a value of 5000would wait 5 seconds and a value of 10000would wait 10 seconds.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING JAVASCRIPT TIMERS

Page 75: Javascript Tutorial - 4730-5

CONTROLLING PROGRAM FLOW 4

° Wait for the designated time value.

■ The script function is executed after the timeout value is reached, displaying function’s heading and image.

· Open the timeout.html file again in a browser.

‚ Click the Stop button before the timeout value is reached.

■ The timeout is not stopped, and the image is again displayed.

Note: The timeout can only be cleared using the clearTimeout() method, which is discussed in the section “Clear Timeouts and Intervals” later in this chapter.

59

Chapter 11 covers the Math object. Thisobject includes a method that is used tocreate random numbers between 0 and 1.Using this method, you can create a scriptthat lets you play musical chairs by randomlyselecting a timeout. The code for this lookslike this:

<form name=“form1”>

<input type=“button”name=“button1” value=“Get Ready”onclick=“stopMusic()”/>

<input type=“text” name=“text1”value=“music is playing”/>

</form>

<script language=“javascript”>

function stopMusic() {

seat = Math.floor(Math.random() *10000);

stop =window.setTimeout(“document.form1.text1.value = ‘music stopped’”,seat);

}

</script>

The code creates a form with a button and a textbox. When a user clicks the button, thestopMusic() function is called. This functionrandomly selects a number that is used for thesetTimeout() method. The text box is updatedwhen the time expires to inform the users thatthe music has stopped.

Page 76: Javascript Tutorial - 4730-5

SET REGULARLY TIMED INTERVALS

JAVASCRIPT

⁄ Open js-skeleton.html in Notepad.

¤ Add a window.setInterval() method.

‹ Add a form with two text boxes.

› Set the first parameter of setInterval() to update the second text box with the contents of the first text box.

ˇ Set the second parameter of setInterval() to a time value.

Á Save the file as setInterval.html.

‡ Open setInterval.html in a browser.

■ Two text boxes are displayed.

60

SET REGULARLY TIMED INTERVALS

Setting timeouts results in a one-timeexecution of a statement or function. Ifyou want to set multiple timeouts, you

can include the setTimeout() methodwithin a for loop, or you can use anothermethod that can set up regularly repeatingtimeouts: setInterval().

The setInterval() method can be used toexecute a statement, function, or group ofstatements at regular intervals repeatedly. ThesetInterval() method accepts twoparameters, just like the setTimeout()methods. The first parameter is the statementto execute, and the second parameter is the

time in milliseconds until the statement isexecuted. You must enclose the first parameterwithin quotation marks.

Timeouts created with the setInterval()method continue indefinitely unless theclearInterval() method is called. Thesection “Clear Timeouts and Intervals,” later inthis chapter, covers this method in detail.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

SET REGULARLY TIMED INTERVALS

Page 77: Javascript Tutorial - 4730-5

CONTROLLING PROGRAM FLOW

° Enter some text in the first text field.

■ The setInterval statement is executed after the timeout value is reached, updating the second text box.

· Enter some different text in the first text box.

■ The text is again updated in the second box.

61

4

The code creates a form with a single text box.Interval() is then set to respond everysecond. At each interval, the time object iscreated and the toLocaleString() method isdisplayed in the text box. The time due to thesetInterval() method is updated everysecond.

Chapter 10 covers the Date object. Thisobject includes a method calledgetLocaleString() that gets the currentlocale’s time. Using this method and thesetInterval() method, you can create aclock with the following code:

<form name=“form1”>

<input type=“text” name=“text1”/>

</form>

<script language=“javascript”>

stop = window.setInterval(“time =newDate();document.form1.text1.value =time.toLocaleString()”,1000);

</script>

Page 78: Javascript Tutorial - 4730-5

JAVASCRIPT

62

CLEAR TIMEOUTS AND INTERVALS

In the section “Using JavaScript Timers,” Ishow that the Stop button on the browserdoes not end a timeout. Timeouts can only be

cleared internally using the clearTimeout()method. This method is part of the windowobject and can be referenced in the currentwindow as window.clearTimeout().

To use the clearTimeout() method, youneed to name the timeout when it is set. Youcan name a timeout by assigning thesetTimeout() method to a variable name.This variable name can then be used as aparameter to the clearTimeout() methodto terminate the timeout.

For example, if a timeout is assigned to avariable like timer1 = setTimeout(x++,1000), the timeout can be canceled at anytime with the clearTimeout(timer1)statement.

You can use a similar method for clearinginterval timeouts created with thesetInterval() method. This method isclearInterval().

This example uses the setInterval.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

CLEAR TIMEOUTS AND INTERVALS

CLEAR TIMEOUTS AND INTERVALS

■ Open the setInterval.html file in Notepad.

¤ Add a new variable and assign it to the setInterval() method.

‹ Add a button to the form with an onclick event.

› Set the onclick event to use the clearInterval() method.

ˇ Save the file as clearInterval.html.

Á Open the clearInterval.html file in a browser.

‡ Type some text in the first text box.

■ The text is updated in the second text box.

Page 79: Javascript Tutorial - 4730-5

CONTROLLING PROGRAM FLOW

63

4

In this code, a button is added to the form withan onclick event. The onclick event isassigned to clear the interval with theclearInterval() method. The parameter tothe clearInterval() method is the variablename that was assigned to the setInterval()method.

° Click the button. ■ The setInterval() method has been stopped.

· Type some text in the first text box.

■ The second text box is no longer updated.

The clock example created in the section “SetRegularly Timed Intervals” can be modified toinclude a button that stops the clock. Thefollowing code adds the Stop button:

<form name=“form1”>

<input type=“text”name=”text1”/>

<input type=“button”name=“button1” value=”Stop”onclick=“window.clearInterval(stop)”/>

</form>

<script language=“javascript”>

stop = window.setInterval(“time= newDate();document.form1.text1.value =time.toLocaleString()”,1000);

</script>

Page 80: Javascript Tutorial - 4730-5

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Create a new function definition with the function keyword and a name.

‹ Add a JavaScript statement within braces after the function declaration.

› Save the file as function.html.

ˇ Open function.html in your browser.

■ The function statements are not executed because they haven’t been called.

Note: By grouping statements within a function, you can execute the statements in the function as many times as needed.

6464

DECLARE A FUNCTION

Y ou can group sections of code togetherinto a structure called a function. You cancall and access a function at any time.

You can send parameters to functions, andfunctions can return values.

You declare functions with the functionkeyword followed by the function name.Parentheses always immediately follow thefunction name. Parameters for the function arecontained within these parentheses, butparameters are not required.

For example, the statement, functionhello() would declare a function namedhello.

All JavaScript statements within the functionshould be contained within braces after thefunction declaration.

The function statements will not be executeduntil the function is called.

Function names have the same limitations andfollow the same requirements as variables.They must begin with a letter, they must notcontain any spaces, and they cannot use anyspecial characters like +, *, /, &, %, $,#, @, or !. Also, remember that functionnames are case-sensitive.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

DECLARE A FUNCTION

DECLARE A FUNCTION

Page 81: Javascript Tutorial - 4730-5

WORKING WITH FUNCTIONS 5

⁄ Open the file function.html in Notepad.

¤ Add a function call after the function statement.

‹ Save the file as function-call.html.

› Open function-call.html in a browser.

■ The function statements are executed, and the results appear on the screen.

Note: When the function name is referenced, the statements within the function are executed. Functions can be called many times within a single file.

65

CALL A FUNCTION

CALL A FUNCTION

After you declare a function, you canexecute it at any time from anywherewithin the document by listing the

function name.

You need to include parentheses when calling afunction whether or not the function hasparameters.

For example, if a function is defined asfunction hello(), then you can executethis function with the statement hello();.

The function call can come before or after thefunction declaration.

This example uses the function.html filefound on the book’s CD-ROM (or which youmay have created in the section “Declare aFunction”), but you can apply these steps toany file.

CALL A FUNCTION

If you use the javascript: keyword, youcan call a function from an HTML link byusing the href attribute of an HTML <a> tag.The section “Call a Function from an HTMLLink,” later in this chapter, shows how to dothis.

Page 82: Javascript Tutorial - 4730-5

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.¤ Create two global variables with var.

‹ Create a function with a document.write statement that displays the values of the declared variables.

› Add a statement to execute the function.ˇ Include another document.write statement outside of the function to display the variable values.

Á Save the file as global.html.

‡ Open the global.html file in your browser.

■ The variables are global because they are declared outside of the function and can be used anywhere within and without functions.

66

UNDERSTAND GLOBAL AND LOCALVARIABLES

Any variables declared with the varkeyword within a function will be local tothe function that they appear in. These

local variables will only be understood withinthe function and are not recognized in anyJavaScript statements outside of the function.

For example, if a variable named myVar1 isdeclared within a function using the varkeyword, then within the function the variablecan be used, but if it is referenced outside ofthe function, then the value will be unknown.

Variables that are implicitly declared withoutthe var keyword in a function will be global.Variables declared outside of functions (even ifthey are declared using the var keyword) arealso global. Global variables can be usedanywhere within the current documentincluding both inside and outside of functions.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

UNDERSTAND GLOBAL AND LOCALVARIABLES

GLOBAL VARIABLES

Page 83: Javascript Tutorial - 4730-5

WORKING WITH FUNCTIONS 5

⁄ Open the file global.html in Notepad.

¤ Move the two variable declarations within the function.

Note: This makes the variables local to the function because they are declared with the var keyword and are now within the function.

‹ Save the file as local.html.

› Open local.html in your browser.

■ A dialog box appears stating that the page has errors.

ˇ Click the Show/Hide Details button to see the errors.

■ Notice that the local variables are undefined when used in the document.write statement outside of the function.

67

A convenient way to keep track of global andlocal variables is to adopt specific codingconventions that have a naming standard thathelps to keep the scope of a variable straight.For example, if you place a lowercase g onthe front of every global variable, as in gVar1,then you can identify a global variable by justlooking at the variable name.

One reason to use local variables is that youwant to build functions that can be easilyreused. By using local variables, you can beguaranteed that regardless of where thefunction is copied, it will not conflict witha global variable that shares the same variablename.

It’s a good idea to use the var keyword outsideof functions. Any variables that are declaredwithout the var keyword are global. Anyvariables declared outside of a function are alsoglobal. Using the var keyword will make itobvious to anyone looking at your code that youare declaring a variable.

LOCAL VARIABLES

Page 84: Javascript Tutorial - 4730-5

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Create a function with a single parameter that displays a message and the parameter value.

■ In this example, the parameter is item.

‹ Add several calls to the function, each with a different value.

› Save the file as parameters.html.

ˇ Open parameters.html in your browser.

■ The function repeats with each call, each with a separate value.

68

PASS A SINGLE PARAMETER

PASS PARAMETERS TO A FUNCTION

If you want to execute a function usingdifferent variable values, you can pass theseas parameters to a function.

Parameters can be passed into a functionwithin the parentheses that follow the functionname. Several variables can be passed if youseparate them with commas.

The calling statement should include thevalues, and the function definition shouldinclude the variable name. You can then usethese variable names within the function. Thenumber of values in the function call should

match the number of variables in the functiondefinition.

For example, if a function is defined asfunction sum(a, b, c), then thefunction call sum(16, 34, 98) would placethe value of 16 in the variable named a, 34 inthe variable named b and 98 in the variablenamed c.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

PASS PARAMETERS TO A FUNCTION

Page 85: Javascript Tutorial - 4730-5

WORKING WITH FUNCTIONS

⁄ Open the file js-skeleton.html in Notepad.

¤ Create a function with several parameters that computes and displays a value.

‹ Add a call to the function.

› Save the file as parameters2.html.

ˇ Open the parameters2.html file in your browser.

■ The computed value is determined by the values passed to the function.

69

5

PASS SEVERAL PARAMETERS

Parameters that are passed to a function arelocal to the function. If a parameter variable isused outside of the function, it will generatean error.

If a function call doesn’t include anyparameters, the function name still needs anempty set of parentheses. These parentheseshelp identify the name as a function.

There is no limit to the number of parametersthat can be passed to a function, so you canpass as many parameters to a function asyou need.

When you call a function, the parameter that ispassed can be a variable or a value. If a variableis passed, then the value of the variable at thetime the function is called is sent to thefunction.

Page 86: Javascript Tutorial - 4730-5

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.¤ Create a function with several parameters that computes a value.

‹ Add a return statement to the function that returns the resulting value.

› Add another document.write statement that calls the function and displays the resulting value.ˇ Save the file as return.html.

Á Open the return.html file in a browser.

■ The returned value is displayed.

70

RETURN VALUES FROM A FUNCTION

You can return values from a function byusing the return keyword. This allowsthe function to determine a resulting

value and send that value back to the mainprogram.

For example, if you create a function thatcomputes a sum and the sum value is stored ina variable named total, then the statementreturn total would send the value oftotal back to where the function was called.

Because a value is being passed back to thefunction call, the function call needs to be a

statement that uses the returned value. Forexample, var1 = func1() would place thereturned value from the func1() functioninto a variable named var1.

The type of data returned from a functioncould be a string, number, or any other value.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

RETURN VALUES FROM A FUNCTION

RETURN VALUES FROM A FUNCTION

Page 87: Javascript Tutorial - 4730-5

WORKING WITH FUNCTIONS

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a function that accepts a single string parameter.

‹ Surround the string parameter with a set of HTML tags and set it equal to a return variable.

› Return the modified string with the return keyword.

ˇ Use a document.write statement to display the returned string.

Á Save the file as return2.html.

‡ Open the return2.html file in your browser.

■ The string passed to a function is returned formatted.

Note: Functions that return desired results can be included within statements.

71

5

RETURN HTML VALUES

A good example of a function that returns avalue is one that accepts parameters,computes a result of an equation, and returnsthe resulting value. For example, a functionthat computes and returns the computed areaof a box, given width, height, and depthparameters, looks like this:

function computeArea(width, height,depth) {

area = width * height * depth;

return area;

}

If this function is included in a Web page file,you could call the function with the followingstatement:

computeArea(3, 4, 5);

The function result is returned directly to thefunction call and can be used within a statementsuch as this:

document.write(“The area of the boxwith the dimensions: “ + width + “, “+ height + “, “ + depth + “ equals “ +computeArea(3, 4, 5));

Page 88: Javascript Tutorial - 4730-5

JAVASCRIPT

⁄ Open the file function.html in Notepad.

¤ Outside of the <script> tags, add two <a> tags and include some link text.

‹ Add the href attribute to each set of <a> tags.

› Set the first href attribute equal to javascript: and the function name.

ˇ Set the second href attribute equal to javascript: and a JavaScript statement.

Á Save the file as href.html.

‡ Open the href.html file in your browser.

■ Two links are displayed.

° Click the first link.

72

CALL A FUNCTION FROM AN HTML LINK

Functions can be called by referencing thefunction name as a JavaScript statement.You can also call a JavaScript function by

referencing the function name within an HTMLlink. This is done using the javascriptkeyword followed by a colon and the functionname.

For example, if a link is defined using the <a> tagand the href attribute is set to javascript:hello(), then the hello() function wouldbe called when you click the link.

You can also use this format to call a functionfrom the browser’s Address field. If you type injavascript: and the function name, thefunction will be executed.

This example uses the function.html filefound on the book’s CD-ROM (or which youmay have created in the section “Declare aFunction”), but you can apply these steps toany file.

CALL A FUNCTION FROM AN HTML LINK

CALL A FUNCTION FROM AN HTML LINK

Page 89: Javascript Tutorial - 4730-5

WORKING WITH FUNCTIONS

■ The function executes and the quote is displayed.

Note: Clicking the HTML link calls the function that displays a quote.

· Click the Back button on your browser.

‚ Click the second link. ■ Clicking this second link executes another JavaScript statement, which displays another quote.

E:\Temp\Authoring\JSB\examples\Ch05 - Working with Functions\global.html - Micrsoft… E:\Temp\Authoring\JSB\examples\Ch05 - Working with Functions\global.html - Micrsoft…

73

5

The HTML form displays a submit buttonlabeled “Display Welcome” in the browser.Clicking this button executes the hello()function, which displays a welcome message.

Another place within an HTML page where afunction call can be placed is within theaction attribute of a <form> tag. For example,

function hello() {

document.write(“Hello andWelcome”);

}

. . .

<form action=”javascript:hello()”>

<input type=”submit” value=”DisplayWelcome”/>

</form>

Page 90: Javascript Tutorial - 4730-5

USING JAVASCRIPT EVENTS

JavaScript events are bits of code that linkusers actions with the scripts that need tobe executed. These actions can be clicking

the mouse, pressing a keyboard key, selectingor changing form elements, or even loadingand unloading a Web page.

You can position JavaScript events withinHTML tags just like the other attributes. Youcan set them equal to a small line of JavaScriptcode or to the name of a JavaScript functiondeclared elsewhere in the Web page.

For example, the onclick event can beadded as an attribute to the <button> tagand set equal to the function named blink,like this:

<button onclick=“blink();”/>

This tag will not only display a button on theWeb page, but after you click this button, theblink() JavaScript function will also beexecuted.

There are a number of different events thatyou can use within a Web page, and the placeswhere you can use them are different for eachevent. Some of the more common JavaScriptevents are covered in this chapter, includingmouse events, keyboard events, and selectionevents.

USING JAVASCRIPT EVENTS

JAVASCRIPT

74

MOUSE EVENTS

Mouse events fire when the user clicks ormoves the mouse. If the user clicks the mousebutton once, the onclick event fires. If theuser clicks the mouse button twice,ondblclick event is fired.

For more precise details, you can use theonmousedown event to signal when the mousebutton is pressed down and the onmouseupevent when a mouse button is released.

The onmouseover event detects when themouse cursor moves over the top of anelement. The onmouseout event detects whenthe mouse cursor moves off an element.

Page 91: Javascript Tutorial - 4730-5

75

MISCELLANEOUS EVENTS

Another common event used with formelements is the onchange event. This eventfires whenever the data of the form element ischanged.

The onload event is used to detect when aWeb page has completely finished loading.Similarly, the onunload event is fired when aWeb page is unloaded. This happens when youleave the current page or when you click thebrowser’s Refresh button.

When you cancel a Web page that is loadinginto your browser, then the onabort event iscalled.

Two form buttons have specific functions —submit and reset. These same functions canbe detected using the onsubmit and onresetevents.

KEYBOARD EVENTS

The onkeypress event can be used to detectwhen a key on the keyboard is pressed. Thespecific key that was pressed can be found inthe window.event.keycode object.

Similar to the mouse button clicks, theonkeydown event detects after the key is firstpressed and held down, and the onkeyupevent fires after the pressed key is released.

SELECTION EVENTS

When an element is highlighted in the browser,it is said to have focus. The onfocus event isused to signal when an element has the focus.Pressing the Tab key can change this focus.When an element loses the focus, the onblurevent fires.

When you select an element, the onselectevent is fired.

HANDLING EVENTS 6

Page 92: Javascript Tutorial - 4730-5

DETECT A MOUSE CLICK

One of the keys to interacting with theuser is to detect mouse clicks. When auser clicks the Web page, he or she

usually expects something to happen. Buttonsand links are prime targets for a clickingmouse, but form elements, including radio andcheck box buttons, can also be clicked with themouse.

A single mouse click can be detected using theonclick event. This event can then trigger aneffect using JavaScript.

The onclick event is typically added to formbuttons such as submit and reset buttons,

created using the <input/> and/or<button> tags. You can also use theonclick event within the <a> tag.

The onclick event is one of the intrinsicevents that is recognized by almost every Webelement. Intrinsic events are a set of commonevents that you can use with a majority of thestandard HTML tags.

This example uses the skeleton.html filefound on the book’s CD-ROM, but you canapply these steps to any file.

DETECT A MOUSE CLICK

JAVASCRIPT

⁄ Open the file skeleton.html in Notepad.

¤ Add <form> and <input/> tags between the <body> tags.

‹ Add the name attribute to the <form> tag and set it to form1.

› Add the type, name, and value attributes to the <input/> tag.

Set the type attribute to button, the name attribute to button1, and the value attribute to the button face text.

Á Add the onclick JavaScript event to the <input/> tag.

‡ Set the onclick event equal to a JavaScript statement that changes the button text.

° Save the file as onclick.html.

76

DETECT A MOUSE CLICK

Page 93: Javascript Tutorial - 4730-5

HANDLING EVENTS

· Open the onclick.html file in your browser.

■ A single button is displayed.

‚ Click the button. ■ The text on the button face changes according to the JavaScript statement in the onclick event.

The onclick event detects when the mousebutton is clicked and released. The action ofclicking and releasing the mouse button canbe detected individually using theonmousedown and onmouseup events. Theuser could press the mouse and not releaseit. In this case, the onclick event would notdetect this action, but the onmousedownevent would.

The onmousedown and onmouseup events arevery similar to the onclick function. They arealso intrinsic events that you can use withalmost every HTML tag.

There is a separate event for detecting double-clicks: The onclick event detects a singleclick, but the ondblclick event detectsdouble-clicks. This event is covered in the nextsection, “Detect a Double-Click.”

77

6

Page 94: Javascript Tutorial - 4730-5

DETECT A DOUBLE-CLICK

Double-clicking is very similar to single-clicking except that the user clicks twicerapidly instead of once on the mouse

button.

Double-clicks can be detected using theondblclick event. You can add this event toall the same elements as the onclick event,including the <input/>, <button>, and <a>tags.

The ondblclick event is also an intrinsicevent. This means that you can use it withalmost any Web element.

You can use double-clicks to add a dualfunction to a button. If you set the onclickevent to process one set of commands and theondblclick event to process a second set ofcommands, then you can use single interfaceelements, like a button, to accomplish twice asmuch work.

This example uses the onclick.html filefound on the book’s CD-ROM (or which youmay have created in the section “Detect aMouse Click”), but you can apply these stepsto any file.

DETECT A DOUBLE-CLICK

JAVASCRIPT

⁄ Open the file onclick.html in Notepad.

¤ After the onclick event, add the ondblclick event.

‹ Set the ondblclick event equal to a JavaScript statement to change the button text.

› Save the file as ondblclick.html.

ˇ Open the ondblclick.html file in your browser.

■ A single button is displayed.

Á Click the button.

78

DETECT A DOUBLE-CLICK

Page 95: Javascript Tutorial - 4730-5

HANDLING EVENTS

■ The text on the button changes.

‡ Double-click the button. ■ The text on the button changes according to the JavaScript statement in the ondblclick event.

79

6

Intrinsic events are a set of events that can beadded to almost every Web element. The list ofintrinsic events includes onclick,ondblclick, onmousedown, onmouseup,onmouseover, onmousemove, onmouseout,onkeypress, onkeydown, and onkeyup.

If the ondblclick event is fired, theonclick event fires as well, because theonclick event is fired any time the mouse isclicked — even when the ondblclick eventis fired.

A single tag can include multiple events.These events are processed in the order thatthey are listed. For example, if a tag includesboth onclick and ondblclick events,then both will be processed any time theelement is clicked twice rapidly.

Page 96: Javascript Tutorial - 4730-5

CREATE ROLLOVER BUTTONS

Rollover buttons are useful in helping theuser to navigate through a Web page.When the mouse cursor moves over the

top of a rollover button, the button changes itsappearance. In JavaScript, you accomplish thisby replacing the original image with a newimage.

You can create rollover buttons by using theonmouseover and onmouseout events. Theonmouseover event is set to display a newimage in place of the original, and theonmouseout event is set to display theoriginal image.

Using the onmouseover and onmouseoutevents causes the new image to display whenthe mouse cursor is over the top of the buttonand the original image to display after themouse cursor leaves the button.

You can use the onmouseover andonmouseout events with hypertext links,image maps, and images.

This example uses the skeleton.html filefound on the book’s CD-ROM, but you canapply these steps to any file.

CREATE ROLLOVER BUTTONS

JAVASCRIPT

⁄ Open the file skeleton.html in Notepad.

¤ Add the <img/> tag.

‹ Add the src attribute and set it equal to an image filename.

› Add the onmouseover and onmouseout events.

ˇ Set the onmouseover event to load another image.

Á Set the onmouseout event to load the original image.

‡ Save the file as rollover.html.

° Open the rollover.html file in your browser.

■ A single image is displayed.

80

CREATE ROLLOVER BUTTONS

Page 97: Javascript Tutorial - 4730-5

HANDLING EVENTS

· Move the mouse cursor over the top of the image.

■ The image changes to the image specified in the onmouseover event.

‚ Move the mouse cursor away from the image.

■ The image reverts to its original look.

Events don’t always need to call a JavaScriptfunction. You can set JavaScript events equalto any valid JavaScript code. This code couldbe a single line of JavaScript, multiple lines ofJavaScript, or a call to a function that isdefined within a set of <script> tags.Within the event, each line of JavaScript mustend with a semicolon (;) including functioncalls.

The onmousemove event triggers wheneverthe mouse moves. This means that when theonmouseover or the onmouseout eventsfire, the onmousemove event also fires. Thisevent can be useful for detecting when a useris using the computer.

The <p> tag can accept the onmouseover andonmouseout events. Using this tag, you canexecute JavaScript statements when the mouserolls over normal text.

81

6

Page 98: Javascript Tutorial - 4730-5

DETECT A KEY PRESS

You can enter text into a text field ortextarea element using the keyboard,but there may be times when you want to

detect a single key press, such as a key to starta certain function.

When a keystroke on the keyboard is pressed,it can be detected using the onkeypressevent. The actual key that was pressed isidentified using thewindow.event.keyCode object.

Using the onkeypress event, you can checkfor the key that was pressed and reactaccordingly.

The onkeypress event is an intrinsic event,so you can use it with most Web elements.

With the onkeypress events, you can assignall your interface elements a quick selectionkey. This enables users to navigate yourinterface using just the keyboard. It also makesyour site accessible for people with disabilities.

This example uses the skeleton.html filefound on the book’s CD-ROM, but you canapply these steps to any file.

DETECT A KEY PRESS

JAVASCRIPT

⁄ Open the file skeleton.html in Notepad.

¤ Add <form> and <input/> tags between the <body> tags.

‹ Add the name attribute to the <form> tag and set it to form1.

› Add the type, name, and value attributes to the <input/> tag.

ˇ Set the type attribute to text, the name attribute to text1, and the value attribute to the text field text.

Á Add the onkeypress event to the <input/> tag.

‡ Set the onkeypress event equal to an if statement that checks the window.event.keyCode value and displays some text if correct.

° Save the file as onkeypress.html.

82

DETECT A KEY PRESS

Page 99: Javascript Tutorial - 4730-5

· Open the onkeypress.html file in your browser.

■ A single text field is displayed.

‚ Click in the text field to give it the focus.

— Press the D key on the keyboard.

■ The text updates to what you set it to in the onkeypress event.

The onkeydown and onkeyup events arevery similar to the onmousedown andonmouseup events. It is possible that theuser could press a keyboard key and notrelease it. In this case, the onkeydown eventwould detect this action, but theonkeypress event would not until thekeyboard key was finally released.

The onkeydown and onkeyup events willalways be fired whenever the onkeypressevent is fired, but the onkeydown event will bedetected before the onkeyup event.

If the onkeypress event is added to two ormore elements, the event will only be detectedif the element has focus. You can change thefocus of elements by using the Tab key.

83

HANDLING EVENTS 6

Page 100: Javascript Tutorial - 4730-5

SET FOCUS

Focus determines which form element willbe affected if the keyboard keys arepressed. For example, if a button has the

focus and you press the Enter key, it wouldrespond just as if you had clicked the buttonwith the mouse cursor.

Using HTML, you can set the tab order ofform elements. Using the Tab key, you canmove the focus between different formelements.

As the focus moves, you can detect if anelement has the focus by using the onfocus

event. Using the onblur event, you can set anaction to occur when an element loses focus.

You can use the onfocus and onblur eventswith the <select>, <input/>, and<textarea> tags, as well as withframesets.

This example uses the onkeypress.html filefound on the book’s CD-ROM (or which youmay have created in the section “Detect a KeyPress”), but you can apply these steps to anyfile.

SET FOCUS

JAVASCRIPT

⁄ Open the file onkeypress.html in Notepad.

¤ Replace the onkeypress event with the onfocus and onblur events.

‹ Copy the <input/> tag and paste another copy of it within the <body> tags.

› Change the name attribute of the second <input/> tag.

ˇ Set the onfocus and onblur events equal to a statement that changes the text field text.

Á Save the file as onfocus.html.

‡ Open the onfocus.html file in your browser.

■ Two text fields appear side-by-side.

° Click the left text field to give it the focus.

84

SET FOCUS

Page 101: Javascript Tutorial - 4730-5

■ The text updates according to the field’s onfocus event.

· Click the right text field. ■ The text updates in both fields — the first according to its onblur event (because it lost the focus) and the second according to its onfocus event (because it gained the focus).

Note: The onblur event for the second text field will fire when it loses focus.

You can use the onselect event with textfields and textarea elements to detectwhen a section of text is selected. After youknow that text is highlighted, you can workwith the selected section and replace, delete,or change it.

There are two events that can detect when aform is reset and submitted: onreset andonsubmit. The onreset event happenswhen a reset button is clicked, and theonsubmit event happens when a submitbutton is clicked. Using these events, you canoverride the default HTML action thathappens when these buttons are used.

One example of a situation in which you wouldneed to know if an element has focus is whenyou are trying to detect a keypress, because theonkeypress event will only work for theelement that has focus.

85

HANDLING EVENTS 6

Page 102: Javascript Tutorial - 4730-5

DETECT A PULL-DOWN MENU SELECTION

The selection list element is a commonway to offer a list of choices to the user.You can create selection lists within a

form by using the <select> tag. You cancreate each separate list item by using the<option> tags within the <select> tags.Using the onchange event, you can detectwhen a list item is selected.

The onchange event can detect when a formelement changes. The onchange event can beused with the <select>, <input/>, and<textarea> tags.

When you use the onchange event with thetext field and textarea elements, it detectswhen the text within these fields changes. Byusing this event, you can detect if the text wasupdated. Required fields can be checked to seeif they have been filled out before the form issubmitted.

This example uses the skeleton.html filefound on the book’s CD-ROM, but you canapply these steps to any file.

DETECT A PULL-DOWN MENU SELECTION

JAVASCRIPT

⁄ Open the file skeleton.html in Notepad.

¤ Add a <form> with a text box and a set of <select> tags.

‹ Add four sets of <option> tags with text.

› Add the onchange event to the opening <select> tag.

ˇ Set the onchange event to a statement that changes the text in the text field.

Á Save the file as onchange.html.

‡ Open the onchange.html file in your browser.

■ Two text fields appear side-by-side.

86

DETECT A PULL-DOWN MENU SELECTION

Page 103: Javascript Tutorial - 4730-5

° Click the first option in the selection list.

■ The text field updates according to the onchange event.

· Click the second option in the selection list.

■ The text field updates again.

87

HANDLING EVENTS 6

The onchange event is very useful forvalidating forms because it fires anytime aform element is changed. For example, if atext field is created that asks the user to inputan integer value between 0 and 9, you cancreate a function that validates the value thatis entered into the text field. Such a functionlooks like this:

function intCheck(val) {

if (val < 0 || val > 9)

document.alert(“This valueis out of range. Please enter aninteger value between 0 and 9.”);

}

. . .

<form name=”form1”>

<input type=”text” name=”text1”value=”1”onchange=”intCheck(this.value)”/>

</form>

When the text field is changed, the function iscalled. The value for this text field is passed as aparameter. This parameter is checked to see if itis less than 0 or greater than 9. If it is, an alertdialog box is displayed with a message.

Page 104: Javascript Tutorial - 4730-5

CREATE PAGE LOADING ANDUNLOADING MESSAGES

As Web pages get more complex, theymay take longer to load. This can beconfusing to the user who isn’t quite

sure if the page has fully loaded or not.

Using the onload event, you can notify theuser when the page has completely finishedloading. This event is usually placed within the<body> tag.

The onload event is useful to ensure that allthe graphics have been downloaded from theserver before executing a script on the page.

A similar event to onload is onunload. Thisevent happens when the current page is left orwhen the page is reset using a browser’sRefresh button.

You can use the onunload event to set anydefault values or provide a message to usersbefore they leave the current page.

This example uses the skeleton.html filefound on the book’s CD-ROM, but you canapply these steps to any file.

CREATE PAGE LOADING ANDUNLOADING MESSAGES

JAVASCRIPT

⁄ Open the file skeleton.html in Notepad.

¤ Add <form> and <input/> tags between the <body> tags.

‹ Add and set the type, name, size, and value attributes to the <input/> tag.

› Add the onload and onunload events.

ˇ Set the onload event to display a message in the text box and the onunload event to display an alert dialog box.

Á Save the file as onload.html.

‡ Open the file onload.html in a browser.

■ The loading Web page message appears while the page is loading.

88

CREATE PAGE LOADING AND UNLOADING MESSAGES

Page 105: Javascript Tutorial - 4730-5

■ After the Web page has finished loading, the message updates.

— Load a separate Web page in your browser.

■ An alert box appears with a message.

Any time a Web page is loading in a browser,the user can cancel the page by clicking theStop browser button. This action can bedetected using the onabort event. Thisprovides a useful way to inform the user whathas happened if all the elements haven’tloaded.

The onerror event lets you detect when anerror loading elements occurs. If the browserexperiences trouble loading an image or apage, then the onerror event fires. Usingthis event, you can present a message to theuser that is easy to understand.

It’s not always a good idea to display alert dialogboxes before the user leaves a Web page. Manyusers will not appreciate having to click in analert dialog box before they can leave your Webpage. This technique should be used withcaution.

89

HANDLING EVENTS 6

Page 106: Javascript Tutorial - 4730-5

JAVASCRIPT

⁄ Open the Notepad file.

¤ Add an attribute to the <body> tag that sets the background color.

‹ Within the <script> tags, add the document.write() method to display some text.

› Within the parentheses of the document.write() method, add the document.bgColor property.

ˇ Save the file as object.html.

Á Open the file object.html in a browser.

■ The document object’s method displays the object’s property value.

9090

UNDERSTAND OBJECTS, PROPERTIES,AND METHODS

To unleash the power of JavaScript, you need tounderstand the concept of objects. An object is anabstract container that holds data. This data can

be a single number or a complex data structure.

In JavaScript, you can create your own objects, or youcan use predefined objects, such as string, frame,image, date, and textarea.

Objects can have properties that can provideinformation about them. For example, the documentobject includes properties that hold the backgroundcolor and title of the page. Properties can be referenced

by placing a period between the object and propertyname, as in document.title.

Objects can also have methods, which are functionsspecific to the object that perform a task. For example,the document object has a method named write()that displays the value of the variable or stringcontained within the parentheses. Methods arereferenced just like properties, such asdocument.write().

This example uses the js-skeleton.html file foundon the book’s CD-ROM, but you can apply these stepsto any file.

UNDERSTAND OBJECTS, PROPERTIES,AND METHODS

UNDERSTAND OBJECTS, PROPERTIES, AND METHODS

Page 107: Javascript Tutorial - 4730-5

USING OBJECTS

‡ Open the object.html file in Notepad.

° Change the document.bgColor property to document.fgColor.

· Save the file as object2.html.

‚ Open the object2.html file in a browser.

■ The document’s foreground color value is displayed.

Here’s how you can tell the differencebetween a property and a method: An objectproperty reference ends with a single variablename, but a method always ends with a set ofparentheses. So any object reference thatincludes a set of parentheses is a method.The parentheses may or may not contain a setof parameter values. Either way, theparentheses are required.

Almost all the preset objects includeproperties and methods. Objects you create,however, will not necessarily have propertiesand methods. Creating objects is coveredlater in this chapter in the section “CreateNew Objects.”

91

Although several objects have commonproperties and methods, most are unique tothe object. No specific properties or methodsare common for all objects.

7

Page 108: Javascript Tutorial - 4730-5

The complete collection of JavaScript objectsthat refer to Web page elements is calledthe Document Object Model (DOM).

The parent object (the top object that contains asubobject) of the Document Object Model is thewindow object. This object includes everythingthat deals with the browser window, such as thelocation of the Web pages and the history, whichis a list of the previously visited pages.

The window object also includes thedocument object. The document objectincludes all the elements that make up theWeb page, such as links, images, and forms.

The form object includes many differentobjects representing the various elements thatcan be placed on a form such as text,textarea, password, button, radio,checkbox, select, and combo.

As the DOM is traversed, objects are referredto as subobjects of their parent. For example, aradio button on a form is referred to aswindow.document.form.radio.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING WEB PAGE ELEMENT OBJECTS

USING WEB PAGE ELEMENT OBJECTS

JAVASCRIPT

⁄ Open the Notepad file.

¤ Add a form with a textarea element under the <script> tags.

‹ Add buttons to the form using <input/> tags.

› Add the onclick event to each <input/> tag.

ˇ Set the onclick event for the first button to use a method.

Á Set the onclick event for the second button to use a property.

‡ Save the file as ta_object.html.

° Open ta_object.html in a browser.

■ The textarea element is displayed with two buttons.

· Click the first button.

9292

Page 109: Javascript Tutorial - 4730-5

USING OBJECTS

■ The text in the box is selected.

‚ Type some new text in the box.

— Click the second button. ■ The text you typed in the textarea box is displayed.

All Web page elements are included withinthe window parent object. This parent objectis assumed and doesn’t need to be includedalong with objects that are part of thedocument object. For example, a radio buttonobject can be referred to as document.form.radio instead ofwindow.document.form.radio.

The window object needs to be referred to forany object used outside of the currentdocument. This includes the location andhistory objects; the history object iscovered later in this chapter in the section“Using the history Object.” For example,to refer to the history object, you needto use the window.history notation.

93

7

Page 110: Javascript Tutorial - 4730-5

USING SUBOBJECTS

Objects can be nested in a hierarchy.Objects that are contained within anotherobject are referred to as subobjects.

These subobjects are linked to the parentobject (see the section “Using Web PageElement Objects”) with a period (.).Subobjects can also contain additionalsubobjects, thereby providing more and moredetail as the object definition is traversed.

For example, if a Web page includes a formnamed form1, and the form includes a textfield named text1, the value of the text field

can be identified as window.document.form1.text1.value. Here, document isthe parent, and form is a subobject. form alsoserves as the parent to the text field (itssubobject).

Object properties and methods can also bereferenced using the period (.). For example,document.bgColor is the background colorproperty for a Web page, and the methoddocument.write(“hello”) writes theword hello to the Web page.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING SUBOBJECTS

CHANGE A TEXT FIELD

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a form with a text field element in front of the <script> tags.

‹ Within the <script> tags, reference a subobject that alters the value of the text field.

› Save the file as sub-object.html.

ˇ Open sub-object.html in a browser.

■ The text within the text field is updated using JavaScript.

9494

Page 111: Javascript Tutorial - 4730-5

USING OBJECTS

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a form with two radio button elements in front of the <script> tags.

‹ Within the <script> tags, reference a subobject that displays a check mark in one of the radio buttons.

› Save the file as sub-object2.html.

ˇ Open the file sub-object2.html in a browser.

■ One of the radio buttons is checked (´) using JavaScript.

When referencing subobjects, the referenceshould always end with either an objectproperty or a method. If the reference doesn’tconclude with a property or a method, theobject is undetermined.

A reference to a subobject can be used withina JavaScript statement just like a variable.

You can’t include a space in a subobjectname. You can, however, use the underscorecharacter to separate terms in a name. TheJavaScript syntax uses periods to connectsubobjects to their parents. If a space is usedin the subobject name, the parent will beunidentified.

95

CHECK A RADIO BUTTON

7

Page 112: Javascript Tutorial - 4730-5

USING PREDEFINED OBJECTS

JavaScript’s predefined objects include usefulobjects for working with dates andmathematical functions, as well as objects

for interacting with all the various elements ofa Web page.

Many predefined objects, such as form,button, and frame, let you work with actualWeb page elements. These objects arediscussed in the earlier section “Using WebPage Element Objects.” Other predefinedobjects, such as String, Date, and Math, letyou work with different types of data.

Each of these objects has properties andmethods that can be used to get informationabout the object or to perform a certain task.These objects, their properties, and theirmethods are covered in more detail inChapters 10–14.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING PREDEFINED OBJECTS

USING THE STRING OBJECT

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a string variable and assign it a value (see Chapter 9).

‹ Use the document.write() method to display the string value.

› Add another string variable and assign it a substring of the first string.

ˇ Use the document.write() method to display the value of the second string.

Á Save the file as string.html.

‡ Open the file string.html in a browser.

■ The string and its substring are displayed.

Note: The substring is simply a portion of the original string. It begins at the character index specified by the substr parameter (in this example, 20).

9696

Page 113: Javascript Tutorial - 4730-5

USING OBJECTS

⁄ Open the file js-skeleton.html in Notepad.

¤ Use the document.write() method to display some text.

‹ Use the document.write() method to display the result of a value calculated from a Math property and a Math method.

› Save the file as math.html.

ˇ Open math.html in a browser.

■ The computed value is displayed.

A predefined object exists for almost every Webpage element, including browser history,anchors, links, plug-ins, check boxes, and resetbuttons. Many are accessible using generalbrowser objects. Chapters 12 and 14 discussthese in detail.

97

USING THE MATH OBJECT

7

Many of JavaScript’s predefined objects, theirproperties, and their methods are covered inChapters 9–11. These objects include Array,Date, Math, and String. The Array object isused to create and manipulate an array ofvariables. The Date object is used to createand manipulate dates and times. The Mathobject is used to represent mathematicalconstants such as logarithms and mathematicalexpressions. The String object enables you towork with strings.

An example of each of these objects is

MyArray = new Array(20);

MyDate = new Date(20);

Area = Math.PI * Math.pow(radius,2);

MyString = “Welcome to here.”;

Page 114: Javascript Tutorial - 4730-5

CREATE NEW OBJECTS

Some objects, like the string object, arecreated implicitly whenever a string isdeclared. For example, if you assign a

string to a variable such as str1 = “Hello,everyone”, you can access the propertiesand methods of this object by referring to thevariable name, such as str1.length.

Other objects, such as the Date object, need tobe created using the new keyword and afunction constructor. For example, to create anew Date object named myDate, you would

set the variable name equal to the new keywordand the constructor function for the Dateobject like this: myDate = new Date().

The new keyword, when used with theObject() constructor, can be used to createuser-defined objects.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

CREATE NEW OBJECTS

CREATE NEW OBJECTS

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a variable and assign it a new Date object.

Note: This new Date object allows you to retrieve the current date using the toLocaleString() method (see Chapter 10).

‹ Use the document.write() method to display the values of the current date and month.

› Save the file as new.html.

ˇ Open the new.html file in a browser.

■ The current date and month are displayed.

98

Page 115: Javascript Tutorial - 4730-5

USING OBJECTS

Á Open the new.html file in Notepad.

‡ Add another document.write statement to display the current time.

° Save the file as new2.html.

· Open the file new2.html in a browser.

■ The current time is also displayed.

99

7

You can create custom objects by using afunction to define the object. Variables withinthese functions become object properties,and the names of other functions become theobject methods.

For example,

function helloObject(var1, var2,var3) {

helloObject.name = var1;

helloObject.birthdate = var2;

helloObject.age = var3;

helloObject.welcome = printObject;

}

function printObject(name) {

document.write(“Welcome “ + name);

}

creates a new object named helloObject thathas name, birthdate, and age as propertiesand welcome() as a method.

Page 116: Javascript Tutorial - 4730-5

REFER TO THE CURRENT OBJECT

As you work with subobjects (see thesection “Using Subobjects”), you will findthat it is cumbersome to reference the

entire object tree every time you want to usean object. JavaScript includes a keyword thatcan be used to reference the current object.

The keyword to reference the current object isthis. The this keyword can be placed inplace of the object’s parent but can only beused within the current function.

For example, if you are using variables passedto a function, such as function

hello(str1), you can use the thiskeyword to refer to these variables, such asthis.name = str1.

Another place you can use the this keywordis to refer to the current Web element. Forexample, if you pass the text field value of aform to a function, you can refer to the valuewithin the event handler as this.value.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

REFER TO THE CURRENT OBJECT

IDENTIFY OBJECT PROPERTIES

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Create a function with parameters.

‹ Create a property for each parameter and assign it the parameter’s value.

› Using the new keyword, create another object.

ˇ Using document.write statements, display the object’s property values.

Á Save the file as this.html.

‡ Open this.html in a browser.

■ The values of the object instance are displayed.

100

Page 117: Javascript Tutorial - 4730-5

USING OBJECTS

⁄ Open the js-skeleton.html file in Notepad.

¤ Add a form with a text field to the page.

‹ Add the onclick event to the text field.

› Set the onclick event equal to the this.select() method.

ˇ Save the file as this2.html.

Á Open this2.html in a browser.

‡ Click the text field.

■ The text in the text field is selected.

This onclick event would pass the value of thecurrent element to the function. In this case, thevalue of the text field would be passed.

101

REFER TO THE CURRENT WEB PAGE ELEMENT

7

The this keyword can also be used as aparameter that is passed to a function. Forexample, suppose you have a function likethe following:

function makeBold(text1) {

document.write(“<b>“ + text1 +“</b>“);

}

Then, you could call this function from anevent within an HTML element like so:

<form name=“form1”>

<input type=“text” name=“text1”onclick=“makeBold(this.value)”

</form>

Page 118: Javascript Tutorial - 4730-5

VIEW OBJECT PROPERTIES

When working with an object, knowingall the object properties that theobject supports is quite helpful.

Having a JavaScript reference handy can helpwith this, but you can also use JavaScript to listan object’s properties.

A special version of the for loop can be usedto look into the object and view all itsproperties. This for loop includes the inkeyword and the object name.

For example, the statement for (prop inwindow) loops through all the properties in

the window object. You can then include adocument.write statement with the forloop to display the properties. You can also usethe window[prop] statement to display thevalues of the property.

These statements can only be used on objectsthat have been defined. If an object doesn’texist, no properties are displayed.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

VIEW OBJECT PROPERTIES

VIEW OBJECT PROPERTIES

JAVASCRIPT

⁄ Open the Notepad file.

¤ Add a for loop with the in keyword and an object name.

‹ Use the document.write() statement to display the object properties and its values.

Note: For predefined objects, a new object doesn’t need to be created.

› Save the file as window.html.

ˇ Open the file window.html in a browser.

■ The browser displays properties and values of the window object.

102

Page 119: Javascript Tutorial - 4730-5

USING OBJECTS

Á Open the window.html file in Notepad.

‡ Change the object in the for loop.

° Save the file as location.html.

· Open the file location.html in a browser.

■ The properties for the new object are displayed.

103

7

To make this object property viewer routinemore usable, you can include it as part of afunction and pass the object name to it. Thecompleted function looks something like this:

functiondisplayObjectProperties(obj) {

objName = obj + ““;

for (prop in obj) {

document.write(objName + “.” +prop + “ = “ + obj[prop] + “<br>“);

}

This function can then be called with anobject name, and the properties and theirvalues will be displayed. The statement to callthis function looks like this:

displayObjectProperties(window);

Page 120: Javascript Tutorial - 4730-5

USING THE ARRAY OBJECT

In Chapter 2, you find out about arrays andhow to create an array of variables. After anarray is created, you can work with the

Array object.

The Array object has a property calledlength that returns the length of the givenarray. For example, if you create a new arraywith the statement array1 = newArray(30), the array1.length property isequal to 30.

The Array object also includes severalmethods that can be used to manipulate thearray elements. The join() method combinesall array elements into a single string,

separating each element with a user-definedvalue passed as a parameter. For example, foran array named array1, the statementarray1.join(“ and “) produces a stringof all array elements with the word and inbetween each element.

You can also sort all the elements of an arrayusing the sort() method. The reverse()method reverses the order of all arrayelements.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING THE ARRAY OBJECT

USING THE ARRAY OBJECT

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Create a new Array object.

‹ Assign several values to the array.

› Use a document.write statement to display the length of the array.

ˇ Save the file as array.html.

Á Open the array.html file in a browser.

■ The array length is displayed.

104

Page 121: Javascript Tutorial - 4730-5

USING OBJECTS

‡ Open the array.html file in Notepad.

° Add another document.write statement that uses the join() method to display the contents of the array.

· Add another document.write statement that uses the sort() method to sort and display the array.

‚ Save the file as array2.html.

— Open the array2.html file in a browser.

Note: The array is defined to hold 10 elements, but only 5 of them are filled, so extra commas show the empty array slots.

■ The join() method lists the contents of the array in their original order. The sort() method displays a sorted list of the array elements.

■ The array length is now returned as 10 instead of 5.

105

7

In addition to the methods described in thissection, the Array object includes anothermethod called slice(). This method can beused to take a subsection of an existing arrayand extract it to create a new array. Theslice() method takes two parameters. Thefirst parameter is the index of the first arrayelement to include in the new array, and thesecond parameter is the last array element toinclude in the new array. A statement thatuses the slice() method would look likethis:

array1 = new Array(5);

array1[0] = “Thomas”;

array1[1] = “Dave”;

array1[2] = “Sue”;

array1[3] = “Adam”;

array1[4] = “Richard”;

array2 = array1.slice(1,2);

These statements create an array named array1that holds five elements. A new array, namedarray2, is created that holds two elements —Dave and Sue.

Page 122: Javascript Tutorial - 4730-5

USING THE IMAGE OBJECT

The image object exists for any Web pagethat includes at least one image. Webpage elements such as images, forms,

applets, and links are included in an array andcan be referred to using an index that matchesits position in the Web page file.

For example, if a Web page has two images,you can refer to the first one asdocument.images[0] and the second oneas document.images[1]. Remember thatarray indexes always start at 0.

Using the index, you can find out informationabout the image, such as its border width, itsdimensions, its name, source, and spacingattributes. There aren’t any methods for theimage object, but you can change theproperties of the images dynamically.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING THE IMAGE OBJECT

USING THE IMAGE OBJECT

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Add an image to the Web page and set the alt and border attributes.

‹ Add document.write statements to display the image attribute values.

› Save the file as image.html.

ˇ Open the image.html file in a browser.

■ The image and its attribute values are displayed.

106

Page 123: Javascript Tutorial - 4730-5

USING OBJECTS

⁄ Open the file js-skeleton.html in Notepad.

¤ Add an <img/> tag to the Web page.

‹ Within the <script> tags, create a new image object.

› Assign the image object’s src property an image filename.

ˇ Add an onload event to the <body> tag that loads a new source image into the image object.

Á Save the file as image2.html.

‡ Load the image2.html file into a browser.

■ The image defined in the image object is displayed.

Note: By preloading the image, the browser caches a copy of it so that it can load quickly with the rest of the page.

107

7

Using a new image object, you canpreload an image into memory while thepage initially loads. After the image is

preloaded, JavaScript can reference the imageobject and display it immediately.

To create a new image object, you need tospecify an image name and use the newkeyword — for example, myImage =newImage().

After creating a new image object, you can setits attributes using the image object properties,such as myImage.src = “house.gif”,myImage.border = “20”, andmyImage.hspace = “10”.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

PRELOAD IMAGESPRELOAD IMAGES

PRELOAD IMAGES

Page 124: Javascript Tutorial - 4730-5

Many of the image object propertiesare the same as the attributes of the<img/> tag — such as border,

width, hspace, and src. When theseproperties are changed in a JavaScriptstatement, the image on the Web page ischanged dynamically. These properties enableyou to change an image’s attributesdynamically using JavaScript.

In addition to the image attributes, setting theimage’s src attribute to a new value canchange the actual image that is loaded in a

Web page. Before changing images, you shouldpreload the new image so that the image isimmediately available to be displayed (see thesection “Preload Images”).

For example, the first image on the Web pagecan be referenced as document.images[0],so if you set document.images[0].src toa new image, the image on the page willchange.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

CHANGE IMAGES

CHANGE IMAGES

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Add an image to the Web page.

‹ Add a simple form with a single button.

› Add the onclick event to the button.

ˇ Within the onclick event, set the image’s source property to another image file.

Á Save the file as changeImage.html.

‡ Open the changeImage.html file in a browser.

■ An image and a button appear.

108

Page 125: Javascript Tutorial - 4730-5

USING OBJECTS

° Click the Web page button.

■ The new image appears.

109

7

Another property of the image object is thecomplete property. This property is aBoolean value that is false until an image iscompletely loaded. When completely loaded,the complete property is set to true. Usingthis value, you can check to see if an image isloaded before changing it. For example, if youhave an image loaded that will change, youcan check the complete property beforeallowing the image to change. The JavaScriptstatements for checking whether an image isfully loaded look something like this:

function changeImage() {

if (document.images[0].complete)

document.images[0].src =“newImage.gif”;

}

Page 126: Javascript Tutorial - 4730-5

USING THE LINK AND ANCHOR OBJECTS

Just like the image object, the link andanchor objects are included in an array forreference using JavaScript. The order that

the link appears on the page is the index forthe array. Links and anchors are countedindependent of one another.

For example, if a page has two anchors andthree links, the first anchor is referenced asdocument.anchors[0] and the first linkwould be referenced asdocument.links[0].

The link object includes href and targetproperties that can be used to dynamically

change the link. The anchor object includes aname property that can dynamically changethe anchor name.

Other link properties are used to describethe link components. The host propertyincludes the domain name, the protocolproperty lists the protocol, such as http:, andthe pathname property lists the path of theURL in UNC (Uniform Naming Convention)format.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING THE LINK AND ANCHOR OBJECTS

USING THE LINK AND ANCHOR OBJECTS

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Add several links and anchors above the <script> tags.

‹ Within the <script> tags, add document.write statements to display the length of the links and anchors arrays.

› Save the file as links.html.

ˇ Open the links.html file in a browser.

■ The links and number of links are displayed.

110

Page 127: Javascript Tutorial - 4730-5

USING OBJECTS

Á Open the links.html file in Notepad.

‡ Add several document.write statements to display information about one of the links.

° Save the file as links2.html.

· Open the links2.html file in a browser.

■ The link information is displayed.

The anchor object doesn’t include all the sameproperties as the link object: The anchorobject includes only a single property — name.

111

7

Links can be decomposed into their variouscomponents by using the properties of thelink object. The protocol property lists theprotocol for the URL, which can be somethinglike http: or ftp:. The hostname propertyincludes the domain name, and the pathnameproperty includes the path to the Web file. Theport property lists the port value for the Webpage, and the host property includes thehostname and port values together. The finalpiece of a URL is the anchor name, which canbe obtained from the hash property. Acomplete URL can be generated from thefollowing:

myLink.protocol + myLink.hostname +myLink.pathname + myLink.port +myLink.hash

Page 128: Javascript Tutorial - 4730-5

CHANGE LINKS

Many objects contain all the variouselements on a Web page. For example,the link object holds all the links

included on the Web page.

Individual links can be located by specifying theindex value for the link. These index values arenumbered sequentially from the top of the pageto the bottom, starting at 0 for the first link.

The index value is specified within squarebrackets immediately after the link’s objectname. For example, the first link on the pagecan be referred to as document.links[0].

The link object shares many of the sameproperties as the location object, includinghost, hostname, href, pathname, port,and protocol.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

CHANGE LINKS

CHANGE LINKS

JAVASCRIPT

⁄ Open the js-skeleton.html file.

¤ Add a link to a Web page.

‹ Add a form with a single button.

› Add onclick to the button and set the event to change the href property of the link.

Note: Changing the href property in Step 4 is what actually changes the link.

ˇ Save the file as changeLink.html.

Á Open the changeLink.html file in a browser.

■ A single link and a button are displayed.

112

Page 129: Javascript Tutorial - 4730-5

USING OBJECTS

‡ Move the mouse cursor over the top of the link.

■ Notice the link URL displayed in the status bar at the bottom of the window.

° Click the button on the Web page.

· Move the mouse cursor over the top of the link again.

■ Notice that the link URL displayed in the status bar has changed.

Note: A good place to use this would be to send the user off to a random URL.

113

7

You can create a random link generator bycreating several links, placing them in anarray, and then randomly selecting a link andchanging a generic link with the random one.The code for this would look like this:

function randomLink() {

randomLink = new Array();

randomLink[0] =“www.animabets.com”;

randomLink[1] =“www.microsoft.com”;

randomLink[2] = “www.cnn.com”;

randNo =Math.floor(randomLink.length *Math.random());

document.links[0].href =randomLink[randNo];

}

In this example, I included the Math.floor()method because it rounds down to the closestinteger.

Page 130: Javascript Tutorial - 4730-5

The history object enables you toduplicate the browser’s Forward andBack buttons to move between viewed

Web pages.

You can use the history object’s lengthproperty to view the length of the currenthistory list saved by the browser.

The history object includes several methods.The back() method can cause the previouslyloaded Web page to appear in the browser.The forward() method displays the nextpage in the browser. (To go forward, the usermust have first gone back to previous pages.)

The go() method accepts a numberparameter, which can be positive or negative,and moves you forward or backward in theHistory list.

For example, the statement document.history.go(-2) displays the Web page thatis two pages back in the History list.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING THE HISTORY OBJECT

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a form with a single button.

‹ Add the onclick event to the button.

› Set the onclick event to move back two pages in the history list.

ˇ Save the file as history.html.

Á Open the history.html file in a browser.

‡ Click the arrow ( ) to the right of the Back button to view the history list.

114

USING THE HISTORY OBJECTUSING THE HISTORY OBJECT

Page 131: Javascript Tutorial - 4730-5

USING OBJECTS

■ The history list is displayed in a drop-down list.

° Click anywhere in the browser window to make the list disappear.

· Click the button. ■ The Web page back two places is loaded in the browser.

The history.go() method can be used toreload the current page. If the index is set to 0,then the current page is the one in the historylist that is loaded. This has the same effect as apage refresh. The code looks like this:

document.history(0);

You can set the number of places to go backin the history list using a user-inputted valuefrom a form element such as a selection listor a text field. The code to do this would looklike this:

document.history(document.form1.text1.value);

You can prevent a user from going back with theBack button by using thewindow.location.replace() method. Thismethod enables you to replace the currenthistory list entry with a URL that is passed as aparameter.

115

7

Page 132: Javascript Tutorial - 4730-5

JAVASCRIPT

116116116

USING THE WINDOW ANDDOCUMENT OBJECTS

JavaScript includes two parent objects thatare used to control the appearance and lookof a browser window. These two objects are

the window and document objects.

The window object is the top-level parent forall objects and includes the document,location, and history objects as sub-objects. window also includes properties andmethods for controlling the external look of abrowser window. I describe several of these inthis chapter, but you can find many morethroughout the remaining chapters.

The document object allows access to thevarious HTML elements that make up a Webpage. One of the document object methods iswrite(), which is used to output text andHTML to the browser window.

For example, the JavaScript statementdocument.write(‘<b>hello</b>‘,name) prints the word hello in bold letters inthe browser followed by the value of theJavaScript variable name.

USING THE WINDOW ANDDOCUMENT OBJECTS

USING THE WINDOW AND DOCUMENT OBJECTS

⁄ Open the CD file js-skeleton.html in Notepad.

¤ Add several document.write() statements.

‹ Within the parentheses of the document.write()

statements, add HTML code within single quote marks.

Note: You can find specifics on HTML in Appendix A, or for more comprehensive coverage try Teach Yourself Visually HTML.

› Save the file as write.html.

ˇ Open the write.html file in a browser.

■ The HTML code is displayed within the browser.

Page 133: Javascript Tutorial - 4730-5

WORKING WITH WINDOWS 8

In addition to the document.write()method which has already been used andexplained, JavaScript includes another similarmethod, document.writeln(). This methodalso displays the passed parameter in thebrowser window, except it includes a newline character at the end of the line. Forexample, the statements

document.writeln(“Hello “);

document.writeln(“and welcome “);

document.writeln(“to my page.”);

include a new line character at the end ofeach line. Because the browser interprets thetext as HTML, the new line characters areinterpreted as white space, causing the text torun together.

117

ADD A VARIABLE

Á Open the write.html file in Notepad.

‡ Add a variable definition and set it equal to a value.

° Beneath the variable definition, add another document.write() statement to display the variable value.

· Save the file as write2.html.

‚ Open the write2.html file in a browser.

■ The text along with the variable value is displayed.

If the statement is written with the windowobject in front of it, it will still work fine. Forexample, window.document.write() worksthe same as document.write().

Page 134: Javascript Tutorial - 4730-5

JAVASCRIPT

118118118

DISPLAY TEXT ON A BROWSER’SSTATUS BAR

The browser window status bar is the spaceat the bottom of the window between thedocument and the edge of the window.

This area is used to display useful informationto the user, such as the link address when themouse cursor is moved over a link.

Using the window.status property, you canset the text that is displayed in the status bar.To do this, you simply need to set thewindow.status property equal to a line oftext. This text can also include JavaScriptstatements.

For example, the statementwindow.status=”hello and welcome”displays “hello and welcome” in the status barof the current window.

If window.status is used to display text inthe status bar and then the mouse cursor ismoved over a link, the text displays the link’slocation.

This example uses the skeleton.html filefound on the book’s CD-ROM, but you canapply these steps to any file.

DISPLAY TEXT ON A BROWSER’SSTATUS BAR

DISPLAY TEXT ON A BROWSER’S STATUS BAR

118

⁄ Open the skeleton.html file.

¤ Add the onload event to the opening <body> tag.

‹ Set the onload event equal to window.status= and the text to display.

› Save the file as status.html.

ˇ Open the status.html file in a browser.

■ The line of text is displayed on the status bar.

Page 135: Javascript Tutorial - 4730-5

WORKING WITH WINDOWS 8

Á Open the status.html file in Notepad.

‡ Add a link to a Web page.

° Save the file as status2.html.

· Open the status2.html file in a browser.

‚ Move the mouse cursor over the top of the link text.

■ The status bar text is replaced with the link reference.

Note: Link addresses are displayed by the browser by default and cannot be overwritten with other text.

119

If the text string displayed in the browser statusbar is longer than the browser window, thebrowser truncates and displays as much of thetext string that it can.

The text on the status bar can be changed inresponse to an event using the window.statusproperty, but you can also set the default text thatshould appear on the status bar when no eventsare detected using the window.defaultStatusproperty. For example, setting

window.defaultStatus = “Processing”

displays “Processing” as the default text thatappears anytime no events are happening.

Page 136: Javascript Tutorial - 4730-5

JAVASCRIPT

120

CHANGE BACKGROUND COLORS

The background color can be set using thebgcolor attribute of the <body> tag instandard HTML, but JavaScript enables

you to dynamically change the backgroundcolor.

The document.bgColor object propertyholds the current color of the background, or ifyou assign this object a color, you can set thebackground color.

For example, if you set the document.bgColor property to blue, the backgroundcolor becomes blue when the document isdisplayed.

Color values can be either browser-recognized color names like red, blue, or orange, or colors can be represented asRGB hexadecimal numbers. RGB hexadecimalnumbers include the number sign (#) followedby the hexadecimal values of red, green, andblue ranging from 00 to FF.

For example, red is represented as #FF0000,blue is #0000FF, and purple is #FF00FF.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

CHANGE BACKGROUND COLORS

CHANGE BACKGROUND COLORS

⁄ Open the js-skeleton.html file.

¤ Add the document.bgColor property and set it to a color name.

‹ Save the file as bgColor.html.

› Open the bgColor.html file in a browser.

■ The Web page background color is set.

Page 137: Javascript Tutorial - 4730-5

⁄ Open the js-skeleton.html file.

¤ Add the bgcolor attribute to the <body> tag and set it equal to a color.

‹ Add a document.write statement within the <script> tags that displays the document.bgColor property value.

› Save the file as bgColor2.html.

ˇ Open the bgColor2.html file in a browser.

■ The background color value is displayed.

121

WORKING WITH WINDOWS 8

LIST THE BACKGROUND COLOR

JavaScript is case-sensitive. That means thatthe exact capitalization needs to be used,including the C in bgColor. If you were touse the document.bgcolor property with alowercase c, the browser would return anobject not recognized error. This can bea tricky error to debug, especially becauseHTML is not case-sensitive.

A statement like

document.bgColor = “#80FFCC”

sets the background color when this statementis executed, but you can change the backgroundcolor at any time using an event. For example,

onclick = “document.bgColor =document.form1.text1.value”

dynamically sets the background color to thevalue taken from a text field whenever the eventis triggered.

Page 138: Javascript Tutorial - 4730-5

JAVASCRIPT

122122

CHANGE TEXT AND LINK COLORS

The document object also includesproperties for setting the foreground textcolor and the link colors. In HTML, you

can set these colors using the text, link,alink, and vlink attributes of the <body>tag. Using JavaScript, however, you candynamically change these colors as the userinteracts with the page.

The object property for the foreground textcolor is document.fgColor. This propertysets the color of the text for the Web page.Care should be taken to ensure that this coloris different from the background color;otherwise, the text will not be readable.

The object property for the link color isdocument.linkColor. This sets the color ofthe links whether applied to text or images. Youcan also set the active link color and the visitedlink color with document.alinkColor anddocument.vlinkColor, respectively.

This example uses the bgColor.html filefound on the book’s CD-ROM (or which youmay have created in the section “ChangeBackground Colors”), but you can apply thesesteps to any file.

CHANGE TEXT AND LINK COLORS

SET THE FOREGROUND COLOR

⁄ Open the bgColor.html file.

¤ Add the document.fgColor object property and set it to a different color than the background color.

‹ Add some text to the page.

› Save the file as fgColor.html.

ˇ Open the fgColor.html file in a browser.

■ The background and foreground colors are displayed.

Page 139: Javascript Tutorial - 4730-5

⁄ Open the fgColor.html file in Notepad.

¤ Add the document.linkColor object property and set it to a different color than the background and foreground colors.

‹ Add a link to the page.

› Save the file as linkColor.html.

ˇ Open the linkColor.html file in a browser.

■ The link is displayed using the specified color.

123

WORKING WITH WINDOWS 8

SET THE LINK COLOR

A color management function could be writtenlike this:

function colors(background, textCol,linkCol, vlinkCol) {

document.bgColor = background;

document.fgColor = textCol;

document.linkColor = linkCol;

document.vlinkColor = vlinkCol;

}

Calling this function with specified colors setsthe color scheme for the Web page. Forexample, the statement colors(“black”,“red”, “orange”, “purple”) sets the colors.

The document.fgColor property holds thevalue of the text color. This property can beused to display the current text color or to setthe current text color with a statement like

document.fgColor = “#80FFCC”

You can also dynamically set the text and linkcolors using the value from a form text field.For example,

onclick = “document.fgColor =document.form1.text1.value”

dynamically sets the text color to the valuetaken from a text field. Because this statementis executed as part of an event, the user couldinput a different color value in the text fieldand trigger the onclick event to update thetext color.

Page 140: Javascript Tutorial - 4730-5

124124

The document title appears in the title barfor the current window. It is typically setusing the <title> tag, which appears

within a Web page’s <head> tags. JavaScriptincludes a document object property that letsyou control the title more than you can using<title> tags: document.title.

The document.title property holds thecurrent document title, or it can be set to a newvalue that appears when the page is loaded.

For example, to set the title of a document to“Welcome to Joe’s,” you could set a namevariable equal to Joe’s and then set the

document.title property equal to“Welcome to “ + name, which woulddynamically generate the title for the currentdocument.

The document title is different from thewindow name. Each Web page can have a titlethat appears in the window title bar. Eachwindow can have a name, which is used byJavaScript to identify the window. The windowname isn’t displayed within the browser and ismainly used internally.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

CHANGE THE DOCUMENT TITLE

⁄ Open the js-skeleton.html file.

¤ Add a variable and assign it a string.

‹ Set the document’s title using the document.title property.

› Use a document.write statement to display the title value.

ˇ Save the file as title.html.

Á Open the title.html file in a browser.

■ The document title appearing in the title bar is displayed as specified.

JAVASCRIPT

CHANGE THE DOCUMENT TITLECHANGE THE DOCUMENT TITLE

Page 141: Javascript Tutorial - 4730-5

125

⁄ Open the js-skeleton.html file.

¤ Use a document.write statement to display the modification date using the document.lastModified property.

‹ Save the file as lastModified.html.

› Open the lastModified.html file in a browser.

■ The date of the last modification is displayed.

It can be very useful for users and publishersto use JavaScript to display the date that thecurrent page was last updated. If this

information is included on the Web page,then you can immediately tell how current thepage is.

The document.lastModified propertydisplays the date when the document was lastmodified.

The format of the modification date includesthe month, date, and year along with the time.In Chapter 10, the Date object is covered inmore detail.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

DISPLAY THE MODIFICATION DATE

The document object includes two additionalproperties that are very useful. Thedocument.URL property holds a string of thecurrent URL. This can be useful for displayingthe current URL for printing. Another usefulproperty is document.referrer, whichdisplays the URL of the document thatcontains the link that led to the current page.This is different than the history, which holdsthe previously visited page.

WORKING WITH WINDOWS 8

DISPLAY THE MODIFICATION DATEDISPLAY THE MODIFICATION DATE

Page 142: Javascript Tutorial - 4730-5

JAVASCRIPT

126126126126126

VIEW THE URL OF THECURRENT DOCUMENT

Auseful piece of information that you canplace at the bottom of every Web page isthe current URL. One of the benefits of

including the URL with the page is that theaddress of the Web page is displayed if theWeb page is printed.

The property that holds the Web page addressis part of the document object. This propertyis URL. Adding this property to the bottom of aWeb page can be accomplished with thestatement document.URL. This property is a

read-only property; you cannot use URL tochange the URL for the current Web page.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

VIEW THE URL OF THECURRENT DOCUMENT

126

When the URL is displayed in the browserusing the document.URL statement, it is URLencoded. This is done so that any spaces orspecial symbols won’t cause a problem. URLencoding can be undone with the unescape()statement covered in Chapter 14.

VIEW THE CURRENT URL

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a document.write() statement to display the current URL.

‹ Save the file as URL.html.

› Open the URL.html file in a browser.

■ The URL for the current Web page is displayed.

Page 143: Javascript Tutorial - 4730-5

127

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a document.write() statement to display the referring URL.

‹ Save the file as referrer.html.

› Open another HTML file.

ˇ Add a link to the referrer.html page.

Á Save the Web page as reflink.html.

‡ Open the reflink.html file in a browser.

° Click on the link.

■ The referrer.html page loads.

■ The referring Web page (reflink.html) is displayed.

When two Web pages are linked togetherand one page loads the other page, thefirst page is called the referring page

because it referred the second page.

The document object includes a property thatcan be used to view the referring Web page —referrer. This property displays the referringURL, which will be URL encoded.

Using document.referrer, you candetermine the link that was used to send theuser to your Web page.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

VIEW THE REFERRING URL

The document.referrer property can haveproblems in the Internet Explorer browser ondifferent operating systems. Depending onyour configuration, the property may show younothing or the URL of the current Web page.

WORKING WITH WINDOWS 8

VIEW THE REFERRING PAGEVIEW THE REFERRING PAGE

Page 144: Javascript Tutorial - 4730-5

JAVASCRIPT

128

OPEN A NEW BROWSER WINDOW

Have you ever noticed while browsingthe Web that some links spawn a newbrowser window? This technique can

be accomplished in JavaScript by using thewindow.open() method.

The window.open() method can accept threeparameters. The first parameter is the URL toopen in the new window. The second parameteris the name of the new window. This name canthen be used to reference the new window andis different from the document’s title.

The third parameter defines the features of thewindow, for which you can set the followingattributes: width, height, toolbar,

status, menubar, scrollbars, andresizable. All but the first two of theseattributes can be set to either yes or no.

For example, the JavaScript statement window.open(“mypage.html”, “mywindow”,“width=200, height=400, toolbar=no,status=no, resizeable=yes”); opens anew 200-x-400-pixel resizable window with notoolbar or status bar and loads the mypage.htmlfile in it.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

OPEN A NEW BROWSER WINDOW

OPEN A NEW BROWSER WINDOW

⁄ Open the Notepad file.

¤ Within the <script> tags, add the window.open() statement.

‹ Within the parentheses, add in quotation marks the URL of the page to open and a name for the new window.

› Also within the parentheses, add and set the width, height, and resizable attributes.

ˇ Save the file as open.html.

Á Open the open.html file in a browser.

■ The Web page is displayed.

Page 145: Javascript Tutorial - 4730-5

WORKING WITH WINDOWS 8

■ The new window is also opened with the specified dimensions and displays the referenced Web page.

■ If you set resizable to yes, you can click and drag one of the corners or sides of the new window to resize it.

From the original Web page, you can writetext to the new window. When you create anew window, one of the parameters is to givethe new window a name. This name can beused to send output to the new window. Forexample, the document.write() functionwrites output to the current Web page, andmywindow.write() writes text to a newwindow named mywindow.

The JavaScript property that holds thewindow’s name is window.name. You can alsouse the window.opener property to retrievethe name of the window that spawned a newwindow. The current window can also beaccessed using the window.self property.

129

Page 146: Javascript Tutorial - 4730-5

JAVASCRIPT

130

CLOSE A REMOTE WINDOW

If many browser windows are opened, thenthe screen can become very cluttered. Youcan always close a window by clicking the

Close button (X) in the upper-right corner ofthe window, but JavaScript also includes amethod for closing remote windows.

To close a remote window, you can use thewindow.close() function. This closes thecurrent remote window.

If the window.close() function is used toclose the original browser window, an alertdialog box will appear, asking if you wish toclose the browser window. Windows that havebeen opened using the window.open()function automatically close without aconfirmation dialog box.

This example uses the write.html and open.html files found on the book’s CD-ROM, butyou can apply these steps to any file.

CLOSE A REMOTE WINDOW

CLOSE A REMOTE WINDOW

⁄ Open the file write.html in Notepad.

¤ Add a set of <form> tags under the <script> tags.

‹ Create a button within the form using an <input/> tag.

› Add the onclick event to the <input/> tag and set it to window.close().

ˇ Save the file as close.html.

Á Open the open.html file in Notepad.

‡ Change the URL for the new window to close.html.

° Save the file as open2.html.

Page 147: Javascript Tutorial - 4730-5

· Open the open2.html file in a browser.

■ The Web page and a new window are opened and displayed.

‚ Click the Close button in the remote window.

■ The remote window closes, but the window that opened it originally remains.

With several windows open, you can switchthe focus between the different windowsusing the window.focus() method. You canalso force a window to lose focus with thewindow.blur() method. You can tell whichwindow has focus by looking at the title bar.The title bar of the window that has focusappears a different color than the otherwindows. You can change the window thathas focus by clicking in the window with themouse. You can also switch the focusbetween the different windows using theAlt+Tab keys.

In the example in this section, you add a Closebutton to the remote window. If you add aClose button to the original window, thedifference is that closing the original windowwill end your session and a dialog box askingyou to confirm the command will appear.

131

WORKING WITH WINDOWS 8

Page 148: Javascript Tutorial - 4730-5

JAVASCRIPT

132

PRINT A WINDOW

Web browsers include a button on themain toolbar that enables you to printthe current Web page. This same

feature can also be made accessible usingJavaScript.

The method that enables the user to print thecurrent Web page is window.print(). Thismethod opens the Print dialog box, which letsyou select the printer, number of copies, andother print options.

If a printer isn’t connected to the currentcomputer, the window.print() method isignored.

When a new window is opened using thewindow.open() method, one of the methodparameters can set the toolbar to be hidden onthe new window. If the toolbar isn’t visible,then the Print button will also not be available.For this case, you can add a print feature to aWeb page using the window.print()method.

This example uses the close.html file foundon the book’s CD-ROM (or which you mayhave created in the section “Close a RemoteWindow”), but you can apply these steps toany file.

PRINT A WINDOW

PRINT A WINDOW

⁄ Open the close.html file.

¤ Copy the <input/> tag to create another button for the Web page.

‹ Change the button value to Print and the event statement to window.print().

› Save the file as print.html.

ˇ Open the print.html file in a browser.

■ A button that enables printing appears on the Web page.

Á Click the Print button on the Web page.

Page 149: Javascript Tutorial - 4730-5

■ The Print dialog box appears.

‡ Select a printer and the print options.

° Click the OK button. ■ The page is printed.

The window.print() button produces thesame results as the browser’s Print buttonincluded on the toolbar. In addition to thismethod, JavaScript includes several othermethods that match toolbar features. Thesemethods include the window.back() andwindow.forward() methods, which do thesame thing as the toolbar’s Back and Forwardbuttons. JavaScript also includes a window.home() method that loads the browser’s homepage just like the Home button on the toolbar.The function of the Stop button can also beincluded within a Web page by using thewindow.stop() method.

If you create a button using window.print()and click the button, if a printer isn’t connectedto your computer, then a dialog box will appearstating that you need to add a printer before youcan print.

133

WORKING WITH WINDOWS 8

Page 150: Javascript Tutorial - 4730-5

JAVASCRIPT

134

MOVE A WINDOW

The window object includes a couplemethods that can be used to move andreposition the current window.

The window.moveTo() method accepts twoparameters for specifying the distance in pixelsfrom the left edge and top of the screen wherethe upper-left corner of the browser should bemoved to. For example, the statementwindow.moveTo(200, 400) positions theupper-left corner of the browser 200 pixelsfrom the left edge of the screen and 400 pixelsfrom the top of the screen.

The window.moveBy() method also acceptstwo parameters that are used to specify the

horizontal and vertical number of pixels thebrowser should move. For example,window.moveBy(10, 50) moves thecurrent window to the right 10 pixels anddown 50 pixels every time it is executed.

The parameters can be positive or negativevalues. Negative values move the window to theleft and up rather than to the right and down.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

MOVE A WINDOW

USING WINDOW.MOVETO()

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a form with two text fields and a button.

‹ Add the onclick event to the button and set it equal to window.moveTo().

› Set the parameters of the window.moveTo() method to the value of the text fields.

ˇ Save the file as moveTo.html.

Á Open the moveTo.html file in a browser.

‡ Click the form button.

■ The entire window moves to the specified coordinates.

Page 151: Javascript Tutorial - 4730-5

⁄ Open the moveTo.html file in Notepad.

¤ Change the window.moveTo() method to the window.moveBy() method.

‹ Change the name of the button.

› Save the file as moveBy.html.

ˇ Open the moveBy.html file in a browser.

Á Click the form button.

■ The window moves the amount specified.

This function causes the window to move to theright and down 1 pixel for each time throughthe loop until the 100-pixel limit is reached.

135

WORKING WITH WINDOWS 8

USING WINDOW.MOVEBY()

One of the benefits of using JavaScript tomove a window is control. With severalwindows open, the window.moveTo andwindow.moveBy methods enable you toposition the newly opened window exactlywhere you want it. For example, if you open aremote window with links, you can move it tothe side of the main window.

Another useful technique that you can use isto dynamically update the x and y values ofthe window.moveBy() method to animate themovement of the window — for example:

function moveDiag() {

for (i=1;I<100;I++)

window.moveBy(i,i)

}

Page 152: Javascript Tutorial - 4730-5

JAVASCRIPT

136

RESIZE A WINDOW

The window object also includes a couplemethods that are similar to the movemethods that can be used to resize the

current window.

The window.resizeTo() method acceptstwo parameters for specifying the width andheight in pixels of the browser window. Forexample, the statement window.resizeTo(200, 400) resizes the browser window to awidth of 200 pixels and a height of 400 pixels.

The window.resizeBy() method increasesthe width and height of the current window.For example, window.resizeBy(10, 50)

increases the width of the window by 10 pixelsand increases the height of the window by 50pixels.

The parameters of the window.resizeBy()method can be negative values. Negativevalues decrease the window size.

This example uses the moveTo.html filefound on the book’s CD-ROM (or which youmay have created in the section “Move aWindow”), but you can apply these steps toany file.

RESIZE A WINDOW

USING WINDOW.RESIZETO()

⁄ Open the file moveTo.html in Notepad.

¤ Change the window.moveTo() method to window.resizeTo().

‹ Change the value of the text in the text boxes and the name of the button.

› Save the file as resizeTo.html.

ˇ Open the resizeTo.html file in a browser.

Á Click the form button.

■ The window is resized to the specified coordinates.

Page 153: Javascript Tutorial - 4730-5

⁄ Open the resizeTo.html file.

¤ Change the window.resizeTo() method to the window.resizeBy() method.

‹ Change the name of the button.

› Save the file as resizeBy.html.

ˇ Open the resizeBy.html file in a browser.

Á Click the form button.

■ The window is increased by the amount specified.

JavaScript includes two more methods that letyou control the window and are very similar tothe window.resizeTo() andwindow.resizeBy() methods. These methodsare window.scrollTo() and window.scrollBy(). These methods let you controlhow the page in the browser scrolls. Forexample, the statement window.scrollTo(10, 200) scrolls the window to the right 10pixels and down 200 pixels. These methodsonly work if the Web page is large enough toneed scrolling.

If the browser is maximized by using theMaximize button in the upper-right corner ofthe browser window, then the resizeBy()method will not have any effect.

137

WORKING WITH WINDOWS 8

USING WINDOW.RESIZEBY()

Page 154: Javascript Tutorial - 4730-5

JAVASCRIPT

138

INFORM THE USER WITH AN ALERTDIALOG BOX

The window object contains severalmethods that can be used to interactdirectly with the user. These methods make

it possible to present dialog boxes to the user.

Many programs use dialog boxes to presentinformation to the user. Dialog boxes can alsobe used to collect information from the user.

JavaScript includes three different types of dialogboxes: alert, prompt, and confirm. All thesedialog boxes are window object methods.

The simplest dialog box is an alert dialog box.This dialog box presents a text message to theuser and includes a single OK button. Themessage is defined in quotation marks as aparameter of the alert() method.

For example, the statement window.alert(“Hello”) creates a dialog box with theword Hello in it.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

INFORM THE USER WITH AN ALERTDIALOG BOX

INFORM THE USER WITH AN ALERT DIALOG BOX

⁄ Open the file js-skeleton.html in Notepad.

¤ Within the <script> tags, add the window.alert() method to display a message.

‹ Save the file as alert.html.

› Open the alert.html file in a browser.

■ An alert dialog box appears with the message in it.

ˇ Click the OK button.

Page 155: Javascript Tutorial - 4730-5

Á Open the file js-skeleton.html in Notepad.

‡ Within the <body> tags, add an onload event.

° Set the onload event equal to the window.alert() method to display a message.

· Save the file as alert2.html.

‚ Open the alert2.html file in a browser.

■ An alert dialog box appears with the message in it.

— Click the OK button.

Note: Alert dialog boxes can be opened by placing the window.alert statement within the <script> tags or within an event.

139

WORKING WITH WINDOWS 8

Alert dialog boxes can be used for debuggingpurposes. For example, consider the followingfunction for checking variables:

function checkVariable(varName, var1) {

window.alert(“The value of “ +varName + “ is “ + var1);

}

You can call this function using a function thatlooks like this:

checkVariable(“blink”, blink);

Whenever this function is called, an alert dialogbox appears with the variable name and its valuedisplayed. This can be very beneficial as youbuild your scripts. Once the script is complete,you can simply remove the function and all itsrelated calls.

Page 156: Javascript Tutorial - 4730-5

JAVASCRIPT

140

ACCEPT INPUT WITH A PROMPTDIALOG BOX

The alert dialog box works well if you wantto display a message to the user, but itdoesn’t let the user input information into

the script. A prompt dialog box, however,enables users to enter text into a text field.

The window object includes a method forcreating a prompt dialog box. This dialog boxincludes an OK button, a Cancel button, and atext field where the user can enter information.

Prompt dialog boxes are created using theprompt() method. This method can accept

two parameters. The first parameter definesthe message text that is displayed in the dialogbox. The second parameter is used to definethe default text that appears within the textfield. If the OK button is clicked withoutchanging the text in the text field, then thisdefault text is passed to the script.

When the OK button is clicked, the text in thetext field of the prompt dialog box is returnedto the script. You can capture this text if youassign the prompt() method to a variable.

ACCEPT INPUT WITH A PROMPTDIALOG BOX

ACCEPT INPUT WITH A PROMPT DIALOG BOX

⁄ Open the CD file js-skeleton.html in Notepad.

¤ Within the <script> tags, declare a variable and set it equal to the results of the window.prompt() method.

‹ Add several document.write() methods to display the variable’s value.

› Save the file as prompt.html.

ˇ Open the prompt.html file in a browser.

■ A prompt dialog box appears with a message in it.

Page 157: Javascript Tutorial - 4730-5

Á Type a name in the text field.

‡ Click the OK button. ■ The personalized page is displayed.

If you don’t want to include a default textfield message that appears when the dialogbox is displayed, then you can simply set thesecond parameter to the prompt() method toan empty string (“”). If you don’t include thesecond parameter, the text <undefined> isdisplayed as the default text in the text fieldof the prompt dialog box.

The prompt dialog box includes an OK buttonand a Cancel button. If the OK button isclicked, the value within the text field of theprompt dialog is returned to the script.However, if the Cancel button is clicked, anull value is returned to the script. You checkfor a null value using the if(window.prompt(“Input a value”,”10”)!= null) statement.

141

WORKING WITH WINDOWS 8

Page 158: Javascript Tutorial - 4730-5

JAVASCRIPT

142

ENABLE USER DECISIONS WITH ACONFIRM DIALOG BOX

The prompt dialog box lets you input a lineof text to the script, but another type ofdialog box — confirm — enables you to

ask the user questions.

The confirm dialog box is also part of thewindow object. This dialog box includes bothOK and Cancel buttons and can be used toenable the user to respond to questions.

Confirm dialog boxes are created using theconfirm() method. The confirm() methodcan accept only a single parameter that is usedto display the message within the dialog box.

The confirm() method returns a value oftrue if the OK button is clicked or false ifthe Cancel button is clicked. By setting avariable equal to the window.confirm()method, you can capture the user’s responseto the confirm dialog box.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

ENABLE USER DECISIONS WITH ACONFIRM DIALOG BOX

ENABLE USER DECISIONS WITH A CONFIRM DIALOG BOX

⁄ Open the file js-skeleton.html in Notepad.

¤ Declare a variable and set it equal to the results of the window.confirm() method.

‹ Add an if-else statement that checks the value of the confirm dialog box and displays appropriate text.

› Save the file as confirm.html.

ˇ Open the confirm.html file in a browser.

■ A confirm dialog box appears with a question in it.

Á Click the OK button.

Page 159: Javascript Tutorial - 4730-5

■ A positive message is displayed.

‡ Click Refresh to reload the Web page.

° Click the Cancel button. ■ A different message is displayed.

When this reset button is clicked, theconfirmReset() function is called and aconfirm dialog box is displayed. If the user clicksOK, the page form is reset. If the Cancel buttonis clicked, the form is not reset.

143

WORKING WITH WINDOWS 8

One place that the confirm dialog box can beused is to double-check with the user beforean action is taken. For instance, Web pageforms typically have a Reset button that resetsall the form elements to their default values.A function can be created that enables theuser to confirm the Reset action:

function confirmReset() {

check = window.confirm(“Are yousure you want to reset this form?”);

if (check)

document.form1.reset1.click();

}

<form name=”form1”>

<input type=”reset” name=”reset1”onclick=”confirmReset()”>

</form>

Page 160: Javascript Tutorial - 4730-5

JAVASCRIPT

144

The string object includes properties andmethods that let you work with text.

The string object has a single property —length — which returns the number of charactersin the string. This information is valuable as youwork with strings because it lets you know howmany characters are in the string. The stringobject also has numerous methods that can beapplied to text. A number of these methods can beused to format the text with HTML tags. Forexample, the bold() method returns a string oftext surrounded by opening and closing <bold>tags. Other string-formatting methods includebig(), fontColor(color), fontSize(size),

italics(), link(href), small(), strike(),sub(), sup(), toLowerCase(), andtoUpperCase(). See the section “Format StringVariables” later in this chapter for an example ofusing these methods.

Other methods enable you to combine, locate, andextract portions of text. These methods includecharAt(index), concat(text),replace(text1, text2), andsubstring(index1, index2).

This example uses the js-skeleton.html filefound on the book’s CD-ROM, but you can applythese steps to any file.

⁄ Open the file js-skeleton.html in Notepad.

¤ Create a string variable and assign it a value.

‹ Use a document.write() statement to display the value of the string.

› Add a document.write() statement to display the string formatted with the bold() method.

ˇ Save the file as string.html.

Á Open the string.html file in a browser.

■ The string is displayed normally and in bold.

FORMAT TEXT

USING THE STRING OBJECTUSING THE STRING OBJECT

Page 161: Javascript Tutorial - 4730-5

WORKING WITH STRINGS

145

⁄ Open the string.html file in Notepad.

¤ Add a document.write() statement to display the string converted to uppercase.

‹ Save the file as string2.html.

› Open the string2.html file in a browser.

■ The string is displayed in uppercase.

Single-quote marks can be used in place ofdouble-quote marks. In some places, youmay want to use a set of each. For example,if you specify a document.writestatement within an event, the quotes for thedocument.write statement need to bedifferent from the event quotes.

string objects by default are createdwhenever a string variable is declared.Strings are assigned to any variable that hasa pair of quotes in the definition. You canalso create string objects using the newkeyword, but it is not necessary. To do this,you need to list a name for the string and setit equal to new String(). For example,the JavaScript statement string1 = newString(); creates a new string object, andstring1.bold(); calls the bold()method for that string.

CHANGE TEXT CASE

9

Page 162: Javascript Tutorial - 4730-5

Asubstring is a portion of a string. Toextract a section of a string, you can usethe substring() method.

The substring() method accepts twoparameters, which correspond to the first andlast characters to extract from the base string.

For example, if a string is defined as str1 =“useful handbook”, the statementstr1.substring(0,10) equals the string“useful hand”.

JavaScript includes another useful substringmethod, substr(), which also accepts two

parameters. The first parameter marks thebeginning of the substring, and the secondparameter marks the length to extract.

For example, if a string is defined as str2 =“boring dialogue”, the statementstr2.substr(7,4) would result in“dial”. Remember that spaces count ascharacters and the string index starts with 0.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

JAVASCRIPT

146

⁄ Open the file js-skeleton.html in Notepad.

¤ Create a string variable and assign it a value.

‹ Use a document.write() statement to display the value of the string.

› Add a document.write() statement to display the substring created with the substring() method.

ˇ Save the file as substring.html.

Á Open the substring.html file in a browser.

■ The string and its substring are displayed.

Note: The substring started at the first position, as specified by the first parameter, 0, and ended at string index 13 (a space), as specified by the second parameter.

WORK WITH SUBSTRINGS

WORK WITH SUBSTRINGSWORK WITH SUBSTRINGS

Page 163: Javascript Tutorial - 4730-5

‡ Open the file substring.html in Notepad.

° Add a document.write() statement to display another substring created with the substr() method.

· Save the file as substring2.html.

‚ Open the substring2.html file in a browser.

■ The string and two substrings are displayed.

Note: The substring started at the position specified by the first parameter, string index 20, and continued for the length specified by the second parameter — 11 characters.

JavaScript includes another method thatworks just like the substring() methodwith an additional feature. The slice()method works on strings the same way that itworks on arrays. It accepts two parameters.The first parameter is the starting index valuewhere the string should be sliced. The secondvalue is the ending index where the sliceshould end. The difference between thismethod and the substring() method isthat the second parameter can be a negativevalue. Negative values are counted from theend of the string backwards. For example, astring is defined as str1 = “out tolunch” before the statementstr1.slice(3, -2) returns the substring“to lun”.

147

WORKING WITH STRINGS 9

Page 164: Javascript Tutorial - 4730-5

The substring() and substr()methods are used to break strings apart,but JavaScript includes another method

that is used to combine (concatenate) strings.

The concat() method tacks a second stringonto the end of the first. The second string thatis attached is identified as a parameter to theconcat() method.

For example, if a string is defined as str1 =“Thanks for the “, and another string isdefined as str2 = “work well done.”,these two strings can be combined with thestatement str1.concat(str2).

Another easy way to combine strings is withthe addition assignment (+=) operator. Thisoperator is used a lot in earlier examples andsimply needs to be placed between two stringsto add the second string to the first one.

For example, str1 and str2 can also becombined using the statement str1 +=str2.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

JAVASCRIPT

148148

⁄ Open the file js-skeleton.html in Notepad.

¤ Create two string variables and assign them values.

‹ Use document.write() statements to display the values of both strings.

› Add a document.write() statement to display the strings combined with the concat() method.

ˇ Save the file as concat.html.

Á Open the concat.html file in a browser.

■ The strings are displayed separate and combined.

CONCATENATE STRINGS

CONCATENATE STRINGSCONCATENATE STRINGS

Page 165: Javascript Tutorial - 4730-5

⁄ Open the file concat.html in Notepad.

¤ Add a document.write() statement to display the string combined with the + operator.

‹ Save the file as concat2.html.

› Open the concat2.html file in a browser.

■ The second combined string is now displayed.

Note: There isn’t an advantage to using the concat() method over the addition assignment operator.

This statement displays the quote marks aroundthe quoted word. Other escape charactersinclude the single quote (\’), the backslash(\\), the backspace (\b), the tab (\t), the newline (\n), the carriage return (\r), and a formfeed (\f).

For example, str2 = “The file islocated in the C:\\temp\\testdirectory.”; correctly displays thebackspace characters.

149

WORKING WITH STRINGS 9

USING THE ADDITION ASSIGNMENT OPERATOR

Strings are enclosed within quote marks, sohow do you display a quote mark? Anycharacter that cannot be printed by includingit within the string quotes is called an escapedcharacter. When working with strings, youcan include special escape characters such asthe quote mark if it is preceded by abackslash (\). For example, to include quotesaround a word in a string, use the backslashcharacter like this:

str1 = “He responded, \”Hooray\”when he was finished.”

Page 166: Javascript Tutorial - 4730-5

JavaScript could be used to create functionsthat would format strings using HTML tags,but many of the basic formatting options are

already available as methods of the stringobject.

These string-formatting methods simply addthe correct formatting tags on the beginningand end of the string. For example, for thestring str1 = “Little John”, thestatement str1.big() equals <big>LittleJohn</big>.

Other string-formatting methods includebig(), bold(), italics(), small(),strike(), sub(), and sup(). The sub()

and sup() methods are used to format stringcharacters as subscripts or superscripts.

You can also change the font size using thefontsize() method, which accepts a sizeparameter. The size parameter can be aninteger between 1 and 7, with 7 being thelargest. The font color can be set with thefontcolor() method, which accepts a colorparameter including a color name or ahexadecimal color value.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Create a string variable and give it a value.

‹ Use a document.write() statement to display the value of the string.

› Add several document.write() statements to display the string with different formats, using some of the string-formatting methods.

ˇ Save the file as format.html.

Á Open the file format.html in a browser.

■ The string is displayed normally and with formatting.

150

FORMAT STRING VARIABLES

FORMAT STRING VARIABLESFORMAT STRING VARIABLES

Page 167: Javascript Tutorial - 4730-5

‡ Open the file format.html in Notepad.

° Add a document.write() statement to display the string with a different font size and color.

· Save the file as format2.html.

‚ Open the format2.html file in a browser.

■ The string is displayed with a different font size and color.

151

WORKING WITH STRINGS 9

If an entire string is formatted using thesub() or sup() methods, it is difficult tonotice how the string looks any different froma normal string unless it can be compared toanother string on the page. A morereasonable way to use the sub() method isto build a string:

water = “H” + “2”.sub() + “O”;

This statement creates a string variablenamed water that includes an H and thestring for 2 that is returned from the sub()method and an O. The resulting stringdisplays the number as a subscript to theletter H. An example of the sup() methodwould be

squared = “x” + “2”.sup();

Page 168: Javascript Tutorial - 4730-5

Any defined string object can bechanged into an anchor or a link usingthe anchor() and link() methods of

the string object.

The anchor() method accepts a nameparameter that is used to specify the name ofthe anchor. The link() method accepts anhref parameter that defines where the linkpoints.

For example, if you define a string using thestatement str1 = “This is thestart”, you can change this string into ananchor with the name “start” by using the

following statement:str1.anchor(“start”).

An example of the link() method would beas follows. Given the string str2 = “funfor kids”, the following statement convertsthis string into a link:str2.link(“www.animabets.com”).

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Create string variables and assign each a value.

‹ Use for and document.write() statements to display the strings’ values.

› Create a couple anchors and links by using the anchor() and link() methods. Set the links to point to the anchors, including the number symbol (#) in front of them.

ˇ Save the file as link.html.

Á Open the link.html file in a browser.

■ The anchors and links are displayed.

152

BUILD ANCHORS AND LINKS

BUILD ANCHORS AND LINKSBUILD ANCHORS AND LINKS

Page 169: Javascript Tutorial - 4730-5

‡ Move the mouse over the first link.

■ Notice how the status bar reveals that the link points to the anchor name.

° Move the mouse over the second link.

■ Notice how the status bar reveals that the link points to the other anchor name.

The anchor() method can accept any stringor variable value to be used as the anchorname. The parameters to the link()method must be a valid URL or location.Using the link() method with an invalidURL does not cause the script to error, butthe link will not be available when clicked.

If you use an anchor name within the link()method, a link will be established to the anchor.The anchor needs to include a number symbol(#) in front of the anchor name. The hrefparameter that is passed to the link() methodcan be either a relative URL or an absolute URL.Absolute URLs must include a protocol such ashttp.

153

WORKING WITH STRINGS 9

Page 170: Javascript Tutorial - 4730-5

The string object includes a singleproperty — length. This property isuseful because it can be used as part of a

for loop to look at each letter in a string.

For example, for the string defined as str1 =“hello”, the str1.length is equal to 5.

The length property counts all characterswithin the quotation marks including spacesand any HTML code.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Within the <script> tags, create a string variable and assign it a value.

‹ Use document.write() statements to display the string and the value of the length of the string.

› Save the file as length.html.

ˇ Open the length.html file in a browser.

■ The string and its length are displayed.

154

DETERMINE STRING LENGTH

Escaped characters such as \” or \t count asonly a single character when the lengthproperty is used.

DETERMINE STRING LENGTHDETERMINE STRING LENGTH

Page 171: Javascript Tutorial - 4730-5

CHANGE CASE

⁄ Open the file js-skeleton.html in Notepad.

¤ Within the <script> tags, create a string variable and assign it a value.

‹ Add document.write() statements to display the string as it appears initially and then converted to uppercase and lowercase.

› Save the file as case.html.

ˇ Open the case.html file in a browser.

■ The string is displayed in all lower- and uppercase.

It is common when validating forminput such as the value of a textfield, to use the toUpperCase()or toLowerCase() methodsbefore checking any data. Thisensures that the data isn’t case-sensitive. Case-sensitivity isimportant for some strings such aspasswords. If the server expectsthe password in all capitals or alllowercase, then you can force thestring to be either.

155

WORKING WITH STRINGS 9

If a string is inputted to your script in all lowercase (or alluppercase) letters, you can convert the string to alluppercase (or all lowercase) letters.

The toLowerCase() method can be used to convert astring to all lowercase letters. Remember that even initialcapitals (first letter of each word is capitalized) are changedto lowercase. The toUpperCase() method can be used toconvert a string to all capital letters.

This example uses the js-skeleton.html file found onthe book’s CD-ROM, but you can apply these steps to anyfile.

CHANGE CASE

CHANGE CASE

Page 172: Javascript Tutorial - 4730-5

Using JavaScript, you can search within astring for a section of text. Thiscapability is essential for being able to

parse through a string.

The string object method to accomplish astring search is search(). The parameter forthis method is the string for which you’researching. The method returns the index forthe position of the search string.

For example, if you have a string defined asstr1 = “Your name is mud.”, you canlocate the word mud with the followingstatement str1.search(“mud”). The

results of this last method are 13. Rememberthat the string index numbers always start with 0.

If the search string cannot be found within thestring, the method returns a value of -1.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Create a string variable and assign it a value.

‹ Use a document.write() statement to display the value of the string.

› Add another document.write() statement to display the index of a word in the string.

ˇ Save the file as search.html.

Á Open the search.html file in a browser.

■ The string and its index are displayed.

156

SEARCH WITHIN A STRING

SEARCH WITHIN A STRINGSEARCH WITHIN A STRING

Page 173: Javascript Tutorial - 4730-5

‡ Open the search.html file in Notepad.

° Change the parameter of the search() method to search for a string that doesn’t exist.

· Save the file as search2.html.

‚ Open the search2.html file in a browser.

■ The string index is returned as -1.

157

WORKING WITH STRINGS 9

When search features are added to a Webpage, you will want to validate the existenceof the string in the text before continuing withthe search. This validation can be done bychecking to see if the text exists using thesearch() method — for example:

functioncheckSearch(searchString, text) {

if (text.search(searchString)== -1)

document.write(“The searchstring doesn’t exist within thissection of text.”)

else {

searchIndex =text.search(searchString);

return searchIndex;

}

}

This function checks first to see if the searchstring exists in the section of text. If it doesn’texist, a message is displayed; if it does,however, the search is executed, and the indexis returned.

Page 174: Javascript Tutorial - 4730-5

LOCATE CHARACTERS IN A STRING

JavaScript includes some methods additionalto search() for precisely locatingcharacters and strings.

The indexOf() method, like the search()method, can be used to locate the firstoccurrence of a string, but you can also specifywhere the method begins looking. Rememberthat the first index value in a string starts with 0.

For example, if a string is defined as str1 =“I like spaghetti and meatballsand garlic bread”, you can find the first“and” string using the

str1.indexOf(“and”) statement. You canthen find the second “and” in the string byusing the statement str1.indexOf(“and”,20). This statement will start looking for the“and” string starting at the 20th character inthe string.

You can also search from the end of the stringusing the lastIndexOf() method. If youprovide a second parameter to this method, itsearches backward toward the beginning of thestring from the index specified in the secondparameter.

LOCATE CHARACTERS IN A STRING

JAVASCRIPT

⁄ Open the file js-skeleton.html from the CD-ROM in Notepad.

¤ Within the <script> tags, create a string variable and assign it a value.

‹ Use document.write() statements to display the value of the string and the index of the second ‘and’.

› Save the file as indexOf.html.

ˇ Open the indexOf.html file in a browser.

■ The string and the index of the second and are displayed.

158

USING THE INDEXOF() METHOD

Page 175: Javascript Tutorial - 4730-5

⁄ Open the file indexOf.html in Notepad.

¤ Use the lastIndexOf() method to display the index of the second and.

‹ Save the file as lastIndexOf.html.

› Open the lastIndexOf.html file in a browser.

■ The string and the index of the second and are displayed.

159

WORKING WITH STRINGS 9

USING THE LASTINDEXOF() METHOD

Using the indexOf() method, you can writea function to find all the occurrences of asearch string within a string. To do this, youcan use an if or while statement. Such afunction looks like this:

function findAll(searchString,text) {

num = 0;

index = 0;

pos = new Array();

while(text.indexOf(searchString) != -1) {

pos[num] =text.indexOf(searchString, pos[

index = pos[num];

num++;

}

}

This function stores the position of each searchstring in an array. Each time through the whileloop, the indexOf() method starts searchingfrom the index of the last search string. Thissearch continues until the search string is nolonger found.

Page 176: Javascript Tutorial - 4730-5

REPLACE TEXT IN A STRING

Sometimes finding the index of a searchstring just isn’t enough. You may want toreplace the string with another string. You

can do this manually, but JavaScript alsoincludes a method that does this.

The replace() method can be used toreplace an existing string with another one.The replace() method accepts the string tosearch for as its first parameter. The secondparameter is the string to replace the first onewith.

For example, if a string is defined as str1 =“I like spaghetti and meatballs

and garlic bread”, you can replace allthe ‘and’ string with the word or by usingthe statementstr1.replace(“and”,”or”).

This method replaces only a single instance ofthe search string, not all instances, in the entirestring. To replace all instances, you need to usethe method several times.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

REPLACE TEXT IN A STRING

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Create a string variable and assign it a value.

‹ Use a document.write() statement to display the value of the string.

› Use the replace() method within another document.write() statement to replace the word and with a comma.

ˇ Save the file as replace.html.

Á Open the replace.html file in a browser.

■ The string is displayed normally and with the replacement.

Note: Only the first and was replaced because the replace() method was used only once.

160

REPLACE TEXT IN A STRING

Page 177: Javascript Tutorial - 4730-5

⁄ Open the file indexOf.html in Notepad.

¤ Use the lastIndexOf() method to display the index of the second and.

‹ Save the file as lastIndexOf.html.

› Open the lastIndexOf.html file in a browser.

■ The string and the index of the second and are displayed.

This code checks for the existence of the searchstring, and if found, it uses the replace() methodto replace it. If the search string isn’t foundwithin the string, the loop condition fails and theprogram continues.

161

WORKING WITH STRINGS 9

All the search strings within a string can bereplaced at once using a while loop such asthe following:

str1 = “standard string”;

searchStr = “str”;

repStr = “tr”;

while (str1.search(searchStr) !=-1) {

str1.replace(searchStr,repStr);

}

Page 178: Javascript Tutorial - 4730-5

SPLIT A STRING

Using JavaScript, you can split a stringinto an array of strings. You may findthis capability useful for extracting all

the separate words within a string.

The split() method does this. This methodtakes a single parameter that is the separatorto locate and use to split the string. Themethod returns an array of strings and can becaptured if the method statement is assignedto a variable. None of the array elementsinclude the separator.

For example, if a string is defined as vocab =“paradigm convolution exception”,

the split() method with the space as aseparator can split these words into an array ofstrings. The method statement looks likemyArray = vocab.split(“ “) and thearray includes three elements.

The strings are placed within the array namedmyArray in the order that they appear in thestring. For example, myArray[0] would equal“paradigm”.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

SPLIT A STRING

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Create a string variable and assign it a value.

‹ Use a document.write() statement to display the value of the string.

› Use the replace() method within another document.write() statement to replace the word and with a comma.

ˇ Save the file as replace.html.

Á Open the replace.html file in a browser.

■ The string is displayed normally and with the replacement.

Note: Only the first and was replaced because the replace() method was used only once.

162

SPLIT A STRING

Page 179: Javascript Tutorial - 4730-5

‡ Open the file replace.html in Notepad.

° Add another document.write() statement to display the string with another replacement.

· Save the file as replace2.html.

‚ Open the replace2.html file in a browser.

■ The updated string is displayed.

163

WORKING WITH STRINGS 9

This simple function separates list items usingthe split() method and places each item asan element in an array. You can view the listusing this code:

for (j=0;j<listArray.length;j++) {

document.write(“List item “ + j+ “: “ + listArray[j]);

}

You can use a textarea to obtain a list ofitems. If you have the user place a symbolsuch as an asterisk (*) in front of each listitem in the textarea box, you can use thesplit() method to separate the list itemsinto an array. A function to do this would looklike this:

function textList(text) {

listArray = text.split(“*”);

}

Page 180: Javascript Tutorial - 4730-5

USING THE DATE OBJECT

The date object isn’t associated with a Webpage element, but it is included as part of thedefault JavaScript syntax.

Before you can use the date object, you must createit. To create a date object, you need to give it avariable name and set it equal to the new keywordfollowed by Date(). For example, myDate = newDate() creates a new date object called myDate.

By defining a parameter to the Date() object, youcan set the date format. The date format accepts threedefinitions. The first must be placed in quotes andinclude “month day, year hours:minutes:seconds.”

The second definition includes just numbers for theyear, month, and day. The third definition is like thesecond except it also includes values for the hours,minutes, and seconds — for example, Date(“Jul29, 1982 06:30:00”), Date(1993, 4, 17)for May 17, 1993, and Date(1997, 3, 4, 10,37, 00) for April 4, 1997 at 10:37 a.m. Months arespecified starting with 0, so 0 is January, 1 isFebruary, and so on.

This example uses the js-skeleton.html filefound on the book’s CD-ROM, but you can applythese steps to any file.

USING THE DATE OBJECT

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Create a new date object including a format within the Date() parentheses.

Note: In this example, I’ve used the first date format.

‹ Use a document.write statement to display the date.

› Save the file as new.html.

ˇ Open the new.html file in a browser.

■ The time and date are displayed.

164

USING THE DATE OBJECT AND DATE FORMATS

Page 181: Javascript Tutorial - 4730-5

WORKING WITH DATES AND TIMES

Á Open the new.html file in Notepad.

‡ Change the format in the Date() object.

Note: In this example, I’ve used the third date format.

° Save the file as new2.html.

· Open the new2.html file in a browser.

■ The new time and date are displayed.

Note: The index for months starts with 0, so 0 is January, 1 is February, and so on, which is why February is returned in this example.

165

10

The date object, when unformatted, holdsonly a single piece of data — an integer. Thisinteger is the number of milliseconds thathave transpired since January 1, 1970. Thisnumber for the current time is a rather largenumber.

To compare date objects, both objects needto be converted to the standard date objectformat, which is the number of millisecondssince January, 1970. Any new date objectthat is created automatically appears in thisformat, and you can convert a date to thisformat using the Date.UTC() method. Thismethod accepts the same formats as a newdate object. For example, Date.UTC(86,2, 16, 8, 45, 00) sets a date objectequal to March 16, 1986 at 8:45:00.

Page 182: Javascript Tutorial - 4730-5

DISPLAY THE LOCAL TIME AND DATE

After creating a new date object, you canuse one of many methods to getinformation about the current date

and time.

One very useful date object method is thetoGMTString() method, which will returnthe current Greenwich mean time (GMT).Greenwich mean time is the time zone whereall other time zones are measured from. Anotheruseful method is toLocaleString(). Thismethod returns the current date and time for thelocal time zone.

The format for these dates and times lists theday, the date, the month, and then the year.After the year comes the hours, minutes, andseconds, and finally the time zone.

For example, Wed, 12 Apr 200003:37:38 UTC is the date and time formatfor Wednesday, April 12 of the year 2000 at3:37 and 38 seconds. UTC is short forUniversal Coordinated Time, which is anothername for GMT.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

DISPLAY THE LOCAL TIME AND DATE

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Create a new date object.

‹ Use a document.write statement to display the Greenwich mean time.

› Save the file as date.html.

ˇ Open the date.html file in a browser.

■ The time and date for Greenwich mean time is displayed.

166

DISPLAY GREENWICH MEAN TIME

Page 183: Javascript Tutorial - 4730-5

⁄ Open the date.html file in Notepad.

¤ Change the toGMTString() method to toLocaleString() and update the displayed text.

‹ Save the file as date2.html.

› Open the date2.html file in a browser.

■ The local time and date are displayed.

The format of the date object remains thesame displaying the day, date, time, and timezone if you use the toGMTString()method. This method displays the day andmonth using three characters, such as Fri forFriday and Apr for April. For example, thisformat looks like this: Fri, 14 Apr 200019:01:54 UTC. The date format for thetoLocaleString() method is a littledifferent. This method displays only numberswith the date first and then the time. Slash

symbols (/) are placed between the datenumbers. For example, the format for thismethod is 04/14/2000 13:05:13. You canalso use the toString() method to displaythe date object. This format looks different stillwith the year at the end of the string. Forexample, this format looks like Fri Apr 1413:06:23 MDT 2000. If you want to use acustom format, you can use the get methods toformat the date, as shown in the next section,“Get Time and Date Values.”

167

WORKING WITH DATES AND TIMES 10

DISPLAY LOCAL TIME AND DATE

Page 184: Javascript Tutorial - 4730-5

JavaScript includes several methods thatenable you to retrieve specific date and timeinformation from a date object. These

methods all begin with the word get and returninteger values.

The getDate() method returns the date, soon January 24, this method would return 24.The getDay() method returns an integerrepresenting the day of the week; that is, 1 isfor Monday, 2 is for Tuesday, and so on,through 7 for Sunday.

The getHours() method returns the hour ofday in 24-hour military time format. For

example, 3:00 p.m. returns 15. ThegetMinutes() and getSeconds()methods return the number of minutes andseconds.

The getMonth() method returns an integerrepresenting the month of the year startingwith 0 for January, so July returns a 6 andDecember returns 11. The getYear()method returns a two-digit value for the year,so 1996 would return 96.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

GET TIME AND DATE VALUES

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Create a new date object.

‹ Use document.write statements to display the get methods for the current date.

› Save the file as getDate.html.

ˇ Open the getDate.html file in a browser.

■ The values for the current date are displayed.

168

GET DATE VALUES

Page 185: Javascript Tutorial - 4730-5

⁄ Open the getDate.html file in Notepad.

¤ Add several additional document.write statements to display the values of the get methods for the current time.

‹ Save the file as getDate2.html.

› Open the getDate2.html file in a browser.

■ The values for the current time are displayed.

Using the get methods, you can create asimple clock. The key to this clock is thesetTimeout() method that is set to call theclock function every 1000 milliseconds. Theclock function can display the time to a textfield named text1 located within a formnamed form1:

169

WORKING WITH DATES AND TIMES 10

GET TIME VALUES

function clock() {

cTime = new Date();

cHours = cTime.getHours();

cMinutes = cTime.getMinutes();

cSeconds = cTime.getSeconds();

document.form1.text1.value =cHours + “:” + cMinutes + “:” +cSeconds;

setTimeout(“clock()”, 1000);

}

This function creates a new date object, getsthe hours, minutes, and seconds, and displaysthese values in a text field. It then calls the samefunction again after 1,000 milliseconds, and theclock is updated again.

Page 186: Javascript Tutorial - 4730-5

SET TIME AND DATE VALUES

When working with the date object,you can also set dates and timesusing one of several methods that

begin with the word set. These methods placean integer value into a date object.

The setDate() method sets the date for theobject and can be a value between 1 and 31.The setMonth() sets the value for themonth. It accept values 0 through 11 with 0for January (so July returns 6 and Decemberreturns 11). setYear() can accept a two-digit or four-digit year value, so 96 would setthe year to 1996.

The setHours() method sets the hour of dayin 24-hour military time format. For example,setHours(15) would set the hour to 3:00p.m. The setMinutes() andsetSeconds() methods set the number ofminutes and seconds for the time.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

SET TIME AND DATE VALUES

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Create a new date object and set the initial date within the parentheses.

‹ Use a document.write statement to display the initial date.

› Change the month, date, and year values using the set methods and display the results.

ˇ Save the file as setDate.html.

Á Open the setDate.html file in a browser.

■ The date before and after the changes is shown.

170

SET DATE VALUES

Page 187: Javascript Tutorial - 4730-5

⁄ Open the setDate.html file in Notepad.

¤ Change the hours, minutes, and seconds using the set methods and display the results.

‹ Save the file as setDate2.html.

› Open the setDate2.html file in a browser.

■ The initial time and changed time are displayed.

If you enable a user to enter a date such astheir birthday using a Web page form, youcan create and save the entire date object.The date object can then be manipulatedand used as needed. For example, you couldcompute how many days until their nextbirthday or display a unique page on theirbirthday. A function to create such a datewould look like this:

171

WORKING WITH DATES AND TIMES 10

SET TIME VALUES

function birthday() {

myBirthday = new Date();

myBirthday.setMonth(document.form1.text1.value);.myBirthday.setDate(document.form1.text2.value);.myBirthday.setYear(document.form1.text3.value);

document.write(“Your birthday is“ + myBirthday);

}

This function creates a new date object andsets the date’s month, date, and year based onthe values of three text fields found on a Webpage form named form1.

Page 188: Javascript Tutorial - 4730-5

Along with the get and set methodsused to control months, dates, years,hours, minutes, and seconds are two

more methods for controlling the time.

The getTime() method returns an integervalue that is equal to the number ofmilliseconds that have passed since January 1,1970. This is the standard format for dates andtimes. You can also use the setTime()method to set the time of a date object. Thismethod accepts the number of millisecondsthat have passed since January 1, 1970.

You can also change a date into this standardformat using the Date.parse() method.This method accepts a month, date, and yearsuch as February 14, 1980 or a moredescriptive format like Mon Nov 17 199713:47:23 MST and returns the number ofmilliseconds since January 1, 1970.

To convert the number of milliseconds sinceJanuary 1, 1970 to a recognizable format, youcan use the toGMTString() method.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

WORK WITH TIME

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Create a new date object.

‹ Use a document.write statement to display the results of the getTime() method.

› Save the file as getTime.html.

ˇ Open the getTime.html file in a browser.

■ The results of the getTime() method are displayed.

172

WORK WITH TIME

Page 189: Javascript Tutorial - 4730-5

Á Open the file getTime.html in Notepad.

‡ Create another date object and set its date.

° Use a document.write and a Date.parse() statement to display the number of milliseconds since January 1, 1970 for this date.

· Save the file as parse.html.

‚ Open the parse.html file in a browser.

■ The number of milliseconds since January 1, 1970 for this date are displayed.

173

WORKING WITH DATES AND TIMES 10

You may sometimes want to perform somearithmetic on a date object. For example, tofigure out how many days are between twodates, you could subtract the two dates andthen calculate the number of days. Such ascript looks like this:

function compDates(date1, date2){

diffMilliseconds = date2 –date1;

diffSeconds = diffMilliseconds/ 1000;

diffMinutes = diffSeconds /60;

diffHours = diffMinutes / 60;

diffDays = diffHours / 24;

return diffDays;

}

This function accepts two dates and returns thedifference in the number of days between them.

Page 190: Javascript Tutorial - 4730-5

JavaScript includes a method that can beused to compute the time difference fordifferent time zones. All times zones are

computed relative to Greenwich mean time(GMT). GMT is also referred to as UTC, whichstands for Universal Time Coordinated.

The getTimezoneOffset() returns thenumber of minutes between GMT and thelocal time zone. The returned value could bepositive or negative, depending on whether thecurrent time zone is ahead of or behindGreenwich mean time.

For example, if the user’s computer is locatedwithin the Pacific standard time zone, then forthe date object named myDate, thestatement myDate.getTimezoneOffset()returns a value of 480. This value representsan offset of 8 hours from GMT.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

⁄ Open the file js-skeleton.html in Notepad.

¤ Create a new date object.

‹ Use a document.write statement to display the current local time and date.

› Add another document.write statement to display the time zone offset.

ˇ Save the file as getTimezoneOffset.html.

Á Open the file getTimezoneOffset.html in a browser.

■ The local time and date and the time zone offset are displayed.

174

WORK WITH TIME ZONES

JAVASCRIPT

WORK WITH TIME ZONESWORK WITH TIME ZONES

Page 191: Javascript Tutorial - 4730-5

‡ Open the getTimezoneOffset.html file in Notepad.

° Add another document.write statement to display the time in the neighboring time zone.

Note: To display the time in a neighboring time zone, you typically only need to add or subtract an hour from the time.

· Save the file as getTimezoneOffset2.html.

‚ Open the getTimezoneOffset2.html file in a browser.

■ The local and neighboring time zone times are displayed.

175

WORKING WITH DATES AND TIMES 10

The getTimezoneOffset() method doesn’tneed to directly handle daylight saving timebecause DST is computed and controlled by theoperating system. Because JavaScript queries thesystem for this information, it automaticallyconverts your date and time settings toaccommodate for the changes caused bydaylight saving time.

The time zone offset value that is returned bythe getTimezoneOffset() method isbased on the user’s internal computersystem. For a Windows-based system, thisvalue is retrieved from the system setting thatis configured using the Control Panel Dateapplication. If the date and time specified inthis system application is incorrect, the dateobject methods will return incorrect valuesfor the date object.

Page 192: Javascript Tutorial - 4730-5

USING THE MATH OBJECT

The Math object includes properties andmethods that make it possible to workwith mathematical equations and

computations.

The Math object includes properties forrepresenting various mathematical values, suchas Euler’s constant (E), base-10 logarithms(LOG10E), natural logarithms (LN10), pi (PI),and the square root of two (SQRT2).

The Math object methods include a variety ofadvanced mathematical functions. Thesefunctions include, but are not limited to,

abs(x), ceil(x), floor(x), sin(x),cos(x), tan(x), log(x), min(x),max(x), pow(x,y), random(), andsqrt(x), where x and y are numbers.

The Math object doesn’t need to be specifiedas a sub-object of the document or windowobjects, but it does need to be capitalized. Forexample, to specify the value of pi, you mustuse the Math.PI syntax.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING THE MATH OBJECT

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a form with two text boxes and a button.

‹ Add the onclick event to the button.

› Add a statement for the onclick event that computes the area of a circle based on the text box value.

ˇ Save the file as math.html.

Á Open the math.html file in a browser.

■ A form with two text boxes and a button is displayed.

176

USING THE MATH OBJECT

Page 193: Javascript Tutorial - 4730-5

USING THE MATH OBJECT

‡ Enter a number in the first text box.

° Click the form button. ■ The computed answer is displayed in the second text box.

177

11

Each Math object method returns a valuebased on the number that is passed as aparameter. The number passed in as aparameter could be an actual number oranother object. For example,Math.pow(2,3) returns a value of 8,which is the value of 2 raised to the powerof 3. The JavaScript statementMath.cos(document.form1.text1.value) returns the cosine of the valuefound in the text box named text1 on theform named form1.

The Math object keyword that appears infront of the properties and methods alwaysneeds to be capitalized. JavaScript is case-sensitive and does not work if capitalizedincorrectly.

Page 194: Javascript Tutorial - 4730-5

GENERATE RANDOM NUMBERS

Random numbers can be used withinJavaScript scripts for a number ofdifferent purposes, such as randomly

selecting an option for the user.

The Math.random() method returns arandom number between 0 and 1. If youmultiply the number generated by this methodby another number, you can get a randomnumber that is between 0 and the othernumber. For example, the statementMath.random() * 5 generates a numberbetween 0 and 5.

The random number will not be an integer, butyou can make it an integer using theMath.floor() method. This methodtruncates the numbers after the decimal pointand returns an integer. For example,Math.floor(Math.random() * 5)returns a random integer between 0 and 4.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

GENERATE RANDOM NUMBERS

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.¤ Within the <script> tags, create a new array using the Array keyword.‹ Add several quotes to the array enclosed in quotation marks and separated with commas.

› Create a variable using the Math.floor() and Math.random() methods and multiply Math.random() by the array’s length.ˇ Display a quote using document.write().Á Save the file as random.html.

‡ Open the random.html file in a browser.

■ A quote is displayed in the browser.

° Click the Refresh button on the browser.

178

GENERATE RANDOM NUMBERS

Page 195: Javascript Tutorial - 4730-5

■ The page is reloaded and another quote is displayed.

· Click the Refresh button again.

■ The page is again reloaded and another quote is displayed.

The first statement generates a random numberbetween 1 and 3. Statements can be placed inthe braced sections for each option.

179

USING THE MATH OBJECT 11

To select options based on random numbers,you can use a series of if and else ifstatements. For example, consider thefollowing function:

function threeOptions() {

rand =Math.floor(Math.random() * 3);

if (rand == 1) {

document.write(“option 1”);

}

else if (rand == 2) {

document.write(“option 2”);

}

else {

document.write(“option 3”);

}

}

Page 196: Javascript Tutorial - 4730-5

USING MATHEMATICAL CONSTANTS

The properties of the Math object are usedto represent several standardmathematical constants. Various

mathematical equations rely on theseconstants.

These constants include Euler’s constant(Math.E), the natural logarithm of 10(Math.LN10), the natural logarithm of 2(Math.LN2), the base-10 logarithm of Euler’sconstant (Math.LOG10E), the base-2logarithm of Euler’s constant (Math.LOG2E),pi (Math.PI), the square root of one half(Math.SQRT1_2), and the square root of two(Math.SQRT2).

These properties can be inserted wherever theconstant would normally appear in theequation. JavaScript computes the value of theconstant to roughly 17 digits. Using theseconstants enables a high level of accuracywithout having to type in all the digits.

For example, to compute the perimeter of acircle, you can use the statement perimeter= 2 * radius * Math.PI.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING MATHEMATICAL CONSTANTS

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Use document.write statements to display the values of all the mathematical constants and a heading.

‹ Save the file as constants.html.

› Open the file constants.html in a browser.

■ All the Math object constants are displayed.

180

DISPLAY THE MATH OBJECT CONSTANTS

Page 197: Javascript Tutorial - 4730-5

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a form with two text boxes and a button.

‹ Add the onclick event to the button.

› Add a statement for the onclick event that computes the area of a sphere based on the text box value.

ˇ Save the file as sphere.html.

Á Open the file sphere.html in a browser.

‡ Enter a number in the first text box.

° Click the form button.

■ The computed answer is displayed in the second text box.

181

USING THE MATH OBJECT 11

USING THE MATH.PI CONSTANT

Many different mathematical equations relyon these constants. Some of these constantscan be computed using the other Math objectmethods. For example, the Math.LN10constant can be computed using theMath.log() method that is used tocompute the natural logarithm of a number.The reason this number is defined as aconstant is that it appears in many usefulequations and, as a constant, it can be quicklyincluded and computed as part of a JavaScriptstatement.

If the Math object doesn’t include a specificconstant that you need, you can create a globalvariable and assign it the needed variable. Thisvariable could then be used throughout thescript.

Page 198: Javascript Tutorial - 4730-5

USING TRIGONOMETRIC FUNCTIONS

Do you remember the trigonometricfunctions from your geometry class?JavaScript supports these as methods of

the Math object, including the cosine, sine,and tangent functions. JavaScript also supportstheir opposite functions: arc-cosine, arc-sine,and arc-tangent.

The methods for these functions are cos(),sin(), tan(), acos(), asin(), andatan(). All these functions take a singleparameter value and return an angular value inradians.

Radians are a mathematical measure of anangle. 360 degrees is equal to 2 Pi radians. Youcan compute the more common angularmeasurement of degrees by multiplying thenumber of radians by 57.3.

JavaScript also includes one additionaltrigonometric method that can convertstandard x and y coordinate values to anangular measurement. This method isatan2(), and it takes two coordinate valuesas parameters.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING TRIGONOMETRIC FUNCTIONS

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a heading and a form with six text boxes. Make three text boxes to hold the values of the sides of a triangle and three to hold the trigonometric angle values.

‹ Add the onchange event to each text box for the side lengths.

› Set each onchange event equal to the trigonometric equation for computing the angle values.

ˇ Save the file as trig.html.

Á Open the trig.html file in a browser.

■ A form with six text boxes is displayed.

182

USING TRIGONOMETRIC FUNCTIONS

Page 199: Javascript Tutorial - 4730-5

‡ Enter a number into each of the side text boxes, making sure that the sides are those of a right triangle.

■ The computed angle values are displayed.

° Change the values in the side text boxes, again making sure that the sides are those of a right triangle.

■ The computed angle values are updated and displayed.

183

USING THE MATH OBJECT 11

To convert the angles measured in radians todegrees, you can use a function like this one:

function radiansToDegrees(rads) {

degrees = (360 * rads / (2 *Math.PI));

return degrees;

}

The function takes a radian value and returns anequivalent value in degrees. A similar functioncan be created to convert degrees back toradians. Such a function looks like this:

function degreesToRadians(degrees){

radians = (2 * Math.PI *degrees) / 360);

return radians;

}

This function takes a value in degrees as aparameter and returns the same value measuredin radians.

Page 200: Javascript Tutorial - 4730-5

USING LOGARITHMIC ANDEXPONENTIAL METHODS

JavaScript includes two methods for working withnatural logarithms and exponentials based onEuler’s constant.

The log() method takes a number as a parameterand returns the natural logarithm (base e) of thenumber.

The exp() method takes a number as a parameterand returns the value of Euler’s constant raised tothe power of the number.

These two methods are complementary where thelog(x) = y and the exp(y) = x.

This example uses the js-skeleton.html filefound on the book’s CD-ROM, but you can applythese steps to any file.

USING LOGARITHMIC ANDEXPONENTIAL METHODS

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a form with three text boxes and a button.

‹ Add the onclick event to the button.

› Add a statement for the onclick event that computes the log and the exp of the value.

ˇ Save the file as log.html.

Á Open the log.html file in a browser.

‡ Enter a number in the first text box.

° Click the form button.

■ The computed answers are displayed in the other text boxes.

184

USING LOGARITHMIC AND EXPONENTIAL METHODS

The Math.LN10 and Math.LN2properties are constants for valuesreturned by Math.log(10) andMath.log(2). The Math.log()method can be used to return the naturallogarithm of any number.

Page 201: Javascript Tutorial - 4730-5

USING THE SQUARE ROOT METHOD

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a form with two text boxes and a button.

‹ Add the onclick event to the button.

› Add a statement for the onclick event that computes the square root of the value in the first text box.

ˇ Save the file as sqrt.html.

Á Open the sqrt.html file in a browser.

‡ Enter a number in the first text box.

° Click the form button.

■ The computed value is displayed in the second text box.

USING THE SQUARE ROOT METHOD

185

USING THE MATH OBJECT

JavaScript also includes a method for computing thesquare root of a number. This computation isaccomplished with the sqrt() method.

The sqrt() method receives a number as a parameter andreturns its square root.

An example of where the sqrt() method is used is incomputing the Pythagorean theorem (the square of twosides of a right triangle equals the square of thehypotenuse).

This example uses the js-skeleton.html file found onthe book’s CD-ROM, but you can apply these steps to anyfile.

USING THE SQUARE ROOT METHOD

The Math.SQRT1_2 andMath.SQRT2 properties areconstants for values returnedby Math.sqrt(1/2) andMath.sqrt(2). TheMath.sqrt() method can beused to return the square rootof any number.

11

Page 202: Javascript Tutorial - 4730-5

ROUND NUMBERS

If you’re dealing with floating-point numbersthat include a decimal point, you caneliminate the numbers after the decimal

point by using the round() method.

This method changes any floating-pointnumber to the closest integer. Any decimalvalue less than 0.5 converts the number to thelower integer value. Any decimal value equal toor greater than 0.5 rounds up to the nextgreatest integer.

For example, the number 4.45 rounds down tothe integer 4, and a value of 4.50 rounds up tothe integer 5.

ROUND NUMBERS

JAVASCRIPT

⁄ Open the file js-skeleton.html from the CD-ROM in Notepad.

¤ Add a form with two text boxes and a button.

‹ Add the onclick event to the button.

› Add a statement for the onclick event that rounds the value.

ˇ Save the file as round.html.

Á Open the round.html file in a browser.

‡ Enter a number in the first text box.

° Click the form button.

■ The rounded value is displayed in the second text box.

186

ROUND NUMBERS

JavaScript also includes a couple ofmethods that enable you to roundnumbers up to the next nearestinteger or down to the nearest integer.These methods are ceil() andfloor(). For example, the followingstatements are both rounded to avalue of 5:

ceil(4.65);

floor(5.76);

Page 203: Javascript Tutorial - 4730-5

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a form with three text boxes and a button.

‹ Add the onclick event to the button.

› Add a statement for the onclick event that computes the value of the first text box raised to the power of the second text box.

ˇ Save the file as pow.html.

Á Open the pow.html file in a browser.

‡ Enter numbers in the first two text boxes.

° Click the form button.

■ The resulting value is displayed in the third text box.

Raising a number to the power of1⁄2 is the same as computing thesquare root of the number. You caninclude any value as the secondparameter including variables, butthe parameter must be a number.

187

RAISE NUMBERS TO A POWER

USING THE MATH OBJECT

RAISE NUMBERS TO A POWER

JavaScript includes another Math object method that canbe used to raise one number to the power of another.

This method is the pow() method. It accepts twoparameters. The first parameter is the number, and thesecond parameter is the power that the number is raised to.

For example, the statement Math.pow(5, 2) raises thenumber 5 to the power of 2, resulting in a value of 25.

This example uses the js-skeleton.html file found onthe book’s CD-ROM, but you can apply these steps to anyfile.

RAISE NUMBERS TO A POWER

11

Page 204: Javascript Tutorial - 4730-5

FIND MINIMUM AND MAXIMUMVALUES

If you ever want to determine if one numberor another is greater, you could use a seriesof if statements, but a simpler method is

to use the min() and max() methods.

These Math object methods accept twoparameters and return the number that issmaller or greater.

For example, the min(3, 4) statement returnsthe value of 3, because 3 is the smaller numberof the two. The statement max(3, 4) returnsthe value of 4, because 4 is larger than 3.

FIND MINIMUM AND MAXIMUMVALUES

JAVASCRIPT

⁄ Open the file js-skeleton.html from the CD-ROM in Notepad.

¤ Add a form with four text boxes and a button.

‹ Add the onclick event to the button.

› Add a statement for the onclick event that determines the maximum and minimum values in the first two text boxes.

ˇ Save the file as min-max.html.

Á Open the min-max.html file in a browser.

‡ Enter numbers in the first two text boxes.

° Click the form button.

■ The minimum and maximum values are displayed.

188

FIND MINIMUM AND MAXIMUM VALUES

To use an if-else statement to determinemaximum values, the code looks like this:

function maximum(val1, val2) {

if (val1 > val2)

return val1;

else

return val2;

}

Page 205: Javascript Tutorial - 4730-5

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a form with two text boxes and a button.

‹ Add the onclick event to the button.

› Add a statement for the onclick event that computes the absolute value of the value in the first text box.

ˇ Save the file as abs.html.

Á Open the abs.html file in a browser.

‡ Enter a number in the first text box.

° Click the form button.

■ The absolute value of the number is displayed.

189

USING THE MATH OBJECT 11

JavaScript includes another Math objectmethod that can be used to return theabsolute value of a number. Absolute value

ensures that a number is positive. If a negativenumber is sent, then the negative sign isremoved, and the positive value is returned.

This method is the abs() method. It accepts asingle parameter and returns the absolutevalue of the number.

For example, the statement Math.abs(-25)returns a positive value of 25.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

.

USING ABSOLUTE VALUESUSING ABSOLUTE VALUES

USING ABSOLUTE VALUES

The abs() method works on any numberincluding integers and floating-point numbers,but it returns NaN if it is sent a string.

Page 206: Javascript Tutorial - 4730-5

JAVASCRIPT

190

USING TEXT BOXES

Using HTML, you can interact with theuser using forms. Forms enable the userto input simple data types using

elements such as text boxes, radio and checkbox buttons, and selection lists.

Using JavaScript, you can dynamically alter thecontents of a form element such as a text box.

Text boxes are defined in HTML using the<input> tag and setting the type attribute totext. Text boxes also include name andvalue attributes.

To reference a text box in JavaScript, you needto refer to the form name and the text boxname. For example, you can get the value of atext box named text1 within a form namedform1 by using the syntaxdocument.form1.text1.value.

Properties for the text box object includedefaultValue, enabled, form, name,size, type, and value. The methods includefocus(), blur(), and select().

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING TEXT BOXES

DISPLAY TEXT BOX OBJECT PROPERTIES

⁄ Open the file js-skeleton.html in Notepad.

¤ Before the <script> tags, add a form with a single text box.

‹ Add several document.write statements to display some of the text box object properties.

› Save the file as text.html.

ˇ Open the text.html file in a browser.

■ A text box is displayed with its property values.

Page 207: Javascript Tutorial - 4730-5

WORKING WITH FORMS

191

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a form with a text box to the Web page.

‹ Add the onfocus event to the text box and assign it the select() method.

› Save the file as text2.html.

ˇ Open the text2.html file in a browser.

Á Click in the text box.

■ The text within the text boxis selected.

The defaultValue property of the textobject is different from the value property.The defaultValue property is the value thatis included as part of the <input/> tag. Thevalue property is the text that exists insidethe text box. Initially, this text is the same asthe defaultValue, but the user can changeit. If the user changes a value, you canretrieve its initial value from thedefaultValue property.

It is okay to have a text box without anydefault text. If the value attribute isn’tincluded, then the text box will appear blankwithout any displayed text.

Using the select() method, you canautomatically select the contents of a text box.

USING TEXT BOX OBJECT METHODS

12

Page 208: Javascript Tutorial - 4730-5

You need to be careful to keep the contents ofa password box secure. If you view thecontents of a password box with thedocument.form1.password1.valuestatement, the password is visible. Tomaintain password security, you should passany passwords directly to the server.

WORK WITH PASSWORD BOXES

Password boxes are similar to text boxes,except all characters typed in a passwordbox are displayed as asterisks (*). This

password masking is useful for inputtingsensitive information such as a passwordwithout revealing the information to abystander looking over your shoulder.

The password box object includes propertiesfor defaultValue, enabled, form, name,size, type, and value. It also includesmethods for focus(), blur(), andselect().

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

WORK WITH PASSWORD BOXES

WORK WITH PASSWORD BOXES

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Before the <script> tags, add a form with a single password box.

‹ Add several document.write statements to display some of the password object properties.

› Save the file as password.html.

ˇ Open the password.html file in a browser.

■ A password box is displayed with its property values.

192

Page 209: Javascript Tutorial - 4730-5

193

WORKING WITH FORMS 12

WORK WITH HIDDEN FIELDS

Hidden fields are a special type of formelement. You create them using the<input/> tag with the type attribute

set to hidden. Hidden fields do not displayanything within a browser, but can be used topass data to the form-processing script.

The hidden object includes only threeproperties — name, type, and value — andno methods.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

WORK WITH HIDDEN FIELDS

⁄ Open the file js-skeleton.html in Notepad.

¤ Before the <script> tags, add a form with a hidden field.

‹ Add several document.write statements to display some of the hidden object properties.

› Save the file as hidden.html.

ˇ Open the hidden.html file in a browser.

■ The hidden object properties are displayed.

WORK WITH HIDDEN FIELDS

Hidden fields are not visible within a browser,but they can be viewed as part of code withina Web page file. If you use the browser’sView Source option, you can see any hiddenfields and their values.

Page 210: Javascript Tutorial - 4730-5

WORK WITH TEXTAREA BOXES

Textarea boxes are like multiple-line textboxes. They are created using beginningand ending <textarea> tags and can be

used to display full paragraphs of text.

You can specify the size of a textarea box byusing the rows and cols attributes. The colsattribute is similar to the text box’s sizeattribute. It defines the width of the element innumber of characters. You can also specify thenumber of rows of text that are available usingthe rows attribute. Both of these attributes areaccessible as properties to the textarea object.

The textarea object is very similar to thetext object and includes properties foridentifying defaultValue, enabled, form,name, rows, cols, type, and value.

The textarea object also includes, like thetext object, methods for focus(), blur(),and select().

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

WORK WITH TEXTAREA BOXES

DISPLAY TEXTAREA BOX PROPERTIES

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Before the <script> tags, add a form with a textarea box.

‹ Add several document.write statements to display some of the textarea object properties.

› Save the file as textarea.html.

ˇ Open the textarea.html file in a browser.

■ A textarea box is displayed with its property values.

194

Page 211: Javascript Tutorial - 4730-5

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a form with a textarea box to the Web page.

‹ Add the onfocus event to the textarea box and assign it the select() method.

› Save the file as textarea2.html.

ˇ Open the textarea2.html file in a browser.

Á Click in the textarea box.

■ The text within the text box is selected.

This form presents a textarea box with the riddlequestion displayed within it. When the userclicks in the textarea box or when it gets focus,the onfocus event is fired and the JavaScriptstatement is executed, which replaces thequestion with the appropriate answer.

195

WORKING WITH FORMS

USING A TEXTAREA BOX OBJECT METHOD

12

The textarea properties can be combinedwith an event to update the text within atextarea box. For example, imagine listing ariddle and showing the answer when the userclicks in the box. The code looks like this:

<form name=“form1”>

<textarea name=“ta1” rows=“4”onfocus=“document.form1.ta1.value=‘Ihave you covered.’”>What did the rugsay to the floor?</textarea>

</form>

Page 212: Javascript Tutorial - 4730-5

USING BUTTONS

Using HTML, you may make form buttonsin two different ways. The first way is touse the <input/> tag and set the

type attribute equal to button, reset, orsubmit. The second way is to use the<button> tag.

Reset and Submit buttons have their ownobjects and are covered later in this chapter inthe sections “Using a Reset Button” and“Using a Submit Button.”

JavaScript includes a button object thatincludes properties and methods forcontrolling form buttons.

button properties include enabled, form,name, type, and value. The value attributedetermines the text that appears on the surfaceof the button.

The button object methods include click()and focus(). Using the click() method,you can simulate the user clicking the button.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING BUTTONS

DISPLAY BUTTON OBJECT PROPERTIES

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Before the <script> tags, add a form with a button.

‹ Add several document.write statements to display some of the button object properties.

› Save the file as button.html.

ˇ Open the button.html file in a browser.

■ A button is displayed with its property values.

196

Page 213: Javascript Tutorial - 4730-5

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a form with a text box and a button to the Web page.

‹ Add the onclick event to the button and assign it a statement to update the text box.

› Save the file as button2.html.

ˇ Open the button2.html file in a browser.

Á Click the button.

■ The text specified by the onclick event is displayed in the text box.

Using the <button> tag is somewhat differentthan using an <input/> tag, but the resultscan be the same. The following code uses the<button> tag to create a button that updatesa text box when it’s ’ “” clicked:

<form name=“form1”>

<input type=“text” name=“text1”></br>

<button name=“button1”onclick=“document.form1.text1.value=‘Settle down, count to 10 and take adeep breath.’”>Panic Button</button>

</form>

This button works the same as a buttoncreated using an <input/> tag.

197

WORKING WITH FORMS

REACT TO A CLICK EVENT

12

Page 214: Javascript Tutorial - 4730-5

The form object includes the reset() method.This method can be used to simulate the resultsof a Reset button, which resets a form.

USING A RESET BUTTON

Reset buttons are a special type of buttonthat resets all the form elements to theirinitial default values. Reset buttons can

be created using the <input/> tag with thetype attribute set to reset.

The reset object includes properties forenabled, form, name, and value. Just likethe button object, it also includes click()and focus() methods.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING A RESET BUTTON

USING A RESET BUTTON

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Before the <script> tags, add a form with a Reset button.

‹ Add several document.write statements to display some of the reset object properties.

› Save the file as reset.html.

ˇ Open the reset.html file in a browser.

■ A Reset button is displayed with its property values.

198

Page 215: Javascript Tutorial - 4730-5

199

WORKING WITH FORMS 12

The Submit button can be used to send formdata to an e-mail address. You enable thisfunctionality by adding the mailto: keywordand an e-mail address to the action attributeof the <form> tag.

The form object also includes the submit()method. This method can be used to simulatethe results of a Submit button, which submitsa form.

USING A SUBMIT BUTTON

ASubmit button sends the form data to theserver. The place where the data is sentis determined by the <form> tag’s

action attribute. Submit buttons can becreated using the <input/> tag with thetype attribute set to submit.

The submit object includes properties forenabled, form, name, and value, as well asthe click() and focus() methods.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING A SUBMIT BUTTON

USING A SUBMIT BUTTON

⁄ Open the file js-skeleton.html in Notepad.

¤ Before the <script> tags, add a form with a Submit button.

‹ Add several document.write statements to display some of the submit object properties.

› Save the file as submit.html.

ˇ Open the submit.html file in a browser.

■ A Submit button is displayed with its property values.

Page 216: Javascript Tutorial - 4730-5

USING CHECK BOX BUTTONS

Check box buttons are boxes that can bemarked as checked or unchecked. Theyare typically used to set or unset

options. Check boxes are created with an<input/> tag whose type attribute is set tocheckbox.

The checkbox object identifies each separatecheck box element by its name attribute. Forexample, the value of a check box namedcheck1 in a form named form1 could bereferenced using the statementdocument.form1.check1.value.

The properties for the checkbox objectinclude checked, defaultChecked,enabled, form, name, type, and value.The checked property is a Boolean value thatis set to true if the check box is checked.

The methods for this object are click() andfocus().

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING CHECK BOX BUTTONS

DISPLAY CHECK BOX OBJECT PROPERTIES

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Before the <script> tags, add a form with a check box.

‹ Add several document.write statements to display some of the checkbox object properties.

› Save the file as checkbox.html.

ˇ Open the checkbox.html file in a browser.

■ The check box is displayed with its property values.

200

Page 217: Javascript Tutorial - 4730-5

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a form with several check boxes and a button to the Web page.

‹ Add the onclick event to the button and assign it a statement for each check box that checks the check box.

› Save the file as checkbox2.html.

ˇ Open the checkbox2.html file in a browser.

Á Click the button.

■ All check boxes are checked ( ).

This function runs the statements associatedwith each checked check box. If all three areselected, the browser displays all threestatements.

201

WORKING WITH FORMS

CHECK MULTIPLE CHECK BOXES

12

You can set up a function that executesstatements based on which check boxes areselected. Such a function looks like this:

function check() {

if (document.form1.check1.checked== true)

document.write(“Checkbox 1 isselected”);

if (document.form1.check2.checked== true)

document.write(“Checkbox 2 isselected”);

if (document.form1.check3.checked== true)

document.write(“Checkbox 3 isselected”);

}

Page 218: Javascript Tutorial - 4730-5

USING RADIO BUTTONS

Radio buttons come in sets. Only a singleradio button in the set may be selectedat a time. All the radio buttons within a

set share the same name. Each individual radiobutton is indexed by the order that it appearsin the form. The first radio button has an indexvalue of 0.

For example, a set of four radio buttons namedmyradio could be referred to in order asmyradio[0], myradio[1], myradio[2],and myradio[3].

Just like the other Web page elements, theobject properties are similar to the attribute list

for the <input/> tag, including checked,defaultChecked, enabled, form,length, name, and value. The lengthproperty returns the number of radio buttonelements in the set.

The radio button object also includes theclick() and focus() methods.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING RADIO BUTTONS

DISPLAY RADIO BUTTON OBJECT PROPERTIES

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Before the <script> tags, add a form with a set of radio buttons.

‹ Add several document.write statements to display some of the radio object properties.

› Save the file as radio.html.

ˇ Open the radio.html file in a browser.

■ The radio buttons are displayed with their property values.

202

Page 219: Javascript Tutorial - 4730-5

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a form with several radio buttons and a text box to the Web page.

‹ Add the onclick event to each radio button and assign it a statement that updates the text box text.

› Save the file as radio2.html.

ˇ Open the radio2.html file in a browser.

Á Click a radio button.

■ The text in the text box is updated.

This function is a little different than theexample for check boxes because radio buttonsare mutually exclusive. This means that only oneradio button at a time can be selected.

203

WORKING WITH FORMS

RESPOND TO A RADIO BUTTON SELECTION

12

You can set up a function that executesstatements based on which radio button isselected. Such a function looks like this:

function radio() {

if (document.form1.radio1.checked== true)

document.write(“Radio button 1is selected”);

else if (document.form1.radio2.checked == true)

document.write(“Radio button 2is selected”);

else

document.write(“Radio button 3is selected”);

}

Page 220: Javascript Tutorial - 4730-5

WORK WITH SELECTION LISTS

The select object is used to create drop-down lists. Each item in the list is createdwith an <option/> tag. JavaScript

includes a select object, as well as an optionobject, that can be used to control selection lists.

The select object includes the name, length,size, and selectedIndex properties. Thelength property returns the number of optionsin the selection list, and the selectedIndexproperty holds the index of the selected list item.

The option object is a sub-object of the selectobject. It is an array, and each object can bereferred to by using its index value (with 0 beingthe first option).

For example, the first option of a selection listnamed mylist found in a form named form1 isdocument.form1.mylist.option[0]. Theoption object also includes properties. Theseproperties are covered later in this chapter in thesection “Work with Separate Selection List Items.”

The select object also includes the blur() andfocus() methods.

This example uses the js-skeleton.html filefound on the book’s CD-ROM, but you can applythese steps to any file.

WORK WITH SELECTION LISTS

DISPLAY SELECT OBJECT PROPERTIES

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Before the <script> tags, add a form with a selection list.

‹ Add several document.write statements to display some of the select object properties.

› Save the file as select.html.

ˇ Open the select.html file in a browser.

■ The selection list is displayed with its property values.

Á Click an item in the list.

‡ Click your browser’s Refresh button.

■ The selected list item’s property value updates.

204

Page 221: Javascript Tutorial - 4730-5

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a form with a selection list and a text box to the Web page.

‹ Add the onchange event to the selection list and assign it a function.

› Add a function that updates the text box based on the list item that is selected.

ˇ Save the file as select2.html.

Á Open the select2.html file in a browser.

‡ Click one of the list items.

■ The text in the text box is updated.

If you try to reference an index value thatdoesn’t exist, the browser produces an errorand the JavaScript script quits. The error isindicated in the browser with a message thatshows up on the browser’s Status bar.

If no selection list item is selected, theselectedIndex property returns -1. You cancheck for this value to validate that the userhas selected an item on the list.

You can use the selectedIndex property tomark which list item is selected by default.For example, if you set the selectedIndexto 2, then the third item in the list will beselected by default.

205

WORKING WITH FORMS

RESPOND TO A LIST SELECTION

12

Page 222: Javascript Tutorial - 4730-5

WORK WITH SEPARATESELECTION LIST ITEMS

The option object is a sub-object of theselect object. Each selection list item isan element in an array, and each object

can be referred to by using its index value. Thefirst index value is always 0.

The option object also includes severalproperties that relate directly to the individuallist items. The defaultSelected propertyreturns the index of the list item that is markedto be selected initially. The selectedIndexproperty identifies the currently selected list

item, and the selected property is a Booleanthat identifies if the current list item isselected. The text property returns the textthat is in between the beginning and ending<option> tags.

Properties can be used for individual list itemsusing their index values. For example, if thethird item in a list is selected, document.form1.select1.options[2].selectedreturns a value of true.

WORK WITH SEPARATESELECTION LIST ITEMS

DISPLAY OPTION OBJECT PROPERTIES

JAVASCRIPT

⁄ Open the file js-skeleton.html from the CD-ROM in Notepad.

¤ Before the <script> tags, add a form with a selection list.

‹ Add several document.write statements to display some of the option object properties.

› Save the file as option.html.

ˇ Open the option.html file in a browser.

■ The selection list is displayed with the properties for a single list item, as specified by the document.write statements in this example.

206

Page 223: Javascript Tutorial - 4730-5

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a form with a selection list and a button to the Web page.

‹ Add the onclick event to the button and assign it a function.

› Add a function that updates the selection list items.

ˇ Save the file as option2.html.

Á Open the option2.html file in a browser.

‡ Click the form button.

■ The list item text is updated.

207

WORKING WITH FORMS

CHANGE LIST ITEM TEXT

12

The option object includes other properties,such as index, length, name, and value.

The option object doesn’t include any methods.

Selection lists can accept only a singleselection. If you add the multiple attributeto the <select> tag, the selection list allowsmultiple list items to be selected. If themultiple attribute is included, then the usercan select multiple list items by holding downthe Ctrl or Shift keys. The multiple attributeis covered in the next section, “Work with aMultiple-Selection List.”

If the size attribute isn’t specified, then onlya single list item is initially displayed. The listwill include an arrow to its right that willreveal the rest of the list items if it is clickedon. Because the selection list doesn’t includeany way to scroll horizontally, the width ofthe entire list is determined by the width ofthe longest list item element.

Page 224: Javascript Tutorial - 4730-5

WORK WITH A MULTIPLE-SELECTION LIST

Selection list boxes can be set to acceptmultiple selections. Including themultiple attribute in the <select> tag

enables multiple selection.

The select and option object propertieswork the same for multiple selection lists asthey do for single selection lists. TheselectedIndex property, which for singleselection lists the index of the selected item,returns only the index of the lowest selecteditem.

For example, if you have a selection list withseven items and the second, third, and fourthlist items are selected, the selectedIndexproperty returns the index for the second itemin the list, which is 1 because the index startsat 0.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

WORK WITH A MULTIPLE-SELECTION LIST

WORK WITH A MULTIPLE-SELECTION LIST

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Before the <script> tags, add a form with a multiple selection list.

‹ Add several document.write statements to display the selected property for each of the list items.

› Save the file as multiple.html.

ˇ Open the multiple.html file in a browser.

■ The selection list is displayed with none of the list items selected.

208

Page 225: Javascript Tutorial - 4730-5

Á Select several list items while holding down the Ctrl key.

‡ Click your browser’s reload button.

■ The selected property for the selected list items is true.

° Select all the list items while holding down the Ctrl key.

· Click your browser’s reload button.

■ The selected property for all the list items is true.

209

WORKING WITH FORMS 12

You can set up a function that executesstatements based on which selection list itemis selected. Such a function looks like this:

function list() {

if(document.form1.select1.options[0].selected == true)

document.write(“Selection listoption 1 is selected”);

if(document.form1.select1.options[1].selected == true)

document.write(“Selection listoption 2 is selected”);

if(document.form1.select1.options[2].selected == true)

document.write(“Selection listoption 3 is selected”);

}

This function executes a different set ofstatements for each list item that is selected.

Page 226: Javascript Tutorial - 4730-5

DISABLE FORM ELEMENTS

Form elements can be disabled if thedisabled attribute is included. Disabledform elements are removed from the tab

order, which assigns focus. They also becomegrayed out and cannot be interacted with untilenabled again.

Almost all the form elements include adisabled property. This property returns aBoolean value, either true if the form elementis disabled or false if the form element isenabled.

For example, if a form named form1 contains atext box named text1 that is disabled,

document.form1.text1.disabled equalstrue.

Form elements that include the disabledproperty include the button, checkbox,combo, password, radio, reset, select,submit, text, and textarea objects.

This example uses the js-skeleton.html filefound on the book’s CD-ROM, but you can applythese steps to any file.

DISABLE FORM ELEMENTS

DISABLE FORM ELEMENTS

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Before the <script> tags, add a form with a selection list, a text box, and a check box.

‹ Add the disabled attribute to all form elements.

› Add several document.write statements to display the disabled property.

ˇ Save the file as disabled.html.

Á Open the disabled.html file in a browser.

■ The form elements are all disabled.

210

Page 227: Javascript Tutorial - 4730-5

‡ Open the file disabled.html in Notepad.

° Remove some of the disabled attributes from the form elements.

· Save the file as disabled2.html.

‚ Open the disabled2.html file in a browser.

■ Several previously disabled form elements are now enabled.

211

WORKING WITH FORMS 12

Using the disabled property, you candynamically disable form elements. For example,if you have a form named form1, a text boxnamed text1, and a button named button1, thefollowing JavaScript statement disables these twoform elements:

function disableElements() {

document.form1.text1.disabled = true;

document.form1.button1.disabled =true;

}

This function disables the form elements whosedisabled properties are set to true. The formelements can be enabled once again if thedisabled property is set to false.

Page 228: Javascript Tutorial - 4730-5

RESET AND SUBMIT A FORM

The form object includes properties andmethods for the entire form, includingmethods that can be used to reset and

submit the form data to the server.

The form object properties include action,elements, length, method, and target.The action and method propertiesdetermine where and how the form data getspassed to the server. The elements propertyenables you to refer to any element within theform using an index that matches the order inwhich the element appears in the form. Thelength property returns the number ofelements in the form. The target property

specifies which window name the form data issent to. This property is explained in moredetail in Chapter 13.

The form object methods that, like the Resetand Submit buttons, reset and send the formdata to the server are reset() andsubmit(). Using these methods, you canreset or submit the form data using anyJavaScript event.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

RESET AND SUBMIT A FORM

DISPLAY FORM OBJECT PROPERTIES

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Before the <script> tags, add a form with a text box.

‹ Add several document.write statements to display some of the form object properties.

› Save the file as form.html.

ˇ Open the form.html file in a browser.

■ The form is displayed with its properties.

212

Page 229: Javascript Tutorial - 4730-5

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a form with a text box to the Web page.

‹ Add several document.write statements to display the properties of the first form element.

› Save the file as form2.html.

ˇ Open the form2.html file in a browser.

■ The property values of the first form element are displayed.

The form object can accept the onReset andonSubmit events. Using these events, you canoverride the typical Submit and Reset buttonfunctions.

The form object holds an array of all the formelements. Using the form object, you candirectly control all the form elements. The indexvalues for the elements of a form aredetermined by the order in which they appearin the form. For example, if a single formnamed form1 includes two text boxes and abutton, then the first text box can be referencedas document.form1.elements[0], the secondtext box can be referenced asdocument.form1.elements[1], and thebutton can be referenced asdocument.form1.elements[2].

213

WORKING WITH FORMS

DISPLAY FORM ELEMENT PROPERTIES

12

Page 230: Javascript Tutorial - 4730-5

VALIDATE FORMS

One of the useful ways that JavaScriptcan be used with forms is to validatethe form data before it is sent to the

server. If invalid values are identified andcorrected before making a server request, thenmany unnecessary server requests can beeliminated.

CGI scripts on the server can be used tovalidate form data, but using JavaScript tovalidate forms saves an extra trip or two to theserver and ensures the type of data the serverwill be receiving.

For example, you can validate a phone numberto make sure that it doesn’t include any letters.

The way to validate form data is different forevery type of data, but JavaScript includesmany operators that help you customize thevalidation routines.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

VALIDATE FORMS

VALIDATE FORMS

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a form with a text box.

‹ Create a function within the <script> tags that displays an alert dialog box if the value of the text box is unacceptable.

› Add an onchange event to the text box and assign it the function name.

ˇ Save the file as validate.html.

Á Open the validate.html file in a browser.

■ A single text box along with some text is displayed in the browser.

214

Page 231: Javascript Tutorial - 4730-5

‡ Type an invalid value in the text box.

° Press the Enter key. ■ An alert dialog box appears with a message for the user.

Several operators are used in JavaScript aspart of mathematical operations. In additionto the standard mathematical symbols for add(+), subtract (-), multiply (*), and divide (/),the != symbol means “not equal,” && means“and,” || means “or,” <= means “less than orequal to,” and >= means “greater than orequal to.”

Several string functions can also be used tovalidate form data. For example, if you wantto check to see if a specific word is containedwithin a text box or a textarea box, then youcould use indexOf() to search for a stringwithin a line of text.

215

WORKING WITH FORMS 12

Page 232: Javascript Tutorial - 4730-5

CONTROL FORM FOCUS

When a form element has focus, theuser can enter values into the formusing the keyboard.

For example, if a text box has the focus, youcan type data by using the keyboard, and thetyped characters will appear in the text box.

You can use the focus() method to changethe focus between the various form elements.For example, if a form named form1 includesa text box named text1, you can set thefocus to this text box by using the statementdocument.form1.text1.focus().

A similar method to focus() is the blur()method. Using this method, you can cause aform element to lose the focus. Associatedwith these two methods are two events thatcan be used to detect the focus and bluractions — onFocus and onBlur. Theseevents are covered in the next section, “UsingFocus Events.”

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

CONTROL FORM FOCUS

CHANGE FOCUS

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a form with a several text boxes and buttons.

‹ Add the onclick event to each button.

› Set the onclick event to change the focus to one of the text boxes.

ˇ Save the file as focus.html.

Á Open the focus.html file in a browser.

‡ Click one of the buttons.

° Type some text.

■ The text appears in the text box that has the focus.

216

Page 233: Javascript Tutorial - 4730-5

WORKING WITH FORMS

⁄ Open the file focus.html in Notepad.

¤ Change the focus() methods to blur().

‹ Save the file as blur.html.

› Open the blur.html file in a browser.

ˇ Click one of the buttons.

Á Type some text.

■ No text appears in any of the text boxes because they have lost the focus.

Radio buttons and check box buttons don’tinclude the blur() method because eachindividual radio button or check box buttonbelongs to a group and the browser cannotdetermine when a single item loses the focus.Radio buttons and check box buttons bothhave the focus() method, though, andpressing the Enter key when a radio button orcheck box button has the focus selects ordeselects the item.

The focus() method can be used to set thefocus to a specific form element. This can beuseful to automatically set the focus to the firstform element where the user needs to enterinformation.

217

USING BLUR

12

Page 234: Javascript Tutorial - 4730-5

USING FOCUS EVENTSUSING FOCUS EVENTS

DETECT FOCUS

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a form with several text boxes.

‹ Add the onFocus event to each text box.

› Set the onFocus event to change the text in the text box.

ˇ Save the file as onFocus.html.

Á Open the onFocus.html file in a browser.

‡ Click in one of the text boxes.

■ Some text is displayed in the text box that has the focus.

218

When a form element has focus, youcan enter the form data into the formusing the keyboard. You can give any

form element the focus by clicking on it withthe mouse or by using the Tab key.

When the user presses the Tab key, the focuswill move between the various form elements.The default order proceeds according to theorder that the form elements appear in theform, but you can set the order that each formelement receives the focus by using thetabindex attribute.

You can also detect when a form elementreceives or loses the focus by using theonFocus and onBlur events. The onFocusevent can be used on every form element, butthe onBlur event can only be used with theselect, option, text, password, andtextarea form elements.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

Page 235: Javascript Tutorial - 4730-5

WORKING WITH FORMS

° Open the file onFocus.html in Notepad.

· Change the onfocus events to onblur events and change the displayed text.

‚ Save the file as onBlur.html.

— Open the onBlur.html file in a browser.

± Click on one of the text boxes.

¡ Click in another text box.

■ The text box that lost the focus displays a message.

219

DETECT BLUR

12

One common use of the onFocus event is toselect the text in a text box when it gets thefocus. If you use onFocus to select text boxtext, the user doesn’t need to delete theexisting text; instead, the existing text will bereplaced with the new text when the userbegins to type. The functionality to select thetext when it receives the focus can be placedwithin the text and textarea boxes formelements like “”this:

<form name=“form1”>

<input type=“text” name=“text1”value=“default text”onfocus=“document.form1.text1.select()”/>

<textarea name=“ta1” value=“defaulttext”onfocus=“document.form1.ta1.select()”

</form>

When the various form elements get the focus,the onfocus event is fired causing theselect() method to be executed, which selectsthe text within the text box.

Page 236: Javascript Tutorial - 4730-5

WORK WITH THE FRAME OBJECT

Frames enable you to split a Web page upinto several different panes. The tricky partabout working with frames is to determine

which frame gets the focus and where thechanges caused by the JavaScript code appear.

The frame object includes many propertiesthat define the various frames. Theseproperties include frames, onBlur,onFocus, parent, self, top, and window.

The frames property is an array of all theframes included in the frameset. These framesare sub-objects of the parent object, and youcan reference them by an index value thatmatches the order that they appear in the

HTML file. For example, if a frameset includesthree frames, then the first frame could bereferenced as document.frames[0], thesecond one as document.frames[1], andthe third one as document.frames[2].

The frame object also includes severalmethods, such as open() and close(),which are the same as for the documentobject.

This example uses the skeleton.html andjs-skeleton.html files found on thebook’s CD-ROM, but you can apply thesesteps to any file.

WORK WITH THE FRAME OBJECT

WORK WITH THE FRAME OBJECT

JAVASCRIPT

⁄ Open the file skeleton.html in Notepad.

¤ Replace the <body> tags with a frameset page with two frames.

‹ Save the file as frameset.html.

› Open the file js-skeleton.html in Notepad.

ˇ Add a heading.

Á Within the <script> tags, add a document.write statement to display the frame’s name.

‡ Save the file as left.html.

220

Page 237: Javascript Tutorial - 4730-5

WORKING WITH FRAMES 13

° Open the file js-skeleton.html in Notepad.

· Add a heading.

‚ Within the <script> tags, add a document.write statement to display the frame’s name.

— Save the file as right.html.

± Open the frameset.html file in your browser.

■ Two frames appear with the frame name inside each.

Note: The left frame displays the file left.html, and the right frame displays the file right.html.

If you create a frameset and cannot see theframes, then you need to make sure that theWeb pages that you specify in the srcattributes for each frame are available. Youshould also check to make sure that the<frameset> tags replace the <body> tagsfor the frameset file. If the <body> tags existin the file, then the frames will not bevisible.

221

Because individual frames are simply one ofseveral windows that appear in the browser,frame objects can use all the properties andmethods used by the document andwindow objects. For example, you canaccess document properties for a frame forthe first frame on the page using thestatementparent.frame[0].document.title.

Page 238: Javascript Tutorial - 4730-5

ACCESS FRAMES BY NAME

Although you can reference a frame usingits index value such asparent.frames[0], you can also

reference a frame using its name as defined bythe name attribute of the <frame> tag.

For example, if you name a frame frame1,then you could reference the frame asparent.frame1.

You can also reference the frame using theframes array by replacing the index valuewith the name value in quotation marks likethis: parent.frames[“frame1”].

After you create the frame, it acts like astandard window. document objects and allthe properties and methods of the standarddocument object are available. For example,you can reference the frame title of a framenamed frame1 with a statement like this:parent.frame1.document.title.

This example uses the skeleton.html andjs-skeleton.html files found on thebook’s CD-ROM, but you can apply thesesteps to any file.

ACCESS FRAMES BY NAME

JAVASCRIPT

⁄ Open the file skeleton.html in Notepad.

¤ Replace the <body> tags with a frameset page with two frames.

‹ Save the file as frameset2.html.

› Open the file js-skeleton.html in Notepad.

ˇ Specify a background color in the <body> tag.

Á Add a heading.

‡ Within the <script> tags, add a document.write statement to display the frame’s background color.

° Save the file as left2.html.

222

ACCESS FRAMES BY NAME

Page 239: Javascript Tutorial - 4730-5

· Open the file js-skeleton.html in Notepad.

‚ Specify a background color in the <body> tag.

— Add a heading.

± Within the <script> tags, add a document.write statement to display the frame’s background color.

¡ Save the file as right2.html.

™ Open the frameset2.html file in your browser.

■ Two frames appear with the frame’s background color in each.

Note: The left frame displays the file left2.html, and the right frame displays the file right2.html.

223

WORKING WITH FRAMES 13

The Status bar properties are only availablefor the parent frame. If specified for the otherframes, the Status bar properties are ignored.

Although frames extend from a parent object,you can reference any child frame object fromany other child frame object. For example, ifyou have a page with three frames namedframe1, frame2, and frame3, then fromthe file that is loaded into frame1, you canreference the title property for frame2using the following statement:

parent.frame2.document.title;

and the title property for frame3 using thisstatement:

parent.frame3.document.title;

Using this method, you can use one frame tocontrol the other frames on the page.

Page 240: Javascript Tutorial - 4730-5

For a given frameset, you can determinethe number of frames that it includes byusing the length property.

You can reference this property from theparent object. This property returns thenumber of frames.

For example, for a frameset with three frames,the parent.frames.length propertywould return a value of 3.

This example uses the frameset2.html andright2.html files found on the book’s

CD-ROM (or which you may have created inthe section “Access Frames by Name”), butyou can apply these steps to any file.

FIND THE NUMBER OF FRAMES

JAVASCRIPT

⁄ Open the file frameset2.html in Notepad.

¤ Change right2.html to right3.html.

‹ Save the file as frameset3.html.

› Open the right2.html file in Notepad.

ˇ Change the document.write statement to display the number of frames.

Á Save the file as right3.html.

‡ Open the file frameset3.html in your browser.

■ Two frames and the value of the number of frames appear.

224

FIND THE NUMBER

OF FRAMESThe length property can be used todetermine the number of childrenframes that are contained within thecurrent frame. For example, if aframe named myFrame includesthree additional frames within it, thenthe statement self.length willreturn a value of 3.

Page 241: Javascript Tutorial - 4730-5

⁄ Open the file frameset2.html in Notepad.

¤ Change left2.html to left4.html.

‹ Save the file as frameset4.html.

› Open the left2.html file in Notepad.

ˇ Change the document.write statement to display the background color using the self object.

Á Save the file as left4.html.

‡ Open the frameset4.html in your browser.

■ Two frames and the value of the background color appear.

The top object is the same as theparent object for framescontained within a frameset. Fornested framesets, though, the topobject always refers to the top-most frameset.

225

WORKING WITH FRAMES

You can always reference the current frameusing the self object. The parentobject refers to the frameset object that

calls the current frame, but the self objectrefers to the current frame.

For example, if you have a frame namedframe1 and you are writing the code for thisframe, then you can refer to the title for thisframe using self.document.title ratherthan parent.frame1.document.title.

Using the self object reference is shorter andmore intuitive.

This example uses the frameset2.html andleft2.html files found on the book’sCD-ROM (or which you may have created inthe section “Access Frames by Name”), butyou can apply these steps to any file.

REFERENCE THE CURRENT FRAME

13

REFERENCE THE CURRENT FRAMEREFERENCE THE CURRENT FRAME

Page 242: Javascript Tutorial - 4730-5

Using the frame’s array, you can accessall the elements included on a separatepage, such as form elements.

For example, if you have a frameset with twoframes named frame1 and frame2, then youcan reference a text field contained withinframe1 from frame2 with a statement suchas this:parent.frame1.document.forms[0].text1.value.

For nested framesets, this can become a littletricky. To access frames within the sameframeset, you can use the parent keyword,

which contains all the child frames for theframeset. To access frames outside of thecurrent frameset, you can use the topkeyword to get to the top-most frameset. Fromthe top frameset, you can access the childrenframes.

This example uses the skeleton.html andjs-skeleton.html files found on thebook’s CD-ROM, but you can apply thesesteps to any file.

REFERENCE ACROSS FRAMES

JAVASCRIPT

⁄ Open the file skeleton.html in Notepad.

¤ Replace the <body> tags with a frameset page with two frames.

Note: In this example, the rows attribute is used within the <frameset> tag to place the frames on top of one another.

‹ Save the file as crossref.html.

› Open the file js-skeleton.html in Notepad.

ˇ Add a form with a text box.

Á Save the file as topform.html.

226

REFERENCE ACROSS FRAMES

Page 243: Javascript Tutorial - 4730-5

‡ Open the file js-skeleton.html in Notepad.

° Add a form with a text box and a button.

· Add the onclick event to the button and assign it to retrieve the text from the top frame.

‚ Save the file as bottomform.html.

— Open the crossref.html file in your browser.

± Add some text to the text box in the top frame.

¡ Click the button in the bottom frame.

■ The text in the bottom text box appears in the bottom frame.

After you open a new window, you can nameit. You can then use this name to access theproperties and methods of the new window.For example, if you open a new windownamed window1, then you can get its titleusing the window1.document.titlestatement. Frames, on the other hand, arecontained within framesets. Therefore, youneed to access frames using their parentframeset, which is accomplished using astatement likeparent.frame1.document.title.

The only real difference between frames that areside by side and frames that are above oneanother is the attribute that is included in the<frameset> tag. The first frame will always beon top for the rows attribute and to the left forthe cols attribute.

227

WORKING WITH FRAMES 13

Page 244: Javascript Tutorial - 4730-5

When you send text to be displayed in aframe, you need to make sure that the frameis created before you try to send text to it. Ifyour browser cannot find the frame that youare referencing because you didn’t create it,then the browser sends an error.

WRITE TO A SEPARATE FRAME

Throughout the book, the document.writestatement has been used to display text. Thistext appears within the current document

window, but by using frame references, you canwrite text to another window.

For example, if you have a frameset with twoframes named frame1 and frame2, then youcould write the statementparent.frame2.document.write(“welcome”) within the code forframe1. This statement would write the wordwelcome in the second frame.

You could still use the document.writestatement to display text in the current frame.

This example uses the frameset2.html andleft2.html files found on the book’s CD-ROM(or which you may have created in the section“Access Frames by Name”), but you can applythese steps to any file.

WRITE TO A SEPARATE FRAME

JAVASCRIPT

⁄ Open the file frameset2.html in Notepad.

¤ Change left2.html to writeframe.html.

‹ Save the file as write.html.

› Open the left2.html file in Notepad.

ˇ Change the document.write statement to reference the other frame.

Á Save the file as writeframe.html.

‡ Open the write.html file in your browser.

■ Two frames appear, and the code for the left frame displays text in the right frame.

228

WRITE TO A SEPARATE FRAME

Page 245: Javascript Tutorial - 4730-5

⁄ Open the file frameset2.html in Notepad.

¤ Add the onResize event to the first frame and assign it to display some text in the left frame.

‹ Save the file as onresize.html.

› Open the onresize.html file in your browser.

ˇ Resize the frames by dragging the bar that separates them.

■ Text appears in the left frame.

229

WORKING WITH FRAMES

The frame object identifies standard events,including onBlur and onFocus. It also can beused with two unique events — the onMove andonResize events. These events can be added tothe <frame> tags within the frameset file.

When referencing frames from the frameset file,you need to use self and the name of the framebecause the frameset file is the parent.

This example uses the frameset2.html filefound on the book’s CD-ROM (or which you mayhave created in the section “Access Frames byName”), but you can apply these steps to any file.

DETECT FRAME RESIZING

The onMove event fires whenever thewindow is moved. Because all framesare contained within a single browserpage, all frames will detect an onMoveevent at the same time. The onResizeevent only occurs when you resize theframe. Two frames will always detect thisevent at the same time.

DETECT FRAME RESIZINGDETECT FRAME RESIZING

13

Page 246: Javascript Tutorial - 4730-5

SET THE TARGET FRAMEWeb page elements including forms and linkscan include a target attribute. This attributeis the name of a frame where the results of theform or the link should be displayed.

Using JavaScript, you can view the targetvalue using the target property of the frameobject. You can also set the target valuedynamically.

This example uses the crossref.html andtopform.html files found on the book’sCD-ROM (or which you may have created inthe section “Reference across Frames”), butyou can apply these steps to any file.

SET THE TARGET FRAME

JAVASCRIPT

⁄ Open the file crossref.html in Notepad.¤ Change topform.html to targetframe.html.‹ Save the file as target.html.› Open the topform.html file in Notepad.ˇ Move the form above the <script> tags.

Á Add the target attribute to the form.

‡ Add a document.write statement to display the target value.

° Save the file as targetframe.html.

· Open the target.html file in your browser.

■ Two frames and the target name appear.

Note: The target name identifies where the linked Web page will load.

230

SET THE TARGET FRAME

When working with links,you can set a target valuewhere the Web link willload. This is useful forcreating a navigation bar inone frame that contains atarget to another framewhere the link pages areloaded.

Page 247: Javascript Tutorial - 4730-5

⁄ Open the file crossref.html in Notepad.

¤ Change bottomform.html to printframe.html.

‹ Save the file as print.html.

› Open the bottomform.html file in Notepad.

ˇ Change the button’s text.

Á Add a statement to the onclick event to print the frame.

‡ Save the file as printframe.html.

° Open the file print.html in your browser.

· Click the button.

■ The Print dialog box opens.

231

WORKING WITH FRAMES

Another useful method of the frame object is theprint() method. This method enables you to print asingle frame.

The print() method opens the print dialog box for yoursystem. You need to click OK in this dialog box to actuallysend the page to the printer.

This example uses the crossref.html andbottomform.html files found on the book’s CD-ROM (orwhich you may have created in the section “Referenceacross Frames”), but you can apply these steps to any file.

PRINT A FRAME

To print the entire pageincluding all frames, youcan use the followingstatement:

parent.print();

13

PRINT A FRAMEPRINT A FRAME

Page 248: Javascript Tutorial - 4730-5

USING THE NAVIGATOR OBJECT

Some of the most helpful objects enableyou to detect the type of system that theuser is using to view your page. By

detecting these environment properties, youcan customize your content appropriately.

For example, some JavaScript features aredifferent between the Microsoft InternetExplorer and Netscape Navigator browsers.Detecting the browser that is being used letsyou use different features, depending on thebrowser type.

The navigator object includes manyproperties and methods required to determinethe user’s system. The navigator objectproperties include appCodeName, appName,appVersion, platform, and userAgent.

The navigator object method isjavaEnabled(). The properties of thenavigator object are described in thesection “Detect a User’s Browser.”

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING THE NAVIGATOR OBJECT

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Add several document.write statements to display the values of the navigator object properties.

‹ Save the file as navigator.html.

› Open the file navigator.html in a browser.

■ All the properties of the navigator object are displayed.

Note: Internet Explorer version 5 will still return a version number of 4.0 because this is the version number for the last major engine release by Microsoft.

232

USING THE NAVIGATOR OBJECT

Page 249: Javascript Tutorial - 4730-5

DETERMINING ENVIRONMENT PROPERTIES

ˇ Open the file navigator.html in Notepad.

Á Replace the property definition with the navigator method.

‡ Save the file as navigator2.html.

° Open navigator2.html in a browser.

■ The value of each navigator object method is displayed.

233

Some navigator object properties are read-only properties, such as the languageproperty. If the language property were nota read-only property, then you would be ableto change the scripting language at any time,which would confuse the browser.

Many different pieces make up the user’senvironment, including the computer, theoperating system, the browser, and the Webpage. Each of these pieces can be controlledto an extent using JavaScript objects. Thecomputer, operating system, and browsercan all be detected using the navigatorobject, and the Web page URL can bedetected using the location object. Theseobjects are covered in the sections “Usingthe navigator Object” and “Using thelocation Object.”

14

Page 250: Javascript Tutorial - 4730-5

DETECT A USER’S BROWSER

By detecting the user’s browser, you can alterthe content as needed for his or her specificformat. For example, much of the Dynamic

HTML syntax is different for different browsertypes.

The navigator object includes three propertiesthat return the type of browser. TheappCodeName property returns the code name ofthe browser. This is typically Mozilla, which isthe standard code base. The appName propertyreturns the actual browser name, such asMicrosoft Internet Explorer. The appVersionproperty returns the version information orversion number for the browser, such as 5.0.

DETECT A USER’S BROWSER

JAVASCRIPT

234

The main two browser types areMicrosoft’s Internet Explorer andNetscape’s Navigator, but otherbrowsers exist, such as Lynx, atext-only browser, and AOL’scustom browser. These otherbrowsers will have a differentidentifying name, but the codename will probably be similar.

⁄ Open the file js-skeleton.html from the CD-ROM in Notepad.

¤ Add an if statement to check for the word Microsoft within the navigator.appName value.

‹ Include an else if statement that, if Microsoft is not found, checks to see if Netscape can be found.

Note: If the browser is neither a Microsoft nor a Netscape product, then nothing will be displayed.

› Save the file as appName.html.

ˇ Open the file appName.html in a browser.

■ The browser type is detected and displayed.

DETECT A USER’S BROWSER

Page 251: Javascript Tutorial - 4730-5

The earliest versions to useJavaScript were the Netscape2.0 and Internet Explorer 3.0versions. Browsers prior tothese versions cannot interpretJavaScript code.

235

The different browser versions support differing levelsof HTML. For example, the early 3.0 browser versionsonly supported HTML Version 3.2.

Later versions supported later HTML specifications. If youuse a feature in a later HTML version with a browser thatdoesn’t support it, the results can be unexpected.

To eliminate any problems, you can check for the currentbrowser version number using thenavigator.appVersion property.

This example uses the js-skeleton.html file found onthe book’s CD-ROM, but you can apply these steps to anyfile.

DETECT THE BROWSER’S VERSION

⁄ Open the file js-skeleton.html in Notepad.

¤ Add an if statement to check for a specific version number.

‹ Include an else statement that executes if the specified version number isn’t found (including versions that have a higher version number).

› Save the file as appVersion.html.

ˇ Open appVersion.html in a browser.

■ The browser version is detected, and a message is displayed.

DETERMINING ENVIRONMENT PROPERTIES 14

DETECT THE BROWSER’S VERSIONDETECT THE BROWSER’S VERSION

Page 252: Javascript Tutorial - 4730-5

JAVASCRIPT

236

JavaScript can identify the mostcommon operating systems,such as Win32, which includesall Windows 95, Windows 98,Windows Me, Windows NT,and Windows 2000computers; Macintosh, whichincludes older systems, PowerPC, and later versions; andUNIX, which includes thepopular Linux version.

Understanding the user’s operatingsystem helps you to know what type ofinterfaces he or she is most comfortable

with. Macintosh interfaces are different fromWindows and UNIX interfaces.

You can detect a user’s operating system usingthe platform property of the navigatorobject. This property returns the platform forwhich the browser was compiled.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

⁄ Open the file js-skeleton.html in Notepad.

¤ Add an if statement to check for the platform to determine the operating system.

‹ Include an else statement that executes if the specified platform isn’t found.

› Save the file as platform.html.

ˇ Open the file platform.html in a browser.

■ The user’s operating system platform is detected and displayed.

DETECT A USER’S OPERATING SYSTEM

DETECT A USER’S OPERATING SYSTEMDETECT A USER’S OPERATING SYSTEM

Page 253: Javascript Tutorial - 4730-5

⁄ Open the file js-skeleton.html in Notepad.

¤ Add an if statement to check for specific environment properties.

‹ Include an else statement that executes if the specified properties aren’t found.

› Save the file as userAgent.html.

ˇ Open the file userAgent.html in a browser.

■ The browser type and operating system are detected and displayed.

When a request is sent tothe server, part of therequest includes a header.This header is informationabout where the requestcame from and whatinformation is needed tosatisfy the request.

237

The userAgent property of the navigator objectreturns the header information that is sent to theserver during a request by the browser.

The information in the header includes the sameinformation in the appVersion property plus theinformation from the appCodeName property.

This example uses the js-skeleton.html file found onthe book’s CD-ROM, but you can apply these steps to anyfile.

UNDERSTAND A USER AGENT

DETERMINING ENVIRONMENT PROPERTIES 14

UNDERSTAND A USER AGENTUNDERSTAND A USER AGENT

Page 254: Javascript Tutorial - 4730-5

DETERMINE WHETHER JAVA ISENABLED

Java is a programming language that enablesdevelopers to program applications thatwork with the browser over the Web.

Browsers have the option of enabling ordisabling this feature. If Java is disabled, noJava content will run within the browser.

The navigator object includes a method fordetermining whether Java is enabled for thebrowser. This method is javaEnabled(). Itreturns either a true or a false value.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

DETERMINE WHETHER JAVA ISENABLED

JAVASCRIPT

238

DETERMINE WHETHER JAVA IS ENABLED

Java can be enabled or disabledusing the browser settings. Thereason why you would want tocheck to see if Java is enabled is thatJava components are typically ratherlarge and downloading them couldtake a long time. If Java isn’tenabled, you can save the user sometrouble.

⁄ Open the file js-skeleton.html in Notepad.

¤ Add an if statement to check whether Java is enabled.

‹ Include an else statement that executes if Java isn’t enabled.

› Save the file as javaEnabled.html.

ˇ Open the file javaEnabled.html in a browser.

■ The script detects whether Java is enabled on the browser and displays the results.

Page 255: Javascript Tutorial - 4730-5

All browsers return thesame code name becausethey are all based from thesame basic functioningcode. Differentimplementations will havedifferent code names.

239

The appCodeName property returns the name of thecode used by the browser. This value represents abaseline of functionality.

Both Microsoft’s Internet Explorer and Netscape’s Navigatorbrowsers return the value of Mozilla for this value. Thisis the developer’s name for the browser code.

This example uses the js-skeleton.html file found onthe book’s CD-ROM, but you can apply these steps to anyfile.

DETERMINE THE CODE NAME

⁄ Open the file js-skeleton.html in Notepad.

¤ Add an if statement to check the code name.

‹ Include an else statement that executes if the specified code name isn’t found.

› Save the file as appCodeName.html.

ˇ Open appCodeName.html in a browser.

■ The script detects and displays the code name.

DETERMINING ENVIRONMENT PROPERTIES 14

DETERMINE THE CODE NAMEDETERMINE THE CODE NAME

Page 256: Javascript Tutorial - 4730-5

USING THE LOCATION OBJECT

The location object includes properties thathold every piece of information that makes up aURL. These properties are very similar to the

link object properties.

These properties include hash, host, hostname,href, pathname, port, protocol, and search.All these properties return information about thecurrent URL.

The first part of a URL is the protocol. Theprotocol property defines the protocol type, suchas HTTP (Hypertext Transfer Protocol) or FTP (FileTransfer Protocol). The hostname property returnsthe domain name, and the port property returnsthe port if one is included. The host property

returns the host name and the port number together.The path to the file is returned by the pathnameproperty.

At the end of the URL comes the hash or searchinformation. The hash property defines any anchornames included in the URL. These are identified withthe numeric symbol (#). The search propertyreturns any information passed to the server, whichfollows after the question mark (?).

The location object also includes the reload()method, which reloads the current URL.

This example uses the js-skeleton.html filefound on the book’s CD-ROM, but you can applythese steps to any file.

USING THE LOCATION OBJECT

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Add several document.write statements to display the values of the location object properties.

‹ Save the file as location.html.

› Open the file location.html in a browser.

■ All the properties of the location object are displayed.

240

DISPLAY THE LOCATION OBJECT PROPERTIES

Page 257: Javascript Tutorial - 4730-5

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a form with a button.

‹ Add the onclick event to the button and set it equal to the reload() method.

› Save the file as location2.html.

ˇ Open the location2.html file in a browser.

Á Click the button.

■ The page is reloaded.

241

DETERMINING ENVIRONMENT PROPERTIES 14

RELOAD A PAGE

Using the location object, entire URLs canbe divided into their base components. Thisenables you to manipulate URLs as needed. Afunction to deconstruct a URL would look likethis:

function decomposeURL() {

address = location.href;

prot = location.protocol;

domain = location.hostname;

prt = location.port;

path = location.pathname;

anchor = location.hash;

search = location.search;

document.write(“Current URL: “ +prot + domain + prt + path +anchor + search);

}

This function splits the URL into its separatecomponents. Each separate component can bereplaced as needed.

Page 258: Javascript Tutorial - 4730-5

USING COOKIES

Cookies are small pieces of data that helpmaintain the state of the browser. Theyare written to the user’s computer and

are indexed by the site that creates them.When the user returns later to the site, thedata is retrieved and used.

One common use of cookies is to keepinformation about the user’s preferences.Saving a user’s preferences in a cookie willenable the browser to read the cookie anddisplay the Web page according to the user’sspecifications the next time he or she returns.

To write a cookie using JavaScript, you use thedocument.cookie object. By setting thisobject equal to the piece of data that you wantto save, the cookie is automatically written tothe user’s computer. Each piece of data savedin a cookie should have a name and an equalsign so that it can be identified and retrievedlater.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

USING COOKIES

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a function within the <script> tags.

‹ Within the function brackets, add an if statement to check if a cookie exists.

› Also within the function, add a JavaScript statement that creates a prompt dialog box and sets the value to document.cookie.

ˇ Create two variables to locate the start and end positions of the cookie value.

Á Add a JavaScript statement to write the cookie value to the browser.

‡ Add the onload event to the <body> tag and set it equal to the function name.

° Save the file as cookie.html.

242

USING COOKIES

Page 259: Javascript Tutorial - 4730-5

· Open the file cookie.html in a browser.

■ A dialog box appears.

‚ Type a name in the text box.

— Click the OK button.

■ The name is displayed in the browser.

Browsers include settings for disablingcookies if you don’t want them stored onyour computer. For Internet Explorer, you candisable cookies by selecting theTools➪ Internet Options command. Thiscommand opens the Internet Options dialogbox. Select the Security tab and click theCustom Level button. Then select the Disableradio button under the Cookies heading(❍ changes to ● ).

Any string can be included within a cookie, butall cookies need to include a name and a value.The cookie file has a size limitation of 4KB. Ifthe string saved to a cookie is larger than this,then a portion of the cookie data will be lost.

243

DETERMINING ENVIRONMENT PROPERTIES 14

Page 260: Javascript Tutorial - 4730-5

ENCODE CHARACTERS

When some characters such as spacesand certain symbols are passed to theserver, they are confused for server

commands. This can result in incorrectprocessing of data. JavaScript includes twostatements that can be used to encode thecharacters before they are sent to the server.When the encoded characters are received bythe server, they can be unencoded to retrievethe data. This process of encoding anddecoding data ensures the integrity of the data.

The statement to encode a character isescape(). This statement accepts a singlestring, which is the text to encode.

The text is encoded by converting it to apercentage symbol (%) followed by a two-digitASCII value. For example, a space isrepresented by the ASCII value of 20, and anampersand symbol (&) is represented by theASCII value of 26, so the statementescape(“& “) would encode to “%26%20”.

Text received in the encoded format can bedecoded using the unescape() statement.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

ENCODE CHARACTERS

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Assign a string to a variable.

‹ Add document.write() statements to display the initial value of the string and the value of the string encoded.

› Save the file as escape.html.

ˇ Open the file escape.html in a browser.

■ A string and its escaped equivalent are displayed.

244

ENCODE TEXT

Page 261: Javascript Tutorial - 4730-5

14

⁄ Open the file escape.html in Notepad.

¤ Assign the escaped string to a variable.

‹ Add a document.write() statement to display the value of the string decoded.

› Save the file as unescape.html.

ˇ Open the file unescape.html in a browser.

■ An encoded string and its unescaped equivalent are displayed.

If your Web page filename includes anyspaces, then links to the Web page will not beable to locate the Web page name. If youencode the URL by using the escape()statement, then you will be able to use thename with spaces.

The escape() and unescape() statementsare not a part of any object, but are JavaScriptkeywords. They do not need any parentobject in order to work correctly.

The escape() and unescape() statementscan be used on single characters, full lines oftext, or even paragraphs.

Because the type of encoding used byescape() is based on the ASCII character set,it cannot be used with Unicode characters.

245

DETERMINING ENVIRONMENT PROPERTIES

DECODE TEXT

Page 262: Javascript Tutorial - 4730-5

As scripts are created, the syntax must befollowed exactly to avoid generating anerror. Debugging is the process of

identifying and eliminating errors.

Several different types of errors can happen.Syntax errors occur when you use syntax thatthe browser can’t understand, such asmisspelling a keyword or variable. Runtimeerrors are harder to detect. They occur whenthe script’s syntax is correct but the programdoesn’t do what it should. An example of thisis using a wrong equation.

Syntax errors are the easiest to detect becausethe browser lets you know that an error hasoccurred. Runtime errors are harder to find butcan be found with some careful debuggingtechniques.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a couple of document.write statements within the <script> tags.

‹ Misspell the word document in one statement to cause a syntax error.

› Save the file as error.html.

ˇ Open the file error.html in a browser.

■ The page loads, but the status bar displays an error.

Note: The error dialog box includes an Always Display This Message When a Page Contains Errors check box. If you checked this at some earlier time, then the error dialog box appears automatically.

246

DETECT JAVASCRIPT ERRORS

DETECT JAVASCRIPT ERRORSDETECT JAVASCRIPT ERRORS

Page 263: Javascript Tutorial - 4730-5

DEBUGGING JAVASCRIPT

Á Double-click the warning icon in the status bar.

■ The JavaScript error dialog box appears.

‡ Click the Show Details button. (The button label then changes to Hide Details.)

■ The details of the error are displayed.

247

In the error dialog box is a check box thatyou can check to cause the error dialog boxto appear automatically every time thebrowsers detects an error on the currentpage.

If you view the details in the error dialogbox, it includes the line and character wherethe syntax error appears. Using thisinformation, you can locate exactly wherethe syntax error is.

The error dialog box has two buttons used tocycle through the errors. Click the Previousbutton to see the previous error or the Nextbutton to the see the next error.

15

Page 264: Javascript Tutorial - 4730-5

DEBUG WITH COMMENTS

One of the first tasks when debuggingyour script is to determine what worksand what does not. If you correctly

identify the statements that are causing theerror, then you can work to fix it.

The easiest way to locate JavaScript statementsthat work is to use comments. Comments arelines of the script that aren’t executed. Theyare mainly used to document your script. Ifyou comment out a statement with an error,the rest of the page should work fine.

Comments can be added to a single line byplacing two slash marks (//) in front of the

line. These comment marks can be placed inthe middle of the line, which comments outeverything to the end of the line. Double slashmarks (//) affect only the line they are on.

Another way to comment out severalstatements at once is to use the /* and */marks. These marks comment out anystatements within them, even over multiplelines.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

DEBUG WITH COMMENTS

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a couple of document.write statements within the <script> tags.

‹ Misspell the word document to cause a syntax error.

› Comment out the statement with an error.

ˇ Save the file as comment.html.

Á Open the file comment.html in a browser.

■ The page loads, but the statement with an error has been removed with a comment, so no error appears in the Status bar.

248

USING SINGLE-LINE COMMENTS

Page 265: Javascript Tutorial - 4730-5

DEBUGGING JAVASCRIPT

⁄ Open the file comment.html in Notepad.

¤ Add another document.write() statement.

‹ Comment out the document.write statements with multiple-line comment marks instead of the slashes.

› Save the file as comment2.html.

ˇ Open the file comment2.html in a browser.

■ The page loads, but the statement with an error has been removed with a comment, so no error appears in the Status bar.

If only one bracket of a function statement isincluded in a commented statement, thescript produces an error. The same problemhappens if you include only one end of a setof quotes or parentheses in a commentedstatement.

The copy and paste functions can be used totemporarily remove and replace lines of code,but if you use Notepad to write scripts, the copybuffer remembers only a single line of code.Also, if you remove a large section of code, yourun the risk of losing the code.

249

USING MULTIPLE-LINE COMMENTS

15

Page 266: Javascript Tutorial - 4730-5

OUTPUT VALUES TO TEXT BOXES

Another common way to debug your scriptis to output the value of the variables thatyou are working with to a temporary

text box.

This method gives you a chance to examinethe value as the script is being executed. Forexample, if you include a for loop in yourscript, you can display the value of the loopvariables each time the loop is encountered.

Text boxes can be easily included within anyform on the page, or a new form can be

quickly added to the page to display thevalues.

You could add events to various elementswithin the page that display the values with thetext box when fired. This enables you tointeractively check variables as the script is run.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

OUTPUT VALUES TO TEXT BOXES

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a form with a temporary text box and a button.

‹ Within the <script> tag, add a variable and a function to count the number of button clicks and display the number in the temporary text box.

› Save the file as output.html.

ˇ Open the file output.html in a browser.

■ The page displays a temporary text box and a button.

Á Click the button.

250

OUTPUT VALUES TO TEXT BOXES

Page 267: Javascript Tutorial - 4730-5

■ The count variable is displayed in the text box.

‡ Continue to click the button.

■ For each click, the text box is updated.

251

DEBUGGING JAVASCRIPT 15

meters =document.form1.text1.value;

millimeters = meters*1000;

window.alert(“meters converted tomillimeters = “ + millimeters);

After the script is working, the singlewindow.alert statement can be removed.

Another common way to display variables inorder to debug your script is to use alertboxes. Alert boxes are convenient becausethey only take a single-line statement that canbe easily removed after the script is working.For example, if you have a script thatcomputes an intermediate value such as theconversion of meters to millimeters, an alertbox can be used to display the value of thevariable like this:

Page 268: Javascript Tutorial - 4730-5

COMMON JAVASCRIPT ERRORS

Scripts can generate errors many waysusing JavaScript, but some errors are morecommon than others.

One common error that exists in ifstatements is to use the assignment operator(=) instead of the equality operator (==). ifstatements should always include two equalsigns.

Another common way to err is to mismatchbrackets, quote marks, and parentheses. Youshould especially watch when including quotemarks (‘) within double-quote marks (“).

Object properties and methods are case-sensitive, so a property like bgColor will notwork if you forget to capitalize the C.

Another common error is to use properties,methods, and events that aren’t associatedwith a specific object. For example, if you tryto use the onclick event on a form object,the browser detects an error.

This example uses the js-skeleton.htmlfile found on the book’s CD-ROM, but you canapply these steps to any file.

COMMON JAVASCRIPT ERRORS

JAVASCRIPT

⁄ Open the file js-skeleton.html in Notepad.

¤ Add a document.write statement.

‹ Add an if statement to check and display the browser type.

› Incorrectly include only a single equal sign in the if statement.

ˇ Save the file as error2.html.

Á Open the file error2.html in a browser.

■ The error dialog box appears.

252

COMMON JAVASCRIPT ERRORS

Page 269: Javascript Tutorial - 4730-5

‡ Open the error2.html file in Notepad.

° Fix the if statement by adding another equal sign.

· Incorrectly add a single bracket at the end of the if statement.

‚ Save the file as error3.html.

— Open error3.html in a browser.

■ The error dialog box appears.

253

DEBUGGING JAVASCRIPT 15

and locate its partner. These editors also checkthe spelling of keywords to prevent spellingerrors. Good scripting habits like aligning yourbrackets and indenting code help to make yourcode easier to debug and follow.

Certain text editors such as Allaire HomeSiteand Macromedia Dreamweaver can check forsome common errors such as misplacedbrackets. These editors keep track of everyquote and bracket that you type, and when anending bracket or quote is missing, the textappears red until it is entered. You can alsoselect a single bracket or quote, press a key,

Page 270: Javascript Tutorial - 4730-5

JAVASCRIPT

254

This reference is based on the HTML 4.01specification published online atwww.w3c.org. This reference does not

include the deprecated (or discontinued)elements. It also does not include framedefinitions.

COMMON ATTRIBUTES

These common attributes are used across many different elements as indicated. They are divided into threegroupings — core, language, and events.

Attribute Description Acceptable ValuesCore Attributes

id Element ID.class Defines a style sheet class.style Defines inline style sheets.title Provides a title to the element.

Language Attributeslang Indicates primary language.dir Defines text direction. ltr and rtl

Event Attributesonclick Element was clicked.ondblclick Element was double clicked.onmousedown Mouse button was pressed.onmouseup Mouse button was released.onmouseover Cursor was moved over an element.onmousemove Cursor was moved.onmouseout Cursor was moved off an element.onkeypress Keyboard key was pressed.onkeydown Keyboard key was pressed down.onkeyup Keyboard key was released.

Page 271: Javascript Tutorial - 4730-5

HTML 4.01 REFERENCE

255

DOCUMENT STRUCTURE ELEMENTS

These elements compose the major sections of a Web page, including the root <html> tags, the head, and the body.Attribute Description

<HTML> . . . </HTML> (supports common language attributes)version Specifies a DTD.

<HEAD> . . . </HEAD> (supports common language attributes)profile Locates separate meta data file.

<BODY> . . . </BODY> (supports common core, language, and event attributes)onload Document was loaded.onunload Document was unloaded.

HEAD ELEMENTS

The following tags can be included within the head section of a Web page. These tags can appear multipletimes within the head section.

Attribute Description Acceptable Values<TITLE> . . . </TITLE> (supports common language attributes)

<BASE/>href Location of base.

<META/> (supports common language attributes)http-equiv Response header.

name Meta information name.

content Information for name.

scheme Meta data interpretation scheme.

<LINK/> (supports common core, language, and event attributes)charset The browser’s character set.

href Location of the link.

hreflang Language of the link.

type Content type of the link.

rel Forward link type.

rev Reverse link type.

media Specifies media type.

A

Page 272: Javascript Tutorial - 4730-5

JAVASCRIPT

256

HEAD ELEMENTS CONTINUED

Attribute Description Acceptable Values

<SCRIPT> . . . </SCRIPT>charset The browser’s character set.

type Content type of the scripting language.

src Location of external script file.

defer Allows deferred execution of script. defer

<NOSCRIPT> . . . </NOSCRIPT> (supports common core, language, and event attributes)<STYLE> . . . </STYLE> (supports common language attributes)

type Content type of the style language.

media Specifies the media type.

title Title for the style.

<OBJECT> . . . </OBJECT> (supports common core, language, and event attributes)declare Declaration flag. declareclassid Identifies the class ID.codebase The object’s location.data Data passed to the object.type Content type of the object.codetype Content type of the code.archive Archived copy of the object.standby Standby message to show while loading.height Height of the object.width Width of the object.usemap Use client-side image map.name Reference name for the object.tabindex Tab order position.

<PARAM/>id Parameter ID.name Property name.value Property value.valuetype Defines value type. data, ref, and objecttype Content type of the value.

Page 273: Javascript Tutorial - 4730-5

HTML 4.01 REFERENCE A

257

HTML 4.01 REFERENCE

These elements support common core, language,and event attributes.Tag<P> . . . </P><DIV> . . . </DIV><ADDRESS> . . . </ADDRESS>

BLOCK ELEMENTS

HEADING ELEMENTS

There are six heading levels from H1 (the mostimportant) to H6 (the least important). These allshare the same attributes. The heading elementssupport common core, language, and eventattributes.

Tag<H1> . . . </H1>

<H2> . . . </H2>

<H3> . . . </H3>

<H4> . . . </H4>

<H5> . . . </H5>

<H6> . . . </H6>

PHRASE ELEMENTS

These elements mark text as emphasis, strong,definition, code, sample, keyboard, variable, cite,abbreviation, and acronym styles. These elementssupport common core, language, and eventattributes.

Tag<EM> . . . </EM>

<STRONG> . . . </STRONG>

<DFN> . . . </DFN>

<CODE> . . . </CODE>

<SAMP> . . . </SAMP>

<KBD> . . . </KBD>

<VAR> . . . </VAR>

<CITE> . . . </CITE>

<ABBR> . . . </ABBR>

<ACRONYM> . . . </ACRONYM>

Attribute Description<PRE> . . . </PRE> (supports common core, language,

and event attributes)widthWidth of the preformatted text.

PREFORMATTED TEXT ELEMENT

QUOTE ELEMENTS

Attribute Description<BLOCKQUOTE> . . . </BLOCKQUOTE>

<Q> . . . </Q> (supports common core, language, andevent attributes)

cite Location of the quote source.

These elements support common core, language,and event attributes.

Attribute Description<INS> . . . </INS><DEL> . . . </DEL>

cite Location of the source.

datetime Date and time of change.

INSERTED/DELETED TEXT ELEMENT

A

Page 274: Javascript Tutorial - 4730-5

JAVASCRIPT

258

These elements format text as teletype,italics, bold, big, or small. These elementssupport common core, language, and eventattributes.

Tag<TT> . . . </TT>

<I> . . . </I>

<B> . . . </B>

<BIG> . . . </BIG>

<SMALL> . . . </SMALL>

TEXT STYLE ELEMENTS

BIDIRECTIONAL OVERRIDE ELEMENT

Attribute Description Acceptable Values<BDO> . . . </BDO> (supports common core attributes)

lang Defines the language.

dir Defines the text direction. ltr and rtl

LIST ELEMENTS

These elements are used to create lists including definition, ordered, and unordered lists.

Attribute Description Acceptable Values<DL> . . . </DL>

<(DT)> . . . </DT><(DD)> . . . </DD> (supports common core, language, and event attributes)

<OL> . . . </OL> (supports common core, language, and event attributes)type Sets the numbering style. 1, a, A, i, and Istart Sets the list start value.

<UL> . . . </UL> (supports common core, language, and event attributes)type Sets the bullet style. disc, square, and circle

<LI> . . . </LI> (supports common core, language, and event attributes)type Sets the numbering or bullet style. 1, a, A, i, I, disc, square, and

circlevalue Sets the current list value.

These elements mark text as subscripts orsuperscripts. These elements support common core,language, and event attributes.

Tag<SUB> . . . </SUB>

<SUP> . . . </SUP>

SUBSCRIPT AND SUPERSCRIPT ELEMENTS

INLINE ELEMENT

This element supports common core, language,and event attributes.

Tag<SPAN> . . . </SPAN>

Page 275: Javascript Tutorial - 4730-5

259

LINE BREAK ELEMENT

This element supports common core attributes.

Tag<BR/>

HORIZONTAL RULE ELEMENT

This element supports commoncore, language, and eventattributes.

Tag<HR/>

HTML 4.01 REFERENCE

THE ANCHOR ELEMENT

Attribute Description Acceptable Values<A> . . . </A> (supports common core, language, and event attributes)

charset Character set to use.type Content type for the link.name Name of the anchor.href Location of the link.hreflang Language of the link.rel Forward link type.rev Reverse link type.accesskey Shortcut key.shape Client-side image map shape. default, rect, circle, and polycoords Client-side image map coordinates.tabindex Tab order position.onfocus Element has received the focus.onblur Element has lost the focus.

IMAGE ELEMENT

Attribute Description Acceptable Values<IMG/> (supports common core, language, and event attributes)

src Location of image.alt Alternative description.longdesc Location of long description.name Reference name of the image.height Image height.width Image width.usemap Use client-side image map.ismap Use server-side image map. ismap

A

Page 276: Javascript Tutorial - 4730-5

FORM ELEMENTS

Attribute Description Acceptable Values<FORM> . . . </FORM> (supports common core, language, and event attributes)

action Server-side form handler.method HTTP submission method. get and postenctype URL encoding type.accept Acceptable MIME types.name Reference name of form.onsubmit Form was submitted.onreset The form was reset.accept-charset Supported character sets.

<LABEL> . . . </LABEL> (supports common core, language, and event attributes)for Field ID value.accesskey Shortcut key.onfocus Element has received the focus.onblur Element has lost the focus.

<INPUT/> (supports common core, language, and event attributes)type Type of input field. text, password, checkbox,

radio, submit, reset, file,hidden, image, and button

name Reference name.

JAVASCRIPT

260

Attribute Description Acceptable Values<MAP> . . . </MAP> (supports common core, language, and event attributes)

name Reference name for the map.<AREA/> (supports common core, language, and event attributes)

shape Client-side image map shape. default, rect, circle, andpoly

coords Client-side image map coordinates.href Location of the link.nohref Specifies no link. nohrefalt Alternative description.tabindex Tab order position.accesskey Shortcut key.onfocus Element has received the focus.onblur Element has lost the focus.

CLIENT-SIDE IMAGE MAP ELEMENTS

Page 277: Javascript Tutorial - 4730-5

HTML 4.01 REFERENCE

261

FORM ELEMENTS CONTINUED

Attribute Description Acceptable Valuesvalue Value for the input field.checked Marks when radio buttons and checked

check boxes are selected.disabled Disables the form element. disabledreadonly For passwords; allows read mode only. readonlysize Specifies the size of the field.maxlength Maximum length of a text field.src Location of the image.alt Alternative description.usemap Use client-side image map.ismap Use server-side image map. ismaptabindex Tab order position.accesskey Shortcut key.onfocus Element has received the focus.onblur Element has lost the focus.onselect Some text was selected.onchange The element value was changed.accept Acceptable MIME types.

<SELECT> . . . </SELECT> (supports common core, language, and event attributes)name Reference name.size Number of visible rows.multiple Allows multiple selection items. multipledisabled Disables the form element. disabledtabindex Tab order position.onfocus Element has received the focus.onblur Element has lost the focus.onchange The element value was changed.

<OPTGROUP> . . . </OPTGROUP> (supports common core, language, and event attributes)disabled Disables the form element. disabledlabel Labels the element.

<OPTION> . . . </OPTION> (supports common core, language, and event attributes)selected Item is selected. selecteddisabled Disables the form element. disabledlabel Labels the element.value Item value.

A

Page 278: Javascript Tutorial - 4730-5

JAVASCRIPT

262

FORM ELEMENTS CONTINUED

Attribute Description Acceptable Values<TEXTAREA> . . . </TEXTAREA> (supports common core, language, and event attributes)

name Reference name.rows Defines the number of rows.cols Defines the number of columns.disabled Disables the form element. disabledreadonly For passwords; allows read mode only. readonlytabindex Tab order position.accesskey Shortcut key.onfocus The element received the focus.onblur The element has lost the focus.onselect Some text was selected.onchange The element value was changed.

<FIELDSET> . . . </FIELDSET> (supports common core, language, and event attributes)<LEGEND> . . . </LEGEND> (supports common core, language, and event attributes)

accesskey Shortcut key<BUTTON> . . . </BUTTON> (supports common core, language, and event attributes)

name Reference name.value Button value.type Type of button. button, submit, and resetdisabled Disables the form element. disabledtabindex Tab order position.accesskey Shortcut key.onfocus Element has received the focus.onblur Element has lost the focus.

TABLE ELEMENTS

Attribute Description Acceptable Values<TABLE> . . . </TABLE> (supports common core, language, and event attributes)

summary Brief table summary.width Table width.border Defines border width.frame Defines render frame.rules Places rules between rows and columns.cellspacing Spacing between cells.

Page 279: Javascript Tutorial - 4730-5

HTML 4.01 REFERENCE A

263

TABLES ELEMENTS CONTINUED

Attribute Description Acceptable Valuescellpadding Spacing within cells.

<CAPTION> . . . </CAPTION> (supports common core, language, and event attributes)<COLGROUP> . . . </COLGROUP>

<COL> . . . </COL> (supports common core, language, and event attributes)span Number of columns in a span.width Column width.align Horizontal alignment. left, center, right, justify,

and charchar Alignment character.charoff Character offset.valign Vertical alignment. top, middle, bottom, and

baseline<THEAD> . . . </THEAD><TBODY> . . . </TBODY><TFOOT> . . . </TFOOT>

<TR> . . . </TR> (supports common core, language, and event attributes)align Horizontal alignment. left, center, right, justify,

and charchar Alignment character.charoff Character offset.valign Vertical alignment. top, middle, bottom, and

baseline<TH> . . . </TH>

<TD> . . . </TD> (supports common core, language, and event attributes)abbr Header abbreviation.axis List of headers.headers List of header cells IDs.scope Scope of header cells.rowspan Number of rows spanned by cell.colspan Number of columns spanned by cell.align Horizontal alignment. left, center, right,

justify, and charchar Alignment character.charoff Character offset.valign Vertical alignment. top, middle, bottom, and

baseline

Page 280: Javascript Tutorial - 4730-5

JAVASCRIPT

264

SYSTEM REQUIREMENTSTo use the contents of the CD-ROM, your computermust be equipped with the following hardware andsoftware:

• A PC with a Pentium 133 MHz or fasterprocessor or a Mac OS computer with a 68040or faster processor.

• Microsoft Windows 95 or later, Windows NT 4 orlater or Mac OS system software 7.5.5 or later.

• At least 16MB of total RAM installed on yourcomputer (we recommend at least 32MB).

• At least 150MB of hard drive space.

• A ten-speed (10x) or faster CD-ROM drive.

• A sound card for PCs.

• A monitor capable of displaying at least 256colors or grayscale.

• A modem with a speed of at least 28,800 bps.

INSTALLING AND USING THE SOFTWAREShareware programs are fully functional, free trialversions of copyrighted programs. If you like particularprograms, register with their authors for a nominal feeand receive licenses, enhanced versions, and technicalsupport. Freeware programs are free, copyrightedgames, applications, and utilities. You can copy themto as many PCs as you like — free — but they have notechnical support. GNU software is governed by itsown license, which is included inside the folder of theGNU software. There are no restrictions ondistribution of this software. See the GNU license for

more details. Trial, demo, or evaluation versions areusually limited either by time or functionality (such asbeing unable to save projects).

For your convenience, the software titles appearing onthe CD-ROM are listed alphabetically.

Author’s sample filesFor Mac and Windows 95/98/NT. These files contain allthe sample code from the book. You can browse thesefiles directly from the CD-ROM, or you can copy themto your hard drive and use them as the basis for yourown projects. To find the files on the CD-ROM, openthe D:\Author Samples folder.

Acrobat Reader, from AdobeFor Windows 95/98 and NT 4 or later and Macintosh.Evaluation version. Acrobat Reader is a program andplug-in that can be used to display, search, and printPDF files.

Aladdin Expander, from Aladdin SystemsFor Macintosh. Freeware. Aladdin Expander can createexpandable archive files that can be expanded asneeded. This freeware version doesn’t include all thefeatures of the commercial version, but it will notexpire.

BBEdit, from Bare Bones SoftwareFor Macintosh. Demo version. BBEdit is an advancedHTML editor that can be used to create Web pages.This demo allows you to use the full version for anevaluation period.

BBEdit Lite, from Bare Bones SoftwareFor Macintosh. Lite version. BBEdit Lite is a light versionof the popular HTML editing package that can be usedto create Web pages.

WHAT’S ON THE CD-ROM

The CD-ROM included in this book containsmany useful files and programs. Beforeinstalling any of the programs on the disc,

make sure that a newer version of the program is

not already installed on your computer. Forinformation on installing different versions of thesame program, contact the program’smanufacturer.

WHAT’S ON THE CD-ROM

Page 281: Javascript Tutorial - 4730-5

265

CoffeeCup HTML Editor, from CoffeeCup SoftwareFor Windows 95/98 and NT 4 or later. Shareware. TheCoffeeCup tools are a suite of tools that let you workwith all aspects of HTML, Web images, and Java. Thesetools are shareware and need to be registered after agiven amount of time.

CSE HTML Validator Lite, from Windows-Al InternetSolutionsFor Windows 95/98 and NT 4 or later. Lite version. CSEHTML Validator Lite doesn’t include all the features ofthe professional version, but it will not expire.

CSE HTML Validator Professional, from Windows-AlInternet SolutionsFor Windows 95/98 and NT 4 or later. Demo version.CSE HTML Validator Professional can be used tovalidate your Web pages. This demo allows you to usethe full version for an evaluation period.

CuteFTP, from GlobalSCAPEFor Windows 95/98 and NT 4 or later. Shareware.CuteFTP is an FTP client that can be used to transferfiles to a Web server.

CuteMAP, from GlobalSCAPEFor Windows 95/98 and NT 4 or later. Shareware.CuteMAP is an image map editor. It can be used tocreate and save image maps.

Dot Planet ISP, from DotPlanet.com For Windows 95/98/NT. Evaluation version. In case youdon’t have a connection to the informationsuperhighway, the CD includes sign-on software forDotPlanet Internet Access, an Internet service provider.

During the sign-up process, you will need to enter theregistration number: 502CY.

After you are signed on, you can access the world wideWeb from DotPlanet’s home page. You need a creditcard to sign up with DotPlanet Internet Access.

Dreamweaver, from MacromediaFor Windows 95/98 and NT 4.0 or later. Trial Version.Dreamweaver is a robust Web page creation tool. Itallows you to dynamically edit HTML and JavaScriptpages. This demo allows you to use the full version foran evaluation period.

GIF Animator, from Ulead SystemsFor Windows 95/98 and NT 4 or later. Trial version. GIFAnimator is a package that can be used to createanimated GIF images. This demo allows you to use thefull version for an evaluation period.

GraphicConverter, from Lemke SoftwareFor Macintosh. Shareware. GraphicConverter is agraphic conversion program that can be used to convertimages between different formats.

HomeSite, from Allaire CorporationFor Windows 95/98 and NT 4 or later. 30-day evaluationversion. HomeSite is a Visual HTML editor. It can beused to create Web pages. The evaluation version willexpire after 30 days.

HotDog Express, from Sausage SoftwareFor Windows 95/98 and NT 4 or later. Demo version.HotDog Express is the easier-to-use version of SausageSoftware’s Web page creation program (see “HotDogProfessional”).

HotDog Professional, from Sausage SoftwareFor Windows 95/98 and NT 4 or later. Trial version.HotDog Professional is Sausage Software’s professional-level Web page creation program.

HTML Pro, from Niklas FrykholmFor Windows 95/98 and NT 4 or later. Shareware. HTMLPro is a Web page editing package that can be used tocreate Web pages.

Internet Explorer, from MicrosoftFor Windows 95/98 and NT 4 or later and Macintosh.Commercial version. Internet Explorer is a robustbrowser that can be used to display Web pages.

Mapedit, from Boutell CommunicationsFor Windows 95/98 and NT 4 or later. Shareware.Mapedit is an image map editor. It can be used to createand save image maps.

Netscape Communicator, from NetscapeFor Windows 95/98 and NT 4 or later and Macintosh.Commercial version. Netscape Communicator is apopular Web browser that can be used to display Webpages.

WHAT'S ON THE CD-ROM B

Page 282: Javascript Tutorial - 4730-5

JAVASCRIPT

266

Paint Shop Pro, from JASCFor Windows 95/98 and NT 4 or later. Shareware. PaintShop Pro is a powerful image editing package. Thisdemo allows you to use the full version for anevaluation period. Paint Shop Pro includes many toolsfor creating, editing, and working with Web images.

PowWow, from Tribal Voice SoftwareFor Windows 95/98 and NT 4 or later. Freeware.PowWow Professional is an instant messagingcommunication package that includes voice chatcapabilities.

RealPlayer, from RealNetworks, Inc.For Windows 95/98 and NT 4 or later and Macintosh.Commercial version. RealPlayer is a browser plug-inthat can be used to view audio and video files.

Reptile, from Sausage SoftwareFor Windows 95/98 and NT 4 or later. Demo version.Reptile is a seamless tile creation package.

Shockwave and Flash Players, from Macromedia, Inc.For Windows 95/98 and NT 4 or later and Macintosh.Commercial version. The Shockwave and Flash Playersare plug-ins that can be used to display Flash andShockwave content within a browser.

SiteCheck, from Pacific Coast SoftwareFor Windows 95/98 and NT 4 or later. Shareware.SiteCheck is a set of utilities that can be used to checkthe links on your site’s Web pages.

SmartSaver Pro, from Ulead SystemsFor Windows 95/98 and NT 4 or later. 15-day trialversion. SmartSaver Pro is a Web image-optimizationpackage that allows you to visually select the filesettings for creating optimized images. This demoallows you to use the full version for an evaluationperiod.

Spider, from InContext SystemsFor Windows 95/98 and NT 4 or later. Evaluationversion. Spider is a Web-authoring package forcreating Web pages.

Stuffit Expander, from Aladdin SystemsFor Macintosh. Commercial version. Stuffit Expandercan create expandable archive files that can beexpanded as needed.

Stuffit Lite, from Aladdin SystemsFor Windows 95/98 and NT 4 or later and Macintosh.Freeware. Stuffit Lite can be used to compress andarchive files. The lite version is freeware and will notexpire.

Web Razor Pro, from Ulead SystemsFor Windows 95/98 and NT 4.0 or later. EvaluationCopy. Web Razor Pro is a Web image-editing packagethat includes features for creating GIF animations andoptimizing Web images. This demo allows you to usethe full version for an evaluation period.

WinZip, from Nico Mak ComputingFor Windows 95/98 and NT 4 or later. Evaluationversion. WinZip is a file compression and archivingpackage.

TROUBLESHOOTINGI tried my best to compile programs that work onmost computers with the minimum systemrequirements. Your computer, however, may differ,and some programs may not work properly for somereason.

The two most likely problems are that you don’t haveenough memory (RAM) for the programs you want touse, or you have other programs running that areaffecting installation or running of a program. If youget error messages like Not enough memory orSetup cannot continue, try one or more ofthese methods and then try using the software again:

• Turn off any anti-virus software.

• Close all running programs.

Page 283: Javascript Tutorial - 4730-5

267

• In Windows, close the CD-ROM interface andrun demos or installations directly fromWindows Explorer.

• Have your local computer store add more RAMto your computer.

If you still have trouble installing the items from theCD-ROM, please call the IDG Books WorldwideCustomer Service phone number: 800-762-2974(outside the U.S.: 317-572-3443).

WHAT'S ON THE CD-ROM B

Page 284: Javascript Tutorial - 4730-5

JAVASCRIPT

268

USING THE E-VERSION OF THE BOOK

USING THE E-VERSIONOF THE BOOK

Y ou can view JavaScript: Your visual blueprintfor building dynamic Web pages on yourscreen using the CD-ROM disc included at the

back of this book. The CD-ROM disc allows you tosearch the contents of each chapter of the book for aspecific word or phrase. The CD-ROM disc alsoprovides a convenient way of keeping the bookhandy while traveling.

You must install Adobe Acrobat Reader on yourcomputer before you can view the book on the CD-ROM disc. This program is provided on

the disc. Acrobat Reader allows you to view PortableDocument Format (PDF) files, which can displaybooks and magazines on your screen exactly as they appear in printed form.

To view the contents of the book using AcrobatReader, display the contents of the disc. Double-clickthe PDFs folder to display the contents of the folder.In the window that appears, double-click the icon forthe chapter of the book you want to review.

USING THE E-VERSIONOF THE BOOK

FLIP THROUGH PAGES

⁄ Click one of theseoptions to flip throughthe pages of a section.

First page

Previous page

Next page

Last page

ZOOM IN

⁄ Click to magnifyan area of the page.

¤ Click the area of thepage you want to magnify.

■ Click one of theseoptions to display the pageat 100% magnification ( )or to fit the entire pageinside the window ( ).

Page 285: Javascript Tutorial - 4730-5

269

■ Repeat Steps 1 and 3 to find the nextinstance of the text.

To install Acrobat Reader, insert the CD-ROM disc into a drive. In the screen thatappears, click Software. Click AcrobatReader and then click Install at the bottomof the screen. Then follow the instructionson your screen to install the program.

You can make searching the book moreconvenient by copying the .pdf files toyour own computer. Display the contentsof the CD-ROM disc and then copy thePDFs folder from the CD to your harddrive. This allows you to easily access the

Acrobat Reader is a popular and usefulprogram. There are many files available on theWeb that are designed to be viewed usingAcrobat Reader. Look for files with the .pdfextension. For more information about AcrobatReader, visit the Web site at www.adobe.com/products/acrobat/readermain.html.

FIND TEXT

⁄ Click to searchfor text in the section.

■ The Find dialog boxappears.

¤ Type the text youwant to find.

‹ Click Find to startthe search.

■ The first instance ofthe text is highlighted.

BUSING THE E-VERSION OF THE BOOK B

Page 286: Javascript Tutorial - 4730-5

INDEX

270

Aabs( ) method, 189absolute values, 189Acrobat Reader, 264addition assignment operator, 149Aladdin Expander, 264alert( ) method, 138–139alert boxes, 251alert dialog box, informing user with, 138–139anchor( ) method, 152–153anchor element, 259anchor object, 110–111and operator, 43appCodeName property, 239arithmetic operators, 36–37Array object, 104–105arrays

declaring, 28–29elements of, determining number of, 30–31length property, 31numbers, sorting array of, 35predefined array, determining length of, 30separating items into, 162–163separator, specifying unique, 32–33sort( ) method, 34–35sorting, 34–35strings, conversion to, 32–33two-dimensional arrays, 29words, sorting array of, 34

author’s sample files on CD, 264

Bbackground color

changing, 120–121listing, 121

BBEdit Lite, 264bidirectional override element, 258block elements, 257blur, using, 217blur( ) method, 216–217boolean variables, 15, 20break loops, 56browser status bar, displaying text on, 118–119browser window

changing background color, 120–121confirm dialog box, enabling user decisions with, 142–143foreground color, setting, 122link color, changing, 122–123moving windows, 134–135new browser window, opening, 128–129printing windows, 132–133prompt dialog box, accepting input with, 140–141remote window, closing, 130–131resizing windows, 136–137text color, changing, 122–123variables, adding, 117

browsers, JavaScript support disabled on, 10–11button object, 196button object properties, displaying, 196buttons, using, 196–197

Ccase of string object, changing, 155case-sensitivity, 9, 14CD

Acrobat Reader, 264Aladdin Expander, 264author’s sample files, 264BBEdit Lite, 264CoffeeCup HTML Editor, 265

Page 287: Javascript Tutorial - 4730-5

271

CSE HTML Validator Lite, 265CSE HTML Validator Professional, 265CuteFTP, 265CuteMAP, 265Dot Planet ISP, 265Dreamweaver, 265Flash Players, 266GIF Animator, 265GraphicConverter, 265HomeSite, 265HotDog Express, 265HotDog Professional, 265HTML Pro, 265installing, 264Internet Explorer, 265Mapedit, 265Netscape Communicator, 265Paint Shop Pro, 266PowWow, 266RealPlayer, 266Reptile, 266Shockwave, 266SiteCheck, 266SmartSaver Pro, 266software on, 264–266Spider, 266Stuffit Expander, 266Stuffit Lite, 266system requirements, 264troubleshooting, 266–267Web Razor Pro, 266WinZip, 266

ceil( ) method, 186check box buttons, 200–201check box object properties, displaying, 200

checkbox object, 200child frame object, 223clearTimeout( ) method, 62–63click event, reacting to, 197client-side image map elements, 260clock, creating, 169code name, determining, 239CoffeeCup HTML Editor, 265comments, 248–249comments, adding, 12–13comparison expressions, creating, 40–41comparison operator, 40–41concat( ) method, 148–149concatenating strings, 148–149conditional operators, 44–45conditional statements, 20confirm( ) method, 142–143confirm dialog box, enabling user decisions with, 142–143constant variables, 14continue loops, 57cookies, 242–243CSE HTML Validator Lite, 265CSE HTML Validator Professional, 265current frame, referencing, 225current object, referring to, 100–101current Web page element, referring to, 101CuteFTP, 265CuteMAP, 265

Ddate format, 164–165Date object

arithmetic performed on, 173clock, creating, 169date format, 164–165

JAVASCRIPT:Your visual blueprint for

building dynamic Web pages

Page 288: Javascript Tutorial - 4730-5

INDEX

272

date values, getting, 168–169Date.parse ( ) method, 172getDate ( ) method, 168–169getHours ( ) method, 168–169getMonth ( ) method, 168–169getTime ( ) method, 172getTimezoneOffset ( ) method, 174–175getYear ( ) method, 168–169Greenwich mean time, 166, 174local date, displaying, 166–167local time, displaying, 166–167overview, 164–165set date values, 170set time values, 171setDate( ) method, 170setHours( ) method, 170setMinutes( ) method, 170setMonth( ) method, 170setSeconds( ) method, 170setTime( ) method, 172setTimeout( ) method, 169setYear( ) method, 170time values, getting, 168–169time zones, 174–175Universal Time Coordinated, 174

date values, getting, 168–169Date.parse( ) method, 172debugging

alert boxes, 251Allaire HomeSite, 253comments, 248–249common errors, 252–253detecting JavaScript errors, 246–247error dialog box, 247Macromedia Dreamweaver, 253

multiple-line comments, 249runtime errors, 246single-line comments, 248syntax errors, 246text boxes, output value of variables to, 250–251

decimal integer variables, 18declaring functions, 64decrement operator, 38–39disabling form elements, 210–211document object, 92–93

document title, changing, 124modification date, displaying, 125overview, 116–117referring page, viewing, 127URL, viewing current, 126

Document Object Model. See DOMdocument structure, 255document.writeIn( ) method, 117DOM (Document Object Model), 92–93Dot Planet ISP, 265double-clicks, detecting, 78–79Dreamweaver, 253, 265

Eencoding characters, 244–245error dialog box, 247escape( ) statement, 244–245escape characters, 149Euler’s constant, 184eval( ) function, 47events

double-clicks, detecting, 78–79focus, setting, 84–85key press, detecting, 82–83

Page 289: Javascript Tutorial - 4730-5

273

keyboard events, 75miscellaneous events, 75mouse clicks, detecting, 76–77mouse events, 74onabort event, 89onblur event, 84–85onchange event, 86–87onclick event, 76–77ondblclick event, 78–79onerror event, 89onfocus event, 84–85onkeydown event, 83onkeypress event, 82–83onkeyup event, 83onload event, 88–89onmouseout events, 80–81onmouseover events, 80–81onunload event, 88–89overview, 74–75page loading messages, creating, 88–89page unloading messages, creating, 88–89pull-down menu selections, detecting, 86–87rollover buttons, creating, 80–81selection events, 75

exp ( ) method, 184explanatory headers, 13exponential methods, 184expressions

and operator, 43arithmetic operators, 36–37comparison expressions, creating, 40–41comparison operator, 40–41conditional operators, 44–45decrement operator, 38–39

eval ( ) function, 47identifying numbers, 48–49increment operator, 38–39isNaN( ) method, 49logical expressions, creating, 42–43logical operators, 42–43modulus operator, 37not operator, 43operator precedence, 46or operator, 43string expressions, evaluating, 47unary operators, 38–39

external JavaScript file, linking to, 8–9

FFlash Players, 266floating-point variables, 15, 19floor( ) method, 186focus

changing, 216controlling, 216–217setting, 84–85

focus( ) method, 216–217focus events, using, 218–219for loops, 52–53foreground color, setting, 122form element properties, displaying, 213form elements

disabling, 210–211list of, 260–263

form object properties, displaying, 212formatting

string variables, 150–151text, 144

JAVASCRIPT:Your visual blueprint for

building dynamic Web pages

Page 290: Javascript Tutorial - 4730-5

INDEX

274

formsblur, using, 217blur( ) method, 216–217button object, 196button object properties, displaying, 196buttons, using, 196–197check box buttons, 200–201check box object properties, displaying, 200checkbox object, 200click event, reacting to, 197detecting blur, 219detecting focus, 218disabling form elements, 210–211focus, changing, 216focus, controlling, 216–217focus( ) method, 216–217focus events, using, 218–219form element properties, displaying, 213form elements, disabling, 210–211form object properties, displaying, 212hidden fields, 193hidden object, 193list item text, changing, 207list selection, responding to, 205mathematical operations, 215multiple check boxes, 201multiple selection lists, 208–209onBlur events, 218–219onFocus events, 218–219option object, 206–207option object properties, displaying, 206password box object, 192password boxes, 192radio button object, 202–203

radio button object properties, displaying, 202radio button selection, responding to, 203radio buttons, 202–203reset button, 198reset object, 198resetting, 212–213select object, 204–205selectedIndex property, 205, 208selection lists, 204–207selection object properties, displaying, 204submit button, 199submit object, 199submitting, 212–213text box object methods, using, 191text box object properties, displaying, 190text boxes, 190–191textarea box object methods, using, 195textarea box properties, displaying, 194textarea boxes, 194–195validating, 214–215

frame objectacessing frames by name, 222–223child frame object, 223current frame, referencing, 225frame resizing, detecting, 229frames property, 220length property, 224nested framesets, 226number of frames, finding, 224overview, 220–221parent frame, 222–223print( ) method, 231printing frames, 231referencing across frames, 226–227

Page 291: Javascript Tutorial - 4730-5

275

self object, 225separate frames, writing to, 228target frame, setting, 230top object, 225

frame resizing, detecting, 229frames property, 220functions

calling, 65declaring, 64global variables, 66–67HTML link, calling functions from, 72–73HTML values returned from, 71local variables, 66–67overview, 64parameters, passing, 68–69several parameters, passing, 69single parameters, passing, 68values returned from, 70–71

GgetDate( ) method, 168–169getHours( ) method, 168–169getMonth( ) method, 168–169getTime( ) method, 172getTimezoneOffset( ) method, 174–175getYear( ) method, 168–169GIF Animator, 265global variables, 66–67GraphicConverter, 265Greenwich mean time, 166, 174

Hhead elements, 255–256head tags, 9headers, explanatory, 13

heading elements, 257hexadecimal integer variables, 18hidden fields, 193hidden object, 193history object, 92–93, 114–115HomeSite, 253, 265horizontal rule element, 259hostname property, 111HotDog Express, 265HotDog Professional, 265HTML (Hypertext Markup Language), 2HTML 4.01 reference

anchor element, 259bidirectional override element, 258block elements, 257client-side image map elements, 260common attributes, 254document structure, 255form elements, 260–262head elements, 255–256heading elements, 257horizontal rule element, 259image element, 259inline element, 258inserted/deleted text elements, 257line break element, 259list elements, 258phrase elements, 257preformatted text elements, 257quote elements, 257subscript elements, 258superscript elements, 258table elements, 262-263text style elements, 258

JAVASCRIPT:Your visual blueprint for

building dynamic Web pages

Page 292: Javascript Tutorial - 4730-5

INDEX

276

HTML document, JavaScript embedded within, 6–7HTML link, calling functions from, 72–73HTML Pro, 265Hypertext Markup Language. See HTML

Iidentifying numbers, 48–49if loops, 51if-else statements, 50–51image element, 259image object, 106–109increment operator, 38–39indexOf( ) method, 158–159infinite loops, 57inline element, 258inserted/deleted text elements, 257integer variables, 15, 18Internet Explorer, 265intervals

clearing, 62–63setting regularly timed, 60–61

isNaN( ) method, 49

JJava, determining if enabled, 238javaEnabled( ) method, 238JavaScript

browser configuration, JavaScript disabled in, 10–11case-sensitivity, 9comments, adding, 12–13explanatory headers, 13external JavaScript file, linking to, 8–9head tags, 9HTML document, embedded within, 6–7

noscript tags, 10–11overview, 2–3personalizing Web pages with, 7script tags, 6–9statements, 4–5

JavaScript timers, 58–59

Kkey press, detecting, 82–83keyboard events, 75

Llength property, 154, 224line break element, 259link( ) method, 152–153link color, changing, 122–123link object, 110–113links, changing, 112–113list elements, 258list item text, changing, 207list selection, responding to, 205local date, displaying, 166–167local time, displaying, 166–167local variables, 66–67location object, 240–241location object properties, displaying, 240log ( ) method, 184logarithmic methods, 184logical expressions, creating, 42–43logical operators, 42–43

MMapedit, 265Math object, 59

abs( ) method, 189absolute values, 189

Page 293: Javascript Tutorial - 4730-5

277

ceil( ) method, 186Euler’s constant, 184exp( ) method, 184exponential methods, 184floor( ) method, 186log( ) method, 184logarithmic methods, 184Math.E constant, 180mathematical constants, 180–181Math.floor( ) method, 178–179Math.LN2 constant, 180Math.LN10 constant, 180Math.log( ) method, 181Math.LOG2E constant, 180Math.LOG10E constant, 180Math.PI constant, 180–181Math.random( ) method, 178–179Math.SQRT1_2 constant, 180Math.SQRT2 constant, 180max( ) method, 188maximum values, 188min( ) method, 188minimum values, 188overview, 176–177pow( ) method, 187raising numbers to a power, 187random numbers, generating, 178–179round( ) method, 186round numbers, 186sqrt( ) method, 185square root method, 185trigonometric functions, 182–183using, 97

Math.E constant, 180mathematical constants, 180–181

mathematical operations, 215Math.floor( ) method, 178–179Math.LN2 constant, 180Math.LN10 constant, 180Math.log( ) method, 181Math.LOG2E constant, 180Math.LOG10E constant, 180Math.PI constant, 180–181Math.random( ) method, 178–179Math.SQRT1_2 constant, 180Math.SQRT2 constant, 180max( ) method, 188maximum values, 188min( ) method, 188minimum values, 188miscellaneous events, 75modulus operator, 37mouse clicks, detecting, 76–77mouse events, 74moving windows, 134–135multiple check boxes, 201multiple else statements, 51multiple selection lists, 208–209multiple-line comments, 249

Nnavigator object

appCodeName property, 239code name, determining, 239cookies, 242–243detecting a user’s browser, 234detecting browser version, 235encoding characters, 244–245escape( ) statement, 244–245

JAVASCRIPT:Your visual blueprint for

building dynamic Web pages

Page 294: Javascript Tutorial - 4730-5

INDEX

278

Java, determining if enabled, 238javaEnabled( ) method, 238location object, 240–241location object properties, displaying, 240operating system, detecting user’s, 236overview, 232–233platform property, 236reloading pages, 241unescape( ) statement, 244–245user agent, understanding, 237userAgent property, 237

negative integer variables, 18nested framesets, 226Netscape Communicator, 265Netscape Navigator, JavaScript support disabled in, 11noscript tags, 10–11not operator, 43

Oobject methods, 90–91object properties

complete property, 109described, 90–91identifying, 100for loop, 102viewing, 102–103

objectsanchor object, 110–111Array object, 104–105changing images, 108–109creating, 98–99current object, referring to, 100–101current Web page element, referring to, 101document object, 92–93DOM (Document Object Model), 92–93history object, 92–93, 114–115

image object, 106–109link object, 110–113Math object, using, 97methods, 90–91new objects, creating, 98–99overview, 90–91predefined objects, 96–97preloading images, 107properties. See object propertiesradio button, checking, 95string object, using, 96subobjects, 94–95text field, changing, 94this keyword, 100–101Web page element objects, 92–93window. See window object

onabort event, 89onBlur events, 84–85, 218–219onchange event, 86–87onclick event, 76–77ondblclick event, 78–79onerror event, 89onFocus events, 84–85, 218–219onkeydown event, 83onkeypress event, 82–83onkeyup event, 83onload event, 88–89onmouseout events, 80–81onmouseover events, 80–81onunload event, 88–89operating system, detecting user’s, 236operator precedence, 46option object, 206–207option object properties, displaying, 206or operator, 43

Page 295: Javascript Tutorial - 4730-5

279

Ppage loading messages, creating, 88–89page unloading messages, creating, 88–89Paint Shop Pro, 266parameters, passing, 68–69parent frame, 222–223parseFloat( ), 24–25parseInt( ), 24–25password box object, 192password boxes, 192pathname property, 111phrase elements, 257platform property, 236pow( ) method, 187PowWow, 266predefined objects, 96–97preformatted text elements, 257preloading images, 107print( ) method, 231printing

frames, 231windows, 132–133

program flow methodsbreak loops, 56clearTimeout( ) method, 62–63continue loops, 57if loops, 51if-else statements, 50–51infinite loops, 57intervals, setting regularly timed, 60–61JavaScript timers, 58–59for loops, 52–53Math object, 59multiple else statements, 51setInterval( ) method, 60–61setTimeout( ) method, 60while loops, 54–55

prompt( ) method, 140–141prompt dialog box, accepting input with, 140–141protocol property, 111pull-down menu selections, detecting, 86–87

Q-Rquote elements, 257

radio button object, 202–203radio button object properties, displaying, 202radio button selection, responding to, 203radio buttons, 95, 202–203raising numbers to a power, 187random numbers, generating, 178–179RealPlayer, 266referencing across frames, 226–227reloading pages, 241remote window, closing, 130–131replace( ) method, 160–161Reptile, 266reset button, 198reset object, 198resizing windows, 136–137rollover buttons, creating, 80–81round( ) method, 186round numbers, 186runtime errors, 246

Sscientific notation used to express, 19script tags, 6–9scripting language

described, 2–3JavaScript. See JavaScriptVBScript, 3

JAVASCRIPT:Your visual blueprint for

building dynamic Web pages

Page 296: Javascript Tutorial - 4730-5

INDEX

280

search( ) method, 156–157searches within a string, 156–157select object, 204–205selectedIndex property, 205, 208selection events, 75selection lists, 204–205, 206–207selection object properties, displaying, 204self object, 225separate frames, writing to, 228set date values, 170set time values, 171setDate( ) method, 170setHours( ) method, 170setInterval( ) method, 60–61setMinutes( ) method, 170setMonth( ) method, 170setSeconds( ) method, 170setTime( ) method, 172setTimeout( ) method, 60, 169setYear( ) method, 170Shockwave, 266single parameters, passing, 68single-line comments, 248SiteCheck, 266SmartSaver Pro, 266Spider, 266split( ) method, 162–163splitting a string, 162–163sqrt( ) method, 185square root method, 185string expressions, evaluating, 47string length, determining, 154

string objectaddition assignment operator, 149anchor( ) method, 152–153array, separating items into, 162–163case, changing, 155concat( ) method, 148–149concatenating strings, 148–149escape characters, 149formatting string variables, 150–151formatting text, 144indexOf( ) method, 158–159length property, 154link( ) method, 152–153locating characters in a string, 158–159overview, 144–145replace( ) method, 160–161search( ) method, 156–157searches within a string, 156–157split( ) method, 162–163splitting a string, 162–163string length, determining, 154sub( ) method, 150–151substring( ) method, 146–147substrings, 146–147sup( ) method, 150–151text case, changing, 145text in a string, replacing, 160–161toLowerCase( ) method, 155toUpperCase( ) method, 155using, 96

string variables, 15, 21

Page 297: Javascript Tutorial - 4730-5

281

stringsassigning, 17comparing, 41

Stuffit Expander, 266Stuffit Lite, 266sub( ) method, 150–151submit button, 199submit object, 199subobjects, 94–95subscript elements, 258substring( ) method, 146–147substrings, 146–147sup( ) method, 150–151superscript elements, 258syntax errors, 246

Ttarget frame, setting, 230text box object methods, using, 191text box object properties, displaying, 190text boxes, 190–191, 250–251text case, changing, 145text color, changing, 122–123text field, changing, 94text in a string, replacing, 160–161text style elements, 258textarea box object methods, using, 195textarea box properties, displaying, 194textarea boxes, 194–195this keyword, 100–101

time values, getting, 168–169time zones, 174–175timeouts, clearing, 62–63toLowerCase( ) method, 155top object, 225tostring( ) method, 26–27toUpperCase( ) method, 155trigonometric functions, 182–183typeof keyword, 22–23

Uunary operators, 38–39unescape( ) statement, 244–245Universal Time Coordinated, 174URL field, JavaScript statements entered in, 4–5user agent, understanding, 237userAgent property, 237

Vvalues

assigning, 17returned from functions, 70–71

variablesadding, 117arrays. See arraysboolean variables, 15, 20case-sensitivity, 14conditional statements, 20constant variables, 14converting numbers to strings, 26–27

JAVASCRIPT:Your visual blueprint for

building dynamic Web pages

Page 298: Javascript Tutorial - 4730-5

INDEX

282

converting strings to numbers, 24–25decimal integer variables, 18declaring, 16floating-point variables, 15, 19hexadecimal integer variables, 18integer variables, 15, 18negative integer variables, 18overview, 14–15parseFloat( ), 24–25parseInt( ), 24–25scientific notation used to express, 19string variables, 15, 21strings, assigning, 17tostring( ) method, 26–27typeof keyword, 22–23types, determining, 22–23types of, 14–15values, assigning, 17

VBScript, 3

W-ZWeb page element objects, 92–93Web pages

loading messages, 88–89personalizing with JavaScript, 7

Web Razor Pro, 266while loops, 54–55window object, 92–93

alert( ) method, 138–139alert dialog box, informing user with, 138–139browser status bar, displaying text on, 118–119changing background color, 120–121confirm( ) method, 142–143

confirm dialog box, enabling user decisions with, 142–143document.writeIn( ) method, 117foreground color, setting, 122link color, changing, 122–123moving windows, 134–135new browser window, opening, 128–129overview, 116–117printing windows, 132–133prompt( ) method, 140–141prompt dialog box, accepting input with, 140–141remote window, closing, 130–131resizing windows, 136–137text color, changing, 122–123variables, adding, 117window.blur( ) method, 131window.close( ) function, 130window.focus( ) method, 131window.moveBy( ) method, 134–135window.moveTo( ) method, 134–135window.open( ) method, 128window.resizeBy( ) method, 136–137window.resizeTo( ) method, 136–137

window.blur( ) method, 131window.close( ) function, 130window.focus( ) method, 131window.moveBy( ) method, 134–135window.moveTo( ) method, 134–135window.open( ) method, 128window.resizeBy( ) method, 136–137window.resizeTo( ) method, 136–137WinZip, 266

Page 299: Javascript Tutorial - 4730-5

283

JAVASCRIPT:Your visual blueprint for

building dynamic Web pages

Page 300: Javascript Tutorial - 4730-5

284

IDG BOOKS WORLDWIDE, INC.END-USER LICENSE AGREEMENT

READ THIS. You should carefully read these terms and conditions before opening the software packet(s)included with this book (“Book”). This is a licenseagreement (“Agreement”) between you and IDGBooks Worldwide, Inc. (“IDGB”). By opening theaccompanying software packet(s), you acknowledgethat you have read and accept the following terms and conditions. If you do not agree and do not wantto be bound by such terms and conditions, promptlyreturn the Book and the unopened software packet(s)to the place you obtained them for a full refund.

1. License Grant. IDGB grants to you (either anindividual or entity) a nonexclusive license to use onecopy of the enclosed software program(s) (collectively,the “Software”) solely for your own personal orbusiness purposes on a single computer (whether a standard computer or a workstation component of a multi-user network). The Software is in use on acomputer when it is loaded into temporary memory(i.e., RAM) or installed into permanent memory (e.g.,hard disk, CD-ROM or other storage device). IDGBreserves all rights not expressly granted herein.

2. Ownership. IDGB is the owner of all right, title andinterest, including copyright, in and to the compilation of the Software recorded on the CD-ROM. Copyright to the individual programs on the CD-ROM is ownedby the author or other authorized copyright owner ofeach program. Ownership of the Software and allproprietary rights relating thereto remain with IDGBand its licensors.

3. Restrictions On Use and Transfer.

(a) You may only (i) make one copy of the Softwarefor backup or archival purposes, or (ii) transfer the

Software to a single hard disk, provided that you keepthe original for backup or archival purposes. You maynot (i) rent or lease the Software, (ii) copy orreproduce the Software through a LAN or othernetwork system or through any computer subscribersystem or bulletin-board system, or (iii) modify, adapt or create derivative works based on theSoftware.

(b) You may not reverse engineer, decompile, ordisassemble the Software. You may transfer theSoftware and user documentation on a permanentbasis, provided that the transferee agrees to acceptthe terms and conditions of this Agreement and youretain no copies. If the Software is an update or hasbeen updated, any transfer must include the mostrecent update and all prior versions.

4. Restrictions on Use of Individual Programs. You must follow the individual requirements andrestrictions detailed for each individual program in the “What's On The CD-ROM Disc” section of thisBook. These limitations are contained in the individuallicense agreements recorded on the CD-ROM. Theserestrictions may include a requirement that after usingthe program for the period of time specified in its text,the user must pay a registration fee or discontinueuse. By opening the Software packet(s), you will beagreeing to abide by the licenses and restrictions for these individual programs. None of the material on this disc(s) or listed in this Book may ever bedistributed, in original or modified form, forcommercial purposes.

5. Limited Warranty.

(a) IDGB warrants that the Software and CD-ROM are free from defects in materials and workmanshipunder normal use for a period of sixty (60) days fromthe date of purchase of this Book. If IDGB receives

Page 301: Javascript Tutorial - 4730-5

285

notification within the warranty period of defects inmaterials or workmanship, IDGB will replace thedefective CD-ROM.

(b) IDGB AND THE AUTHOR OF THE BOOK DISCLAIM ALL OTHER WARRANTIES, EXPRESS ORIMPLIED, INCLUDING WITHOUT LIMITATIONIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, WITHRESPECT TO THE SOFTWARE, THE PROGRAMS, THE SOURCE CODE CONTAINED THEREIN, AND/OR THE TECHNIQUES DESCRIBED IN THIS BOOK. IDGB DOES NOT WARRANT THAT THE FUNCTIONSCONTAINED IN THE SOFTWARE WILL MEET YOUR REQUIREMENTS OR THAT THE OPERATION OF THE SOFTWARE WILL BE ERROR FREE.

(c) This limited warranty gives you specific legal rights, and you may have other rights which vary from jurisdiction to jurisdiction.

6. Remedies.

(a) IDGB’s entire liability and your exclusive remedy fordefects in materials and workmanship shall be limitedto replacement of the Software, which may be returnedto IDGB with a copy of your receipt at the followingaddress: Disc Fulfillment Department, Attn: JavaScript:Your visual blueprint for Building Dynamic Web pages,IDG Books Worldwide, Inc., 10475 CrosspointBoulevard, Indianapolis, Indiana, 46256, or call 1-800-762-2974. Please allow 3-4 weeks for delivery.This Limited Warranty is void if failure of the Softwarehas resulted from accident, abuse, or misapplication.Any replacement Software will be warranted for theremainder of the original warranty period or thirty (30) days, whichever is longer.

(b) In no event shall IDGB or the author be liable for any damages whatsoever (including withoutlimitation damages for loss of business profits,business interruption, loss of business information, or any other pecuniary loss) arising out of the use of or inability to use the Book or the Software, even if IDGB has been advised of the possibility of such damages.

(c) Because some jurisdictions do not allow theexclusion or limitation of liability for consequential or incidental damages, the above limitation orexclusion may not apply to you.

7. U.S. Government Restricted Rights. Use,duplication, or disclosure of the Software by the U.S. Government is subject to restrictions statedin paragraph (c) (1) (ii) of the Rights in Technical Data and Computer Software clause of DFARS252.227-7013, and in subparagraphs (a) through (d)of the Commercial Computer—Restricted Rightsclause at FAR 52.227-19, and in similar clauses in the NASA FAR supplement, when applicable.

8. General. This Agreement constitutes the entireunderstanding of the parties, and revokes andsupersedes all prior agreements, oral or written,between them and may not be modified or amendedexcept in a writing signed by both parties heretowhich specifically refers to this Agreement. ThisAgreement shall take precedence over any otherdocuments that may be in conflict herewith. If anyone or more provisions contained in this Agreement are held by any court or tribunal to be invalid, illegalor otherwise unenforceable, each and every otherprovision shall remain in full force and effect.