Michael Moncur

Teach Yourself

DHTML
in

24

Hours

800 East 96th St., Indianapolis, Indiana, 46240 USA

Sams Teach Yourself DHTML in 24 Hours
Copyright © 2002 by Sams Publishing
All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein. International Standard Book Number: 0-672-32302-8 Library of Congress Catalog Card Number: 2001096687 Printed in the United States of America First Printing: December 2001 04 03 02 01 4 3 2 1

ACQUISITIONS EDITOR
Scott D. Meyers

DEVELOPMENT EDITOR
Damon Jordan

MANAGING EDITOR
Charlotte Clapp

INDEXERS
Sandy Henselmeier Ken Johnson

PROOFREADER
Plan-It Publishing

TECHNICAL EDITOR
Jason Byars

TEAM COORDINATOR
Amy Patton

INTERIOR DESIGNER
Gary Adair

Trademarks
All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark.

COVER DESIGNER
Aren Howell

Warning and Disclaimer
Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an “as is” basis. The author and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book.

Contents at a Glance
Introduction 1

PART I Getting Started
Hour 1 2 3 4 Understanding DHTML Reviewing HTML Understanding JavaScript Creating a Simple DHTML Example

3
5 17 33 49

PART II Learning DHTML Basics
Hour 5 6 7 8 Understanding the DOM Creating Positionable Elements (Layers) Working with DOM Properties and Methods Responding to Events

59
61 73 87 101

PART III Working with Style Sheets
Hour 9 10 11 12 Introducing Style Sheets Using Style Sheet Properties Controlling Styles with JavaScript Creating Consistent Styles

113
115 129 143 155

PART IV Dynamic HTML in Action
Hour 13 14 15 16 Creating Drop-Down Menus Creating a Menu Tree Creating DHTML Text Effects Using DHTML for Animation

169
171 187 199 213

PART V Learning Advanced Techniques
Hour 17 18 19 20 Dealing with Browser Differences Using DHTML with Forms Using Dynamic Fonts Troubleshooting DHTML

229
231 245 259 271

PART VI Putting It All Together
Hour 21 22 23 24 Creating a Dynamic Site Creating Complex Animations Creating a DHTML Game DHTML Tips and Tricks

285
287 301 315 333

PART VII Appendixes
Appendix A B C D Other JavaScript and DHTML Resources Glossary Browser Compatibility Chart DOM Quick Reference Index

345
347 353 357 361 367

Table of Contents
Introduction 1

PART I Getting Started
HOUR 1 Understanding DHTML

3
5

What Is Dynamic HTML? ......................................................................................6 Static and Dynamic Pages ..................................................................................6 Dynamic HTML Menus ....................................................................................7 Positioning and Animation ................................................................................8 Layers ................................................................................................................8 Text Effects ........................................................................................................8 The Components of DHTML ..................................................................................9 HTML ................................................................................................................9 CSS (Cascading Style Sheets)............................................................................9 The Document Object Model (DOM)..............................................................10 JavaScript..........................................................................................................10 History of DHTML and the DOM ........................................................................11 DOM Level 0....................................................................................................11 Browser-Specific DOMs ..................................................................................12 DOM Level 1....................................................................................................12 DOM Level 2....................................................................................................12 DHTML Browsers ................................................................................................12 Summary ................................................................................................................13 Q&A ......................................................................................................................13 Quiz........................................................................................................................14 Questions ..........................................................................................................14 Answers ............................................................................................................14 Exercises ................................................................................................................15 HOUR 2 Reviewing HTML 17

Basic HTML Syntax ..............................................................................................18 Tags ..................................................................................................................18 Attributes ..........................................................................................................18 The HTML Standard ........................................................................................19 Defining Parts of a Document ..............................................................................19 The <html>, <head>, and <body> Tags..............................................................19 Paragraphs ........................................................................................................20 Headings ..........................................................................................................21 Ordered and Unordered Lists ..........................................................................21

vi

Sams Teach Yourself DHTML in 24 Hours

Images ..............................................................................................................22 Links and Anchors............................................................................................22 Divisions and Spans ........................................................................................22 Styling Text ............................................................................................................23 Bold and Italics ................................................................................................23 Fonts ................................................................................................................24 Indenting ..........................................................................................................24 Using Tables for Layout ..................................................................................24 Creating Forms ......................................................................................................25 The <form> Tag ................................................................................................25 Text Input..........................................................................................................26 Checkboxes and Radio Buttons........................................................................26 Drop-Down Selections ....................................................................................27 Buttons..............................................................................................................27 Workshop: Creating a Web Page with HTML ......................................................27 Summary ................................................................................................................29 Q&A ......................................................................................................................30 Quiz........................................................................................................................30 Questions ..........................................................................................................30 Answers ............................................................................................................31 Exercises ................................................................................................................31 HOUR 3 Understanding JavaScript 33

JavaScript Basics ..................................................................................................34 Beginning and Ending Scripts..........................................................................34 Supporting Older Browsers ..............................................................................34 Hiding JavaScript Code ....................................................................................34 JavaScript Statements ......................................................................................35 Creating Event Handlers ..................................................................................36 Understanding Variables ........................................................................................36 Declaring Variables ..........................................................................................37 Using Arrays ....................................................................................................37 Using Strings ....................................................................................................38 Using Conditions and Loops ................................................................................38 Using the if Keyword ......................................................................................38 Conditional Operators ......................................................................................39 Using for Loops ..............................................................................................39 Using while Loops ..........................................................................................40 Using Functions ....................................................................................................40 Defining a Function..........................................................................................40 Calling Functions..............................................................................................41

Contents

vii

Using Arguments ..............................................................................................41 Returning Values ..............................................................................................41 Understanding Objects ..........................................................................................42 Object Properties and Methods ........................................................................42 Workshop: Adding a Script to a Web Page............................................................42 Adding Event Handlers ....................................................................................43 Putting It All Together ......................................................................................43 Summary ................................................................................................................45 Q&A ......................................................................................................................45 Quiz........................................................................................................................46 Questions ..........................................................................................................46 Answers ............................................................................................................46 Exercises ................................................................................................................47 HOUR 4 Creating a Simple DHTML Example 49

Starting with an HTML Document........................................................................50 Finding Objects......................................................................................................51 Using a DHTML Function ..............................................................................51 Detecting Browser Support ..............................................................................52 Creating the Script ................................................................................................53 Adding Event Handlers ....................................................................................53 Creating the Describe Function ......................................................................53 Workshop: Putting It All Together ........................................................................54 Summary ................................................................................................................56 Q&A ......................................................................................................................56 Quiz........................................................................................................................57 Questions ..........................................................................................................57 Answers ............................................................................................................57 Exercises ................................................................................................................58

PART II Learning DHTML Basics
HOUR 5 Understanding the DOM

59
61

Learning DOM Structure ......................................................................................62 The Level 0 DOM ............................................................................................62 The Level 1 DOM ............................................................................................62 Nodes ................................................................................................................64 Parents and Children ........................................................................................64 Siblings ............................................................................................................64 Using DOM Objects ..............................................................................................64 DOM Object Properties....................................................................................64 Node Relationship Properties ..........................................................................65

viii

Sams Teach Yourself DHTML in 24 Hours

Style Properties ................................................................................................65 Document Object Methods ..............................................................................66 Node Object Methods ......................................................................................67 JavaScript and the DOM........................................................................................68 Workshop: Hiding and Showing Objects ..............................................................68 Creating the JavaScript Function......................................................................68 Creating the HTML Document ........................................................................69 Summary ................................................................................................................70 Q&A ......................................................................................................................70 Quiz........................................................................................................................71 Questions ..........................................................................................................71 Answers ............................................................................................................72 Exercises ................................................................................................................72 HOUR 6 Creating Positionable Elements (Layers) 73

Why Layers? ..........................................................................................................74 HTML Tags for Layers ..........................................................................................74 Positioning Objects ................................................................................................75 Setting Coordinates ..........................................................................................75 Using Units ......................................................................................................76 Showing and Hiding Objects............................................................................76 Background Properties ....................................................................................77 Handling Overflow ..........................................................................................77 Border Properties..............................................................................................78 Creating a Layered Document ..............................................................................78 Workshop: Manipulating Layers with JavaScript..................................................80 Creating the Control Panel ..............................................................................80 Creating the move Function ..............................................................................81 Putting It All Together ......................................................................................82 Summary ................................................................................................................85 Q&A ......................................................................................................................85 Quiz........................................................................................................................85 Questions ..........................................................................................................85 Answers ............................................................................................................86 Exercises ................................................................................................................86 HOUR 7 Working with DOM Properties and Methods 87

Understanding Node Properties ............................................................................88 The nodeValue Property ..................................................................................89 The InnerHTML Property ..................................................................................89 Offset Properties ..............................................................................................89

..........................................................................................................................................................................................................................................................................100 HOUR 8 Responding to Events 101 Understanding Event Handlers .......................................97 Summary ..............................................96 The AddNode Function ..........................93 Working with Attributes ....................................................................................................................................................................103 Dynamic Event Handlers .................................................................................................................................................................................................................................105 Using Keyboard Events ...............................................100 Questions ...........104 Using Mouse Events ...........................................103 Netscape event Properties.....................................................................................................91 Cloning a Node ................Contents ix Using Document Methods and Properties ........................................99 Q&A .........................................................................100 Answers .................................................................104 Using onMouseOver and onMouseOut Events ................................................................................................102 Internet Explorer event Properties ..............................................93 Removing Nodes .........97 The DeleteNode Function ........................................................................................................105 Detecting Mouse Clicks .......................................................................................92 Inserting a New Node ......................................................107 Workshop: Displaying an Event Log ...............................................112 ....................................107 Form Events ............................................................................................................................................................................................................................................................................................................................................................................................................................................................................110 Quiz...................111 Answers ...................110 Q&A ..............99 Quiz..................111 Questions ...........96 Setting Up the HTML Document .......................................111 Exercises .....................................................................................97 Putting It All Together ................................................................................................................................................................................................................................................................................................................................................100 Exercises ......91 Using Node Methods ........104 Using the onMouseMove Event ....................................................................92 Replacing Nodes ...............94 Workshop: Adding and Removing Text on a Page...........................................................................................................................................................90 Creating Elements ..................................................................................................................................................................................................................................................106 The onLoad Event ................................................................................................................................................90 Creating Text Nodes ..........108 Summary ...........................................................................92 Appending a New Node ...........................................................................................................................................................................................102 Using the event Object.........................................................91 The documentElement object......................................................................

.....................................................................127 Exercises .....................................127 HOUR 10 Using Style Sheet Properties 129 Creating Styled Text .....................................118 Creating Rules ..................................................................................................................................................................................132 Setting Margins and Borders ..........................................................................................................................126 Questions ...................................................................................................................................................................................................................................................................................................................................118 Using Classes............................................ Italics.............................................................................................................126 Quiz..............................134 ....................133 Properties for Margins.......131 Working with Fonts ..............................................................................................123 Workshop: Creating a Simple Style Sheet ........................131 Choosing a Font....126 Q&A ........................................................130 Spacing ....................................................................124 Summary .....121 Aligning Text ..x Sams Teach Yourself DHTML in 24 Hours PART III Working with Style Sheets HOUR 9 Introducing Style Sheets 113 115 Why Style Sheets? ................................................................................................................121 Basic Style Properties ......................................130 Capitalization........................................................ and Small Capitals ........................................................................................................................................117 Inline Styles ........................131 Decorating Text .........................................116 Adding Style to Substance ...............................................................................................119 External Style Sheets.......................117 The <style> Tag ................................................................122 Positioning Objects ......................................................................................................................................................................................................................................................................................................117 Integrating Style Sheets with HTML ..........................................................................................................................................................................................................126 Answers .......116 The Traditional Approach .....................................................................................................................................................................................................................131 Setting Font Size .........119 Using Units ...................133 Border Properties........................132 Using Bold........................................................................130 Alignment .....................................................................................................................................................................................120 Cascading Styles ....................................121 Defining Colors and Background Images ....................................118 Using IDs................................................................................................................................................................................................................................................116 Content versus Presentation ............................................................................................................................................

...........................................156 Usability Tips.............................................................................................................................................................................................134 Centering with CSS .............................................136 Workshop: Creating a Styled Document ..........135 Setting Link Styles ...................................................................................................................................................................153 HOUR 12 Creating Consistent Styles 155 Using Restraint ....................................................................................................................................................................................................................................................................151 Quiz...............................................158 ...............151 Q&A ..............................................................................135 Setting Cursor Styles .137 Creating the HTML Document .........................................................................................................................................................................................................................146 Changing Text Styles Dynamically ..............................................................145 Calling the Functions....144 Working with Colors.......................139 Summary ........................................................................152 Questions ........................................................................................................157 Link Colors ..............................................156 Choosing Colors ..........................................................................................................................140 Quiz.....................................................157 Background Images ...................................................................................................................................................................................................................................................137 Creating the Style Sheet ........................................................................................................................................................................................................................................................................145 Using Color Properties ..........................................................................................................................148 Workshop: Using Dynamic Styles ..........................141 Questions ..141 Answers ..............................136 Setting List Styles ......................................................................................................................152 Answers ..........................................................146 Changing Colors Dynamically ....................149 Creating the Function ...........................................................................................................................................149 Creating the HTML Document ................................................................141 Exercises .....................................157 Text and Background Colors..........................................................153 Exercises ....142 HOUR 11 Controlling Styles with JavaScript 143 Dynamic Styles ..................................................................................................................................................................................................................................................................................................................................................................................................135 Setting Other Style Attributes....................................................................................................................Contents xi Overflow and Clipping ........................149 Summary .....................................................................................................140 Q&A .144 Translating Property Names ......................................

...........................................................................................................xii Sams Teach Yourself DHTML in 24 Hours Choosing Fonts ..................................................................................................................................................................................166 Q&A ....................................................167 Answers ......................................180 Workshop: Creating the Complete Example .........................................................................................................................................................................................173 Defining the Layers ....................................................................................183 Q&A ............162 Creating the Function .........................................................168 PART IV Dynamic HTML in Action HOUR 13 Creating Drop-Down Menus 169 171 Overview..................184 Questions ....................................................................................................................................................................175 Creating the JavaScript Functions ...................................................................................................160 Supporting Older Browsers ...........................................................................................................................184 Exercises ...........................................................................178 Displaying a Menu ....................................173 Creating the Menu HTML...............161 Creating the Second Style Sheet ..............................................................................................................................................................161 Creating the First Style Sheet ................172 Objects and Events .............................175 Finishing the HTML Document ...............................................................................................185 .............179 Highlighting Menu Items ............................................................................................................................................................................................................................181 Summary ...178 Erasing Menus .........................................................................................................................................................................................................................................................................................................160 Workshop: Creating Multiple-Choice Styles .........................................................................159 Choosing Font Sizes ............................................................................................................................................................................184 Answers ....173 Creating the HTML Document...........................................163 Summary .......158 Common Font Choices .............160 Margins and Borders...........................................................................................162 Creating the HTML Document .........................................................166 Quiz..........................................................................158 Available Windows and Macintosh Fonts .........................................................................................................................................................................167 Questions .................................................................................................183 Quiz....................................................................172 Event Handlers .........................................................................................................168 Exercises ......................................................................................................................

......................................................................196 Answers ..........................................................................................................................................211 HOUR 16 Using DHTML for Animation 213 Methods of Web Animation .........................197 HOUR 15 Creating DHTML Text Effects 199 Creating Blinking Text ................................................................................................................................189 Creating the HTML Document...............................................................................................................................................200 Completing the Blinking Text Example ...............................214 JavaScript Image Animation .........................................................204 Creating the Script..................202 Completing the Moving Text Example .................................................193 Summary ................................................200 Creating the Script....................................................................................................................189 Completing the HTML Document ............................................................................................................188 Objects and Events .....................................................209 Quiz...............................................................................................................................................................................................................Contents xiii HOUR 14 Creating a Menu Tree 187 Overview.................................................................................................197 Exercises ..........210 Questions ........................................................................................................................................................................................................................................................189 Defining the Menu Items.....................188 Nested Categories ....................................................................................................................................................................................................190 Creating the JavaScript Functions ........................................................192 Collapsing All Items .........................................................................................................................................................................................................................................................................................193 Workshop: Finishing and Testing the Menu..................................................................................................................................196 Questions .....................206 Creating the Script..................191 Hiding and Showing Menus ................................................210 Answers .......................................................................205 Workshop: Creating a Scrolling Message ................211 Exercises .........................................................................................191 Expanding All Items .........................................................................................................................................................................................................................................................................................................................................................201 Creating the Script................................207 Summary ............201 Moving Text ....................................................202 Fading Text ................................................................209 Q&A ....204 Completing the Fading Text Example.................................................................................................................................................................................................................................................206 Putting It All Together .................................214 Animated GIF Images ...............195 Q&A .......................................195 Quiz...................214 ..............................................................................

..........................................................................................................................................................224 Summary .......................................................................237 Netscape 4 DHTML ....................228 Exercises ...........................................217 Creating the HTML Document ..........................................................................................................................................222 The MoveRight Function ...................................................................................................................................................................................................215 Creating the Animation Function .......................................220 Expanding or Collapsing Items ............................................................................239 Finding Layer Objects ..............................................................................................................................................234 Using Feature Sensing..........................................235 Writing Cross-Browser DHTML ............................................................................................................................................................................................................215 Java ......................................215 Creating a Simple Animation ........................222 The ShowHide Function ................................................223 The MoveLeft Function ..........................................................................................................................................................................................227 Questions .......................................................................................................................................................................................216 Workshop: Creating an Animated Navigation Bar ............................................................................................................................................................................239 Finding Style Objects ......................................................................................................................................................................................................218 Planning Layers ....................215 Movies .........228 PART V Learning Advanced Techniques HOUR 17 Dealing with Browser Differences 229 231 DHTML Browser Differences ....................................227 Answers ...............................................................................................238 Internet Explorer 4 DHTML .237 Accommodating Older Browsers .................................................232 Feature Sensing ................................................................................................224 Putting It All Together ............221 Expand and Collapse All .........................................................................................................................................................................................xiv Sams Teach Yourself DHTML in 24 Hours Dynamic HTML ....................214 Flash...............................237 Testing in Multiple Browsers ..........................................243 ................232 Browser Sensing .....................................................................238 Creating Cross-Browser Functions...................................................................................216 Completing the HTML Document ........................................................................................................................................................................241 Summary ..........................................................................................................................................................................................................................................240 Workshop: Supporting Old and New Browsers ...........................................................................227 Q&A ............................................227 Quiz................................................243 Q&A .232 Detecting Browsers........

...................................................................270 Exercises .............244 HOUR 18 Using DHTML with Forms 245 Dynamic Forms....................................................................261 Defining Dynamic Fonts...........246 Creating the JavaScript Function..........................262 Using Truedoc Fonts ............................................................................260 Dynamic Fonts and Browsers .........................................................................................................268 Q&A ....................................................................................................................253 Completing the HTML Document ..................................263 Using Microsoft Fonts.....................................................................................................................................................................................................................................................247 Adding Form Elements..........270 ................................................................................................269 Answers ......................................................................264 Workshop: Using Dynamic Fonts...........................................................................................................................243 Questions ....250 Accepting Data from Forms ..............................................................................................................................249 Completing the HTML Document .........................................................................................................256 Q&A ..............................................256 Quiz...............257 Exercises ................................................................................................................................................269 Quiz.............................................................................................................................................................................................252 Workshop: Creating a Dynamic Order Form .........................................................................................................................................Contents xv Quiz.........................................................................................................................246 Creating the HTML Document ...........................................................................................................................................................................................................243 Answers ............................264 Using Microsoft’s WEFT Tool ..........................................265 Using a WEFT Font .......................................................................257 Questions ..................269 Questions .............266 Summary .....................................................................................................................................262 Using the Web Font Wizard ....244 Exercises .............................................................................249 Creating the JavaScript Function....................................................................................................................................................253 Showing the Ship-to Address ....................................................................................246 Modifying Form Elements ................................................................257 Answers ...........................................................261 Internet Explorer Dynamic Fonts ...................................................................................................................................................................................................................................................265 Using a Truedoc Font ................260 Netscape (Truedoc) Fonts ................................................................258 HOUR 19 Using Dynamic Fonts 259 How Dynamic Fonts Work ...........254 Summary ........................................................................................................................................................................253 Adding Items to the Form ................................................................................................................................................................................................................

........................................................................................................................................................274 Displaying Errors in Internet Explorer ....................................................................................................279 Fixing Minor Errors...................284 PART VI Putting It All Together HOUR 21 Creating a Dynamic Site 285 287 Creating Complex DHTML Sites......................................................................296 Creating the JavaScript File...288 Laying Out the Page ....................................................................................................283 Questions .................................................................................................................................................................................................................272 Common CSS Mistakes............................................................................................................................................................289 Defining Layers .......................................277 Workshop: Debugging a Document .....................................................................................................288 Defining the Menu....................................................................................293 Completing the JavaScript File ...................................................................................296 Modifying the HTML Document ........................................297 Testing the Modified Example .................................................................................290 Creating the JavaScript File ....................273 Common DHTML Mistakes .........................279 The Debugged Document ......................................................................................................................................................282 Q&A .272 Common HTML Mistakes .....273 Common JavaScript Mistakes ................................................275 Testing Dynamic Documents ......................................280 Summary ...........................................................................................298 Q&A ..................................................................288 Creating the HTML Document........272 Avoiding Common Mistakes .......................................274 Displaying Errors in Netscape............................298 ...................................................................................................................................................................................................................283 Exercises .........................................................................................297 Summary ..................................................................................289 Completing the HTML Document ................................................................................................................................................................................................................293 Modifying the Menu Function ........................................................................................................276 Using Debugging Tools .............................................................................................................................................................274 Analyzing Errors......283 Answers ....................................................................294 Workshop: Adding a Scrolling Message ..............................................................282 Quiz...............................................................................................................276 Testing Browser Compatibility ........................277 Fixing Major Errors....................................................................................................................................xvi Sams Teach Yourself DHTML in 24 Hours HOUR 20 Troubleshooting DHTML 271 Tips for Error-free DHTML ...........................................................................................................

.....................................................................................304 Animation with Multiple Images ............................................................................................................313 Answers .........318 Creating the JavaScript Functions ..................................................................................324 Creating the Word List ....308 Creating the Move Function .....................................................308 Changing Direction .......................................................................303 Putting It All Together .302 Detecting the Browser Type .........................................................................................................................................................................................................................................................................................................................................321 Handling Guesses ..........................313 Quiz......313 Questions ................................................................................................................................300 HOUR 22 Creating Complex Animations 301 Following the Mouse Pointer ............................................323 Ending the Game ...................................323 Completing the JavaScript File .......................................................................................................................309 Workshop: Completing and Testing the Animation .............................................................................326 ..................................................Contents xvii Quiz...............................................................................314 Exercises .........................................300 Exercises ...............................319 Drawing the Alphabet .................................................................................................................................302 Capturing Events ....................299 Answers ........................................302 Creating the HTML Document ...................................................................................................................................................................322 Updating the Hangman Graphic ........................................................................................................................................................................................................................................................................................................................................................................................................320 Choosing a Word ....................................................................................318 Setting Up Variables ........303 Creating the Move Function ............................................................................................................................................................................................299 Questions ..................................................................................306 Creating the Graphics ........................307 Setting Up Events ...............................................................................................................................314 HOUR 23 Creating a DHTML Game 315 Creating the HTML Document...............................317 Creating Graphics .............................307 Tracking the Mouse Pointer ......................................319 The Setup Function ...........................................321 Displaying Correct Letters ....................316 Planning Dynamic Features ................................................310 Summary ........................................................................................................................................312 Q&A .............................................................................................................................................................................................................................306 Setting Up Positioning Variables..............................................................................................................................

.....................................................................................................337 Where Do You Go from Here? .............339 Learning More ......................................................327 Testing the Complete Example .........................................347 Dynamic HTML Web Sites .........................................................................................................................338 The Future of DHTML .............................................343 Answers ................................................................................................................342 Q&A ........................................................339 Creating the JavaScript Function.................................................................................................334 Creating the HTML Document .........................330 Questions .........................................................................330 Exercises ........................................................................................................................348 Other Books ..342 Quiz............................................................................................................................339 Workshop: Creating a Scrolling Window .............................................................................................................344 PART VII Appendixes APPENDIX A Other JavaScript and DHTML Resources 345 347 JavaScript Web Sites ..................................................................350 CGI Resources .....................331 HOUR 24 DHTML Tips and Tricks 333 Creating Tool Tips ...................................................................................................349 Debugging Tools and Resources............................................................338 The Future of HTML and JavaScript .................................................................................................................................................................................................................................336 Completing the JavaScript File ..........................................348 Other Sites..................330 Answers .....................................................................349 Development Tools ..............................................................................................................................................................................329 Quiz.............................................................................................................................................................xviii Sams Teach Yourself DHTML in 24 Hours Workshop: Adding the Style Sheet.........343 Questions .....................................................................................................................................................................................................329 Q&A ....................................................................................328 Summary ...........................................341 Summary ......................................................................................................................................................................................................................................339 Creating the HTML Document ..................................................................................................................................................................................................................344 Exercises ......335 Hiding Tips ........................................................................350 APPENDIX B Glossary APPENDIX C Browser Compatibility Chart 353 357 ...................................................................................................................334 Showing Tips .........................................................................

.............................................................................................................................................................................................................361 Window ............363 Navigator .........362 History .............................363 Document..363 DOM Level 1 ..365 Node Methods ...............................Contents xix APPENDIX D DOM Quick Reference 361 DOM Level 0 ..................365 Document Object Methods and Properties ......................................................364 Relationship Properties ........................................................................................................................................................365 Style Properties ............................................................................................................................................................................................................................................................................................................................................................................................362 Location ............................364 Basic Node Properties ....................................................................................................................................................................366 Index 367 ...........................................................364 Offset Properties ........................................................................................

and an independent Web developer.About the Author Michael Moncur is the owner of Starling Technologies. . He has written a number of books. including Sams Teach Yourself JavaScript in 24 Hours and several other best-selling books on networks and MCSE training. a network consulting firm.

Richard Easlick. particularly Chuck Perkins. Melanie. and the tech reviewer. The editor. I’d also like to thank David Rogelberg. Curt Siffert. In particular. saved me from glaring technical errors. Robert Parsons. Vicki Harding. Laura. . Gary and Susan Moncur. and the rest of the team at Studio B for their help throughout this project. Jason Byars. Cory Storm. Tillman. James Chellis. and Kristen). my parents. the rest of the family (not to forget Matt. and for the opportunity to write it. Ian. who tend to be neglected when I’m nearing a deadline. personal thanks go to my wife. helped me write with clarity. Scott Durbin. Scott Meyers managed the project and kept things moving along. Finally. Laura. Acknowledgments I’d like to thank everyone at Sams for their help with this book. and Amy Patton was very helpful with some of the details. Charlotte Clapp handled the final production process. and my friends. and Henry J. Dylan Winslow. Ray Jones. I couldn’t have done it without your support.Dedication To my family and friends. and especially to my wife. Damon Jordan. Matt Strebe.

E-mail: Mail: webdev@samspublishing. I will carefully review your comments and share them with the author and editors who worked on the book. what areas you’d like to see us publish in. Please note that I cannot help you with technical problems related to the topic of this book. you are our most important critic and commentator.com Mark Taber Associate Publisher Sams Publishing 800 East 96th Street Indianapolis. I might not be able to reply to every message. please be sure to include this book’s title and author. what we could do better. When you write. and any other words of wisdom you’re willing to pass our way.Tell Us What You Think! As the reader of this book. IN 46240 USA . as well as your name and phone or fax number. You can e-mail or write me directly to let me know what you did or didn’t like about this book—as well as what we can do to make our books stronger. We value your opinion and want to know what we’re doing right. and that due to the high volume of mail I receive.

I hope you’ll take the time to learn the techniques behind them. Each covers a single DHTML topic. You can study an hour a day. and positioning. and continue with more advanced topics. and the newly standardized W3C DOM (document object model). DHTML (Dynamic HTML) is a combination of technologies that work together to give Web developers unprecedented control over their pages. The lessons start with the basics of DHTML and CSS. so do the technologies behind it. As the Web evolves. . the JavaScript scripting language. CSS (Cascading Style Sheets) are an important aspect of DHTML and account for four chapters of this book. and content within the page can be reformatted. DHTML allows you to do some truly exciting things. While you can do some incredibly sophisticated things with DHTML. or changed in real time. and I’ve had lots of fun while writing this book. or whatever pace suits you. and before long you’ll be developing innovative new features for your site. The components of DHTML include the HTML language that formed the foundation of the Web. Pages can be laid out in precise fashion. colors. and other nerds. DHTML will be easy to add to your library of skills. I hope you find your DHTML experience equally enjoyable as well as practical. programmers. The Web has only scratched the surface of DHTML. layout. you can also do simple things. and should take about an hour to complete. CSS gives developers control over fonts. If you’ve created Web pages with HTML and tried a bit of scripting in JavaScript. added. While you can have all sorts of fun adding DHTML to your Web pages just by copying the scripts in this book.Introduction The World Wide Web started out as a novelty used by engineers. the CSS standard for style sheets. using a standard syntax. and has evolved into the most talked-about communication medium of the new millennium. How to Use This Book This book is divided into 24 lessons.

you’ll find three final sections. includes the latest updates for this book and the latest DHTML news. DHTML made its debut in the 4. and compatibility issues are described in connection with some of the examples. The site also includes downloadable versions of the listings and graphics for the examples in this book. Here’s the URL: http://www. or have trouble getting one of the scripts to work. and the Exercises offer ways for you to gain more experience with the techniques the hour covers.2 Sams Teach Yourself DHTML in 24 Hours Q&A. have noticed an error. While there are differences between the latest versions of Internet Explorer and Netscape. and these are pointed out as they appear. This book’s Web site.com.) . The emphasis is on standard code for standards-compliant browsers. you can also reach the author by e-mail at dhtml@starlingtech.0 or later Some listings will also work in the 4.0 or later • Netscape 6. (Please check the Web site first to see if your question has been answered.0 browsers or can be easily adapted to them. and many different browsers are in use—most of them versions of Microsoft Internet Explorer and Netscape. This Book’s Web Site Since DHTML and other Web technologies are constantly changing and books are static. answers to the exercises in this book. there are no single-browser examples in this book. Quiz.com/dhtml/ If you have questions or comments about this book. you should keep an eye on the latest developments after reading this book. The Quiz includes three questions to test your knowledge. and a message board where you can discuss DHTML with other users. and this book’s emphasis is on the cross-browser features of the DOM. but has vastly changed in the latest versions. This means that most of the examples in this book will require one of the following browsers: • Internet Explorer 5.0 versions of these browsers. Q&A answers a few of the most common questions about the hour’s topic. and Exercises At the end of each hour’s lesson. maintained by author Michael Moncur.starlingtech. The new W3C DOM makes cross-browser DHTML possible. A Note About Browsers The Web is in flux.

PART I Getting Started Hour 1 Understanding DHTML 2 Reviewing HTML 3 Understanding JavaScript 4 Creating a Simple DHTML Example .

.

where it comes from. DHTML has been one of the hottest browser technologies introduced in the past few years. To begin your 24-hour tour of DHTML.HOUR 1 Understanding DHTML While it started with some confusion between Netscape and IE versions. Hour 1 covers the following topics: • What DHTML is and what it can do • The components that make up DHTML • The history of DHTML • What the DOM is and how its versions differ • Which browsers support DHTML . It adds life to otherwise boring Web documents and allows Webmasters to go beyond basic tools such as HTML and JavaScript. this hour presents an overview of DHTML—what it is. and how it can make your life easier and your Web pages more exciting.

While JavaScript adds life to static HTML. from its title to the fine print at the bottom. revolutionized Web pages by making them dynamic. it’s a way of using various technologies (including HTML) to create more dynamic pages than HTML by itself is capable of. but the specifications had little in common besides their name.0 browsers. graphics that change when you move the mouse over them. It isn’t. Static and Dynamic Pages If you’re reading this book. the most popular client-side scripting language for Web pages • The DOM (Document Object Model). Rather. a set of objects that can be used to control every aspect of Web pages from JavaScript or other languages Both Microsoft and Netscape introduced DHTML with their 4. and those annoying scrolling status-line messages. Fortunately. HTML tags are used to define every part of a Web page. but there is no way to change the heading on the top of a page or an arbitrary bit of text within the page. JavaScript has brought us forms that update dynamically and warn you when you enter incorrect data. a standard method of specifying the appearance of Web pages • JavaScript. cross-browser DHTML is becoming easier to manage. The name DHTML might give you the idea that DHTML is a version of HTML. it is generally considered to be a combination of four key technologies: • HTML (Hypertext Markup Language). the standard language for defining Web pages • CSS (Cascading Style Sheets). or forms in real time. JavaScript. the status line. it doesn’t make an entire Web page dynamic: Scripts can change graphics. thanks chiefly to the W3C’s standard for the DOM. .0 in 1995. the display on your browser generally doesn’t change unless you follow a link to a new page.6 Hour 1 What Is Dynamic HTML? Dynamic HTML (DHTML) is a combination of technologies that allow Web designers to control the appearance and behavior of Web pages in new ways. Basic HTML documents are static. While there is no official definition of DHTML. a scripting language first introduced in Netscape 2. chances are you’ve used HTML before. HTML (Hypertext Markup Language) is the foundation of the Web.

your own menus will work in any browser that supports the W3C DOM. . or graphics that change when you move the mouse pointer over them. 1 Dynamic HTML Menus As an example of the power of DHTML. or even the entire page. think about the mouseovers. The MSN menu is currently selected. using the new objects made available by the DOM. As an example. you can bring this same ability to text menus. Figure 1. that are prevalent on today’s Web. At this writing. Microsoft’s site uses DHTML specific to Internet Explorer.1 shows the main page of Microsoft’s Web site. Using DHTML.1 Microsoft’s Web site uses DHTML menus. These are accomplished by using JavaScript to replace one image with another. your script can modify any portion of the page: any word. Using the DOM. You can even use DHTML to create a menu system similar to the one your computer uses. FIGURE 1.Understanding DHTML 7 DHTML removes these limitations. If you follow the guidelines in this book. any link. style. or font dynamically. You can use the same JavaScript language to achieve this. Notice that the options at the top expand into submenus of further options. and the menus won’t work in Netscape. The words in your menu can change color.

You’ll learn more about DHTML animation and create some examples in Hour 16. it was centered around the concept of layers: blocks within a Web page that can be hidden. “Using DHTML for Animation. you can dynamically change the position of the object. Now there’s a standard and precise way to control the font. “Creating Positionable Elements (Layers). size. or text can move across the screen for emphasis. “Dealing with Browser Differences.8 Hour 1 Positioning and Animation While normal HTML does not allow you to specify the exact position of an object in the browser window. but it can also be used in standard pages—menus can slide on to the screen when activated. shown.” Another reason to use layers is that you can create a version of your script that works in Netscape 4.0. when used conservatively and appropriately it can be a striking effect. While DHTML animation ranks right up there with blinking text and scrolling messages on the list of Things You Should Think Twice About Before Doing. color.” Text Effects CSS (Cascading Style Sheets) revolutionizes the use of text on the Web. While Netscape and Internet Explorer supported vastly different methods of using layers. While the new DOM allows you to control just about anything on the page dynamically in a cross-browser fashion. You’ll learn how to work with layers in Hour 6.” Layers When DHTML first appeared in the 4. they were still a popular element of dynamic sites. DHTML animation is useful for games and special effects. layers are still a useful way of handling blocks within a page.” and Hour 22. “Creating Complex Animations.0 or IE 4. .0 browsers. Furthermore. such as sidebars or menus. or moved dynamically. allowing for animation. and position of text within your Web pages. You will learn how to do this in Hour 17. you can do this with CSS and DHTML.

and so on. The newest HTML standard also includes some tags.Understanding DHTML 9 While you can control the presentation of text to some extent with regular HTML.” The Components of DHTML As mentioned earlier in this hour. paragraphs. colors. Nevertheless. move across the screen. or font on command. You will still use the same tags to define headings. and older browsers will still be able to view your document without the benefit of the style sheet. such as <div> to define a section of text.” CSS (Cascading Style Sheets) HTML was always meant to define the content of documents—titles. is a standard defined by the W3C (World Wide Web Consortium). Using CSS. DHTML is actually the combination of several different technologies that add dynamic features to HTML. you’ll learn more about how these components interact to form a dynamic page. it’s a way to add dynamic features to HTML Web pages. and layout. sizes. As you begin to work with DHTML. you can control your page’s appearance in a standard way. In the following sections. HTML HTML. or change size. the language still used for most Web documents. “Reviewing HTML. headings. 1 You’ll learn the details of CSS in Part III. “Working with Style Sheets. it is more important than ever to be sure you are using HTML syntax correctly. DHTML is not a version of HTML—rather. over the years Web designers and browser makers have coerced it into defining presentation—fonts. color. that are very useful with DHTML. “Creating DHTML Text Effects. You’ll learn how to create various text effects in Hour 15. You can make text fade in or out. links. .” You can also use DHTML to make text dynamic. paragraphs. A Dynamic HTML document begins with basic HTML. and links as always. it produces complex HTML that doesn’t meet standards and can even crash some browsers. You’ll review what you need to know about HTML in Hour 2.

the objects are still static until you use a scripting language to change them dynamically.0 in 1995. defined by the <body> tag. or DOM. Since JavaScript is a fundamental part of DHTML. such as Microsoft’s VBScript. and other elements within the page. while still allowing for older browsers and for viewers who prefer to keep their own styles. you’ll spend four hours learning more about it in Part III. Other Web languages. “Working with Style Sheets. to work with the DOM and Dynamic HTML. Microsoft’s alternative language. and objects under this object for all of the paragraphs. links. JavaScript is the Web’s most popular scripting language. or scripts.” The Document Object Model (DOM) The most important part of DHTML is the Document Object Model.” While JavaScript is the most popular scripting language and will be used throughout this book. to perform various functions. VBScript. can also work with the DOM. Along with its popularity. “Understanding JavaScript. The DOM is a hierarchy of objects that represent the various parts of a Web page. This can be used alongside HTML and provides even more control. For example. Since CSS is an important part of DHTML. and has existed in some form since the release of Netscape 2. is supported only on Windows platforms. you can also use other scripting languages. JavaScript While the DOM defines objects for each part of a Web page. you will review the language in Hour 3. . Scripting languages use short sets of commands. there is an object for the body of the page. such as Java.10 Hour 1 CSS (Cascading Style Sheets) is an effort by the W3C (World Wide Web Consortium) to create a separate standard to define presentation. JavaScript is also the most universal Web scripting language.

Since the DOM is at the foundation of DHTML. or images.2 shows the basic hierarchy of objects in the Level 0 DOM.0 browsers. you’ve used this simple DOM. “DOM Quick Reference. top) history images[ ] location forms[ ] form elements . links[ ] document anchors[ ] window (parent. With the newest browsers and the W3C DOM standards. although they are not a W3C standard. and was expanded in two different directions by Netscape and Microsoft with the release of the 4.” summarizes the Level 0 DOM objects. frames[ ]. self. It began with the brief selection of features introduced with JavaScript. While these were not standardized. forms. Figure 1. If you have ever used JavaScript to manipulate the status line. 1 DOM Level 0 When Netscape first released JavaScript. a window. such as Sams Teach Yourself JavaScript in 24 Hours by Michael Moncur.0. the following sections take a brief look at the different DOM versions. they were largely supported by Microsoft as they developed the subsequent versions of Internet Explorer. These objects are informally referred to as DOM Level 0. FIGURE 1. DHTML has been revolutionized once again.Understanding DHTML 11 History of DHTML and the DOM DHTML has had a short but stormy history. You can find more information about the Level 0 DOM in JavaScript books.” Appendix D. “Other JavaScript and DHTML Resources. and more objects were added in Netscape 3. it included a hierarchy of objects referred to as the DOM.2 DOM Level 0 uses a simple hierarchy of objects. Some Web references for the Level 0 DOM are listed in Appendix A.

This W3C recommendation includes the basic Level 0 objects that were generally already supported by both popular browsers. Unfortunately.0 browsers. both Netscape and Microsoft pledged to support the W3C DOM standard.0 were the first versions to support the standard DOM. Netscape 6. DOM Level 1 Fortunately. known as DOM Level 1. the W3C is currently working on DOM Level 3. including the ability to change styles (those defined by CSS style sheets) dynamically in a standard way. Both had also vastly expanded the selection of DOM objects supported. Level 2 adds a number of features. With the release of the 4. Level 1 also includes objects that allow the manipulation of any part of a Web page. Unfortunately. .12 Hour 1 Browser-Specific DOMs As browsers became more sophisticated. so did their object models. the W3C stepped in and created a standard hierarchy of DOM objects. For details on the DOM specifications.org/DOM/.0 were the first two browsers to support the new style of DHTML using the W3C DOM. which focuses mainly on supporting XML (extensible markup language).w3. At this writing. After much protest from Web designers who had endured their share of headaches dealing with multiple DOMs. neither of these supports it perfectly and there are still differences between the browsers. They had very little in common.0 and Internet Explorer 5. both Microsoft and Netscape proudly announced that they had invented Dynamic HTML. These allow the same features as the browser-specific extensions. DOM Level 2 The W3C continued to work on the DOM specification and has now released DOM Level 2 as a recommendation. see the W3C’s Web page at http://www. The new DOM features allowed dynamic features such as layers. the two browsers used two different object models for the new objects. and the hardest part of using DHTML was detecting which browser was in use and arranging separate script commands for each one. but in a standard way. DHTML Browsers As mentioned earlier in this hour.0 and Internet Explorer 5. Netscape 6.

CSS. and how the current browsers support DHTML. You should have one of these browsers to follow along with the examples in the remaining hours of the book.0 browsers using the techniques described in Hour 17. . Many of the examples can also be adapted to work in the version 4. A. Q. if you follow the W3C standards. and the DOM and how they work together to create dynamic pages. you can be sure your dynamic pages will work with future browsers from Microsoft. Absolutely not! If you can understand HTML and some basic JavaScript. or anyone else. You’ve learned about HTML. including older browsers. This attitude is surprisingly common. In the next hour. 1 Unless otherwise noted. Summary In this hour. JavaScript. all of the examples in this book were tested and will run on Netscape 6. Actually. In fact. Do I need to take programming classes to understand it? A. DHTML sounds difficult. You’ll learn the important parts of HTML syntax that can make or break a DHTML document. you’ve learned the basis of DHTML. you’ll take a step back and review the HTML language.Understanding DHTML 13 Browser differences will be mentioned throughout this book in the appropriate places.0 or later.0 or later and Internet Explorer 5. More importantly. for most sites. Netscape. Q&A Q. you can easily add DHTML features to your pages. CSS and DHTML sometimes offer an easier way to accomplish something than traditional HTML and JavaScript. and the special objects that are important for DHTML. Why should I support Netscape? Everyone uses Internet Explorer anyway. Hour 17 provides details on the differences between browsers. You’ve also learned the history of DHTML and the DOM. between 10 and 25% of users still use Netscape browsers.

A new version of HTML with dynamic features b. . DHTML 2. (If you chose answer B. However. ActiveX. DOM c. Microsoft b. A combination of technologies that add dynamic features to HTML documents 3. or other Web programming languages with the DOM? A. Which of the following is a collection of objects that represent parts of a Web page? a. you should check whether browsers support these features. CSS b. you’re partially correct. DHTML (Dynamic HTML) is a combination of technologies that allows you to add dynamic features to HTML documents. The W3C Answers 1. c. Yes. Netscape c. 2. Who developed the new. standard DOM? a. Which of the following is a good description of DHTML? a. A catchy marketing abbreviation that doesn’t really mean anything c. The DOM (Document Object Model) is a collection of objects that represents parts of a Web page. Questions 1. c. b. Quiz Test your knowledge of the material covered in this hour by answering the following questions.) 3. the DOM is language-independent. The DOM is a standard developed by the W3C (World Wide Web Consortium). Can I use Java. You must have suffered through the browser wars long enough to become a cynic.14 Hour 1 Q.

starlingtech. http://www. 1 . perform these exercises: • Prepare yourself for the rest of this book by making sure you have Internet Explorer 5. There you’ll find links to a variety of DHTML examples you can try in your browser.com/dhtml/. • Open this book’s Web site.0 or later installed on your computer.0 or later or Netscape 6.Understanding DHTML 15 Exercises If you’d like to get a better idea of what DHTML can do for Web pages.

.

Although it adds powerful features. body. Before you delve deeper into DHTML. and other sections • How HTML achieves basic text styling • Creating forms in HTML • Creating a basic HTML Web page . you should have a grasp on the fundamentals of HTML.HOUR 2 Reviewing HTML The Web has revolutionized the world of information. and the HTML language is a key part of Web technology. text styles. and forms. Hour 2 covers the following topics: • The syntax of basic HTML documents • How to define document header. ways of defining document sections. This hour reviews the basics of HTML—its syntax. DHTML still uses HTML at its core.

An HTML document is essentially a text document. Tags Tags are the fundamental unit of HTML syntax. The following sections review the basics of HTML syntax. If you’re an HTML expert.</p> Some tags don’t require closing tags. here is a simple section of HTML that uses the <p> and </p> tags to define a paragraph: <p>This is a paragraph.<br> It’s split into two lines. with tags surrounding portions of the text. you will use the same HTML tags. as shown in this example: <p>This is a paragraph. “Other JavaScript and DHTML Resources. the <br> tag defines a line break. But be sure that you review the information on the <div> and <span> tags. for dynamic features to function properly. the following tag defines an image: <img src=”eggplant. and all of the parts of a page—headings. Attributes Many HTML tags use one or more attributes. When you create Dynamic HTML pages.</p> The rest of this hour presents some of the most useful HTML tags. However. you should be sure you are creating valid HTML. As an example.” for a list of Web sites with HTML information. or parameters that define options for the tag. However. The ending tag uses a slash (/) to indicate the end of that block. For example. Tags use the less-than and greaterthan symbols (< and >) around each keyword. you’ve worked with HTML (Hypertext Markup Language). and links—are represented by HTML. and be sure you understand the example in the Workshop section. you can skim this hour. For example. Most tags have a beginning tag and an ending tag. HTML is the fundamental language of the Web. paragraphs. this is by no means a complete reference. See Appendix A. lists.gif”> .18 Hour 2 Basic HTML Syntax If you’ve ever created a Web page.

0. The <html>. exist for the same purpose. . • The opening and closing <head> tags define a header for the document. This organization is responsible for keeping the official documentation of HTML syntax. The current version of HTML is HTML 4. 2 The HTML Standard The HTML standard is maintained by the W3C (World Wide Web Consortium). dividing it into large sections such as the header and body. A number of attributes can be present for any type of tag. Defining Parts of a Document The HTML tags you use most often will define the structure of the Web page. <head>. still work in today’s browsers. which centers text. Some older tags might be deprecated. With each version.gif). While deprecated tags. such as CSS styles. Tags are usually deprecated because alternative methods. the <center> tag. the W3C adds new standard tags. which you can find on their Web site: http://www. and <body> Tags There are some tags you’ll never create an HTML document without: • The <html> and </html> tags are the first and last tags in any document.01. like <center> and <font>. and smaller sections such as individual paragraphs. meaning they might still be supported but should be avoided. it’s likely they’ll be unsupported at some point in the future. These include the style and class attributes for CSS styles. You’ll learn more about these later in this book. is deprecated in HTML 4. and the ID attribute for styles and DHTML.org/. Anything between the opening and closing <html> tags is expected to be in the HTML language. The following sections review some of the most important HTML tags for document structure.Reviewing HTML 19 This <img> tag uses the src attribute to assign the filename and location for the image to be displayed (eggplant.w3c. For example.

and the <br> tag for line breaks. All tags that define the page’s content will reside between the <body> tags. notice two fundamental rules of HTML structure: First of all. each tag has an opening and closing tag. when tags are nested (contained) within other tags. and this still works in most browsers.</p> <p>This is another paragraph. the <p> tag could be used by itself between paragraphs. to ensure your documents will work with DHTML and CSS style sheets.20 Hour 2 • The <title> tag is used in the header of the document to assign it a title. Today’s browsers are pretty forgiving. . Second. Paragraphs As we’ve already mentioned. LISTING 2. DHTML relies on good HTML syntax. Here’s another quick example: <p>This is the first paragraph. without the closing </p> tag. However. you should always use both opening and closing tags as in the example above. so following these rules will prevent some difficult debugging as you add dynamic features. However. and will often display a document even if you omit a closing tag or use the wrong order for nested tags.1 shows the skeleton of a typical HTML document using all of these tags. This is typically displayed in the browser’s title bar.1 The Structure of a Typical HTML Document <html> <head> <title>This is the title</title> </head> <body> The body text goes here. Listing 2. </body> </html> In this example. the </body> tag comes before the </html> tag. • The opening and closing <body> tags define the actual body of the document.<br> It’s split into two lines. you can use the <p> and </p> tags to delimit paragraphs within your document.</p> In earlier versions of HTML. the inner tag ends before the outer one: For example.

2 In today’s popular browsers. .Reviewing HTML 21 Headings You can use the <h1> through <h6> tags to define headings within your document. one centered and one aligned to the left by default: <h1 align=”center”>Top-level heading</h1> <h2>Next-level heading</h2> Ordered and Unordered Lists HTML also allows you to define lists of items with two tags: • • <ul> <ol> defines an unordered list. <h1> headings are quite large and imposing. or right to determine its location horizontally on the page. “Working with Style Sheets. usually displayed as a bulleted list defines an ordered list. and <h6> headings are actually smaller than body text. Here is a quick example of an unordered list: <ul> <li>First item</li> <li>Second item</li> <li>Third item</li> </ul> HTML includes other. center. less commonly used types of lists. Ideally. the <li> tag defines each item in the list. you will use <h1> to label the largest sections of your document. and lower-level headers are displayed in smaller fonts. Here is an example of two headings.” you’ll learn how to solve these problems using CSS. usually displayed as a numbered list Within the opening and closing tags for a list. <h1> headers are displayed with the largest font. including dictionary lists and directory lists. In Part III. Each heading tag can have an align attribute with the value of left. Consult one of the HTML references in Appendix A for more information. and other headings to label smaller sections within those sections.

you use the src attribute to specify the image’s filename. You can also use other attributes.com/”>Visit Microsoft</a> You can also name an anchor. Here are two examples of links: <a href=”page2. Here is an example of an <img> tag with these attributes: <img src=”persimmon. including width and height to specify the image’s size and align to specify how it should line up with text.html”>Next Page</a> <a href=”http://www. This allows you to link to a fragment of a large document. you use the pound sign (#) followed by the anchor name. Anchors are most commonly used to link to another Web page. JPEG. The following is a link to the anchor defined in the previous example: <a href=”#glossary”>Go to the glossary</a> Divisions and Spans Last but not least. you should always include these tags to avoid potential browser errors. and the text between the opening and closing <a> tags is highlighted and clickable in the browser. whether on the same site or anywhere else on the Web. or PNG format.gif” align=”center” width=”100” height=”200”> The width and height attributes are normally optional. However. As mentioned earlier in this hour. the <div> and <span> tags allow you to define arbitrary parts of a document: . when you are using DHTML to dynamically change a document. The following is an example defining an anchor called glossary: <a name=”glossary”> </a> To link to an anchor within a page. whether linked or unlinked. typically in the GIF.Microsoft. Links and Anchors You can use the <a> tag to define an anchor within the page. One reason to include them is that they speed up the display of a page. The href attribute specifies the URL for the destination of the link.22 Hour 2 Images The <img> tag allows you to insert an image into your document. with the <a> tag’s name attribute.

In most cases. rather than using the deprecated <center> tag.0 standard. this is not commonly used because most browsers use underlining to indicate links. center. Styling Text HTML also includes a number of tags that can be used to change the appearance or layout of text. However. . or right. Here’s a quick example with an ID attribute: <div ID=”article”>This is the text within the tags. You can then manipulate that text’s style with CSS. While these might seem like the most useless tags in the language. and you’ll use them constantly throughout this book. or even pick up the text and move it across the screen using DHTML. style. <b>This sentence is bold. <b>This is both bold and italic. You can use the ID.Reviewing HTML 23 • Sections defined by <div> are displayed with a line break before and after them. Bold and Italics The <b> and <i> tags define bold and italic sections of text. The <div> tag has another purpose: <div align=”center”> is currently the best way to display centered text. The following example shows both in action: <p>This is normal text.</b></i></p> You can also use the <u> tag to define underlined text. You can also underline text in a standard way using CSS styles. such as headings or paragraphs. The following sections review some of the most common tags for styling text. they’re actually very important for CSS and DHTML.</b> <i>This one is italic. • Sections defined by <span> aren’t formatted in any particular way at all. and class attributes with either of these tags to uniquely identify a section of text. <div> and <span> are just good ways to assign styles or dynamic properties without causing the browser to format the text in any particular way. but with no other explicit formatting. underlining can be denoted by the use of italics. and has been deprecated in the HTML 4.</div> 2 You can also use these attributes on other HTML tags. You can use the align attribute to specify the text’s horizontal position: left.

Indenting You can use the <blockquote> tag to enclose text that is quoted from another source. <tr> tags enclose table rows. and colors to text. and <td> tags enclose each cell of the table. two sizes larger than normal and red in color: <font face=”sans-serif” size=”+2” color=”red”>Hello!</font> You won’t be seeing the <font> tag again in this book. this is available using style sheets. the following displays some text in a sans-serif font. sizes.0. Using Tables for Layout Tables allow you to lay the content of a document out in columns and rows. For example. The following is an example of a simple table: <table> <tr> <th>Fruits</th><th>Vegetables</th> </tr> <tr> <td>Apples</td><td>Peas</td> </tr> <tr> <td>Oranges</td><td>Carrots</td> </tr> </table> . and style sheets are a much better way to assign fonts. If you need a more versatile method of indenting text. Why? Because it’s deprecated in HTML 4. You’ll learn more about them in Part III.24 Hour 2 Fonts You can use the <font> tag to define a particular font for a section of a document. CSS style sheets can do everything the <font> tag can do and much more. <th> tags define cells that are headings for the table. This is typically displayed with an indentation. The <table> tag is used to define the start and end of the table.

and can also be used with JavaScript and DHTML to add interactivity to pages. . Using DHTML. This is explained in Hour 18.Reviewing HTML 25 Creating Forms Forms are an important part of interactive Web pages. FIGURE 2.” 2 The <form> Tag Forms begin and end with the <form> and </form> tags. Figure 2. you can change forms dynamically based on information the user enters. They can be used with server-side languages such as CGI to gather information. Here is a simple example using these tags: <form name=”form1”> form elements go here </form> The following sections will review some of the elements you can use within a form.1 shows an example of these form elements in use. “Using DHTML with Forms.1 Forms can include a variety of elements.

to indicate that the checkbox will be checked by default. For example. but you can only choose one option within each group of buttons. If the checked attribute is omitted. You can also define a larger area for text input with the <textarea> tag. You define radio buttons with the <input type=”radio”> tag. . Here’s an example: <textarea name=”text1” rows=”5” cols=”70”> This is the default text for the text area. as in this example. </textarea> Checkboxes and Radio Buttons Checkboxes are handy for a simple on/off value or yes/no choice. you give them the same value for the name attribute. You can have several groups of radio buttons within a form with different group names. This allows you to define an area with a number of rows and columns for text. Here is an example with three choices: <input type=”radio” name=”group” value=”opt1” checked> 1 <input type=”radio” name=”group” value=”opt2”> 2 <input type=”radio” name=”group” value=”opt3”> 3 To include the radio buttons in a group. Radio buttons are similar to checkboxes. The name attribute gives the field a name—this will be useful if you are using JavaScript or DHTML to work with this form element. this tag defines a text input 10 characters wide with the default value of “your name here”: <input type=”text” name=”thename” value=”your name here” size=”10”> The value attribute specifies the default value.26 Hour 2 Text Input You can use the <input type=”text”> tag to define a text input within a form. Here is an example: <input type=”checkbox” name=”check1” value=”yes” checked> You can include the checked attribute. The text between the opening and closing <textarea> tags is the default contents. You can define them using the <input type=”checkbox”> tag. the checkbox will be unchecked by default. You can specify the checked attribute for one of the buttons in a group to make it the default selection.

here is the HTML that was used to create the three buttons in Figure 2. you can use one or more buttons within a form. It doesn’t do anything unless you use JavaScript to perform an action.1: <input type=”button” name=”generic” value=”Generic”> <input type=”submit” name=”submit” value=”Submit”> <input type=”reset” name=”reset” value=”Reset”> Workshop: Creating a Web Page with HTML To complete this hour’s tour of HTML. This document will be the home page of Figby Industries. <head>. As an example. or selection list. Your HTML document will include the following: • <html>. To define a list. you use the <select> and </select> tags. There are three types of buttons: • • • <input type=”submit”> creates a submit button. Here is an example with two options: <select name=”choice”> <option value=”1” selected>First Option</option> <option value=”2”>Second option</option> </select> 2 The text between the <option> and </option> tags is displayed in the drop-down list when that option is selected. This simply clears all of the fields within the current form. Buttons are commonly used to submit a form’s contents. you will now create a simple HTML document. This submits the data in the cur- rent form to the server. You can use the selected attribute to indicate a default choice.Reviewing HTML 27 Drop-Down Selections Another way to give the user a choice of options is a drop-down list. <input type=”button”> creates a generic button. and <body> tags to define the basic structure • A heading using <h1> tags . an imaginary company with imaginary products. with two or more <option> tags in between. <input type=”reset”> creates a reset button. Buttons Last but not least. but you can also use buttons to interact with JavaScript and DHTML. You define buttons with the <input> tag.

you should have a copy of Netscape 6 or Internet Explorer 5 or later for future examples.</p> </body> </html> This example will work in Netscape 2. Save the file. However.html”><b>Sales</b></a></td> <td width=”20%”><a href=”service. LISTING 2.2 shows the complete HTML document.0 or later.0 or later or Internet Explorer 3.gif” width=”486” height=”180” border=”0” alt=””><br> <h1>Welcome to Figby Industries!</h1> <p>Welcome! This is the home page of Figby Industries.html extension.html”><b>Products</b></a></td> <td width=”20%”><a href=”sales.html”><b>Employment</b></a></td> </tr> </table> <p>Any truly legitimate company would have much more text in this part of the page than we have. To try this example.</title> </head> <body> <img align=”center” src=”logo.html”><b>Service</b></a></td> <td width=”20%”><a href=”staff. .2 The Example HTML Document <html> <head> <title>Figby Industries. type the HTML into a text editor. giving it a name with the . Follow the links below to learn more about our company and our products. but be sure to save the file as an ASCII text file.28 Hour 2 • An image displaying the company logo • A paragraph of introductory text • Several links to other pages within the site • A table to lay out the links in a row Listing 2. You can use a word processor. Inc.html”><b>Staff</b></a></td> <td width=”20%”><a href=”jobs. your source for all sorts of imaginary products.htm or . </p> <table border=”1” align=”center”> <tr> <td width=”20%”><a href=”products.

you created a simple HTML document. you can load it into a browser. starlingtech. 2 The example HTML document you have created isn’t much yet. including those for forms and some tags that will be useful for DHTML. You’ve learned about some of the most useful HTML tags and attributes. Summary In this hour. You can download this image from this book’s Web site: http://www. Finally. In the next hour. you’ll review the JavaScript language.gif.Reviewing HTML 29 To display this document properly.2 Netscape displays the completed HTML document. logo.com/dhtml/. you’ve reviewed the basics of HTML. You’ll also use JavaScript to add features to the HTML document you created in this hour.2 shows how Netscape 6 displays this example. . another essential part of DHTML. referenced in the <img> tag. FIGURE 2. you’ll need the image. You can also download the HTML document to avoid typing it yourself. After you’ve saved the file. but we will enhance it in the upcoming hours with JavaScript and DHTML. Figure 2.

A DHTML tag 2.01 standard. How does this relate to HTML? A. b. c.30 Hour 2 Q&A Q.01. but with stricter syntax. with somewhat unpredictable results. An HTML tag c.</title> <h1>This is the Title. The HTML examples in this book follow the HTML 4. the browser will do its best to display the page despite the errors. Which of the following tags will not affect the display of the document at all unless you use style sheets or DHTML? a. Quiz Test your knowledge of the material covered in this hour by answering the following questions. Q. Can I test whether my HTML is valid? A. It is similar to HTML 4. However. Yes. <p size=”large”>This is the Title. Several HTML validation programs are available. It depends. An HTML attribute b. more likely. XHTML is a version of HTML based on the XML (extensible markup language) standards. Which of the following will display a title in large text within the body of a Web page? a.</p> <title>This is the Title. b. Some errors will cause an error message to be displayed. Questions 1. See Appendix A for links to some of them. What happens if I make a mistake in my HTML coding? Will the browser display an error message? A.</h1> 3. Q. c. <center> <div> <span> . <input type=”text”> is an example of which of the following? a. I’ve heard about XHTML.

. c. The <title> tag (choice b) sets a title for the document. 2. but it does display with line breaks and can be used to align text. b. 2 Exercises If you’d like to get a little bit more practice with HTML before you move on to bigger and more dynamic things.Reviewing HTML 31 Answers 1. <input type=”text”> is an example of an HTML tag. 3. and notice just how complicated HTML can get. c. try the following exercises: • Add a second row of links to the HTML example in the Workshop section. You can use the <h1> tag to display a title in the body of the page in large text. <div> (choice b) is close. The <span> tag does not affect the document’s display at all by default. but it is only displayed in the browser’s title bar. use your browser’s View Source option. • Visit a few of your favorite Web sites.

.

The following topics will be covered in this hour: • The basics of JavaScript syntax • How to avoid problems with older browsers • How variables. In this hour. but you should have a solid grasp of JavaScript to understand the DHTML examples in the rest of this book. feel free to skim this chapter.HOUR 3 Understanding JavaScript DHTML isn’t a new Web language—it’s just a set of objects that allows you to use a scripting language (such as JavaScript) to manipulate the page you set up in standard HTML. strings. you’ll review the essentials of the JavaScript language. and arrays work in JavaScript • Using JavaScript objects to store data and functions • Using Conditional statements in JavaScript • Using loops to repeat JavaScript statements • Creating and using functions in JavaScript . If you’re already a JavaScript expert.

Hiding JavaScript Code Some older browsers. This tells the browser to interpret the commands between the tags as JavaScript rather than HTML. . don’t support JavaScript at all. There are two important ways to accommodate these browsers when you use JavaScript. Some of the commands are similar.write(“Hello World”). and it works on most of today’s browsers. Throughout this book. Despite the name. such as Netscape 1. you should not specify a version number at all unless you are using features unique to that version. However.1”> The current version of JavaScript is 1. To begin and end the script.1: <script language=”JavaScript1. you use the <script> tag. “Other JavaScript and DHTML Resources. Beginning and Ending Scripts You can place JavaScript commands anywhere in an HTML document. Here is a simple example of a JavaScript command with beginning and ending <script> tags: <script language=”JavaScript”> document. It first appeared in 1995 in Netscape 2. This hour will only give you a quick review of the essentials of JavaScript. You can use JavaScript directly within a Web page without using any special tools to create or compile scripts. and you can specify a version number in your <script> tag to avoid confusing older browsers.0 and Internet Explorer 1. See Appendix A.” for a list of Web sites and books with further information.34 Hour 3 JavaScript Basics JavaScript was the first of the client-side Web scripting languages. JavaScript has little to do with the Java language. The <script> tag specifies the language to be used. we will use <script> tags that do not specify a version unless they require a feature of a later version.5. but it’s a different language with a different purpose. </script> Supporting Older Browsers There are actually several versions of JavaScript. The following tag specifies JavaScript 1.0.0.

To avoid this. to create a script. Older browsers ignore the <noscript> tags and display the text. while allowing the script to work on browsers that support it. 3 Using HTML Comments One problem with older browsers is that they might ignore the <script> tags and display your JavaScript code in the body of the page. even though it supports basic JavaScript. // --> </script> The <!-. or commands. The // in the last line is a JavaScript comment—this prevents the HTML comment tag from being detected as a JavaScript error.). This technique for hiding scripts is not perfect. Netscape 2. This will prevent older browsers from displaying the script. This includes older browsers as well as current browsers with JavaScript turned off.write(“Your browser supports JavaScript.0 doesn’t recognize this tag. might end the comment prematurely if they appear in your script. the <noscript> tag isn’t perfect. Unfortunately. simply place text between the opening and closing <noscript> tags: <noscript>Your browser doesn’t support JavaScript. JavaScript Statements Within the <script> tags. you can use one or more JavaScript statements. Each statement should end with a semicolon (. such as the > (greater-than) symbol. you can enclose your JavaScript code within HTML comments: <script language=”JavaScript”> <!-document.</noscript> Browsers that do support JavaScript ignore the text between the <noscript> tags. </script> . To use it.Understanding JavaScript 35 The <noscript> Tag The <noscript> tag is used to display a message to non-JavaScript browsers.and --> tags begin and end the HTML comment. Here’s a simple example that displays an alert message: <script language=”JavaScript”> alert(“Hello!”). Certain characters.”).

You will use an event handler like this in the Workshop section of this chapter. “Responding to Events. be sure you use the same name consistently. you can use one or more JavaScript statements. For example. JavaScript variable names (and most commands) are case-sensitive.”> Within the quotation marks for the event handler. These are special HTML 4. The following HTML defines a link with an onMouseOver event handler: <a href=”next.” discusses all of the events in detail. Hour 8. or something else. but if you include them it will make debugging easier. For example. Since these are a key part of DHTML. Creating Event Handlers Often. the following statement assigns the variable score a value of 10: score = 10.0 attributes for HTML tags. There are actually many events available. separated by semicolons. Once you name a variable. the onMouseOver event for an HTML tag occurs when the user moves the mouse pointer over that portion of the page.36 Hour 3 Most browsers treat the semicolons as optional. a string of text. . and can be used to respond to events: things that happen in the browser. Understanding Variables JavaScript variables are virtual containers you can use to store data: a number.html” onMouseOver=”alert(‘hello!’). you won’t even need to use the <script> tag to include JavaScript in a document. you can use event handlers. Instead.

you can simply always use it the first time you assign a value to a variable. 3 Functions are groups of commands that you can treat as a unit. you can refer to any element just like a variable. and assigns it an initial value of 5. Using var will insure that a local variable is created rather than assigning a new value to the global one. assigning it a value. This is a way of announcing that a variable will be used and. optionally. Using Arrays When you need to store a number of similar values. that you can use to declare variables. After the array is set up. They are explained in detail later in this hour. Most of the time. The var keyword is only truly required when you declare a local variable within a function that has the same name as a global variable. and is called an element of the array.Understanding JavaScript 37 Declaring Variables JavaScript includes a command. If you’re unsure whether or not to use var . You declare an array using the new keyword. you can use an array. the following statement declares an array called subtotals with 10 elements: subtotals = new Array(10). For example. var. Whether you need to use this keyword depends on the variable’s scope: • Local variables are defined within a function. Here’s an example: var b=5. and can be used only within that function. . For example. • Global variables are defined outside any function. arrays must be declared. you can omit the var keyword and simply use a variable. This makes it easy to avoid errors and will never cause a problem. This statement creates a variable. b. Arrays are groups of numbered variables. this statement assigns the value 5 to the first element of the array: subtotals[0] = 5. Unlike variables. and can be used anywhere. Each variable within the array has a unique index.

your script can display an alert if a variable has a certain value: if (score == 0) alert(“You lose!”). it displays an alert and resets to zero. you enclose them in braces ({}): if (score==10) { alert(“You win!”). alert An if statement has two parts: a condition (score==0 in the example) and an action (the statement in the example. the document. nothing else is required. the ten elements in the subtotals array in the example would have the indices 0 through 9. For example. Using the if Keyword The if statement allows you to test conditions.write(“This text came from JavaScript. score .38 Hour 3 Array indices begin with zero.write function displays text as part of the current Web page: document. you’ve seen variables used to store numbers. If you need more than one statement in the action. This clause allows you to specify what should happen if the condition of the if statement was not true. It also includes the else clause. Thus. Many built-in JavaScript functions use strings.) If the action is a single statement like this. the following statement stores the phrase “No time to lose” in a string variable called phrase: phrase=”No time to lose”. } else { alert(“You lose!”). but for more complex applications you need ways of controlling how your script executes. The following sections will introduce you to conditions and loops. } This example checks the score variable. If it is equal to 10. For example.”). Using Strings So far. For example. score=0. two important ways of controlling your scripts. Using Conditions and Loops You can accomplish quite a bit using simple JavaScript commands. Variables can also store strings of text.

i++) { //statements to repeat go here } The for statement includes three elements within the parentheses. separated by semicolons. You can also use the decrement operator. This is the equality operator. Here is a simple example: for (i=1. and detects whether two values are equal. you might have noticed the double-equals sign (==). i<10. --. JavaScript includes a number of other conditional operators: • == (is equal to) • != (is not equal to) • < (is less than) • <= (is less than or equal to) • > (is greater than) • >= (is greater than or equal to) 3 A common JavaScript error is to confuse the equality operator (==) with the assignment operator (=).Understanding JavaScript 39 Conditional Operators In the previous example. . to subtract one from a variable’s value. You can use the for keyword in JavaScript to execute a block of statements a number of times. Using for Loops One of the nice things about programming languages is that you can let the computer handle repetitive tasks. ++ is called the increment operator. These include the following: • An initial value for a variable (i=1 in the example) • A condition that must remain true for the loop to continue (i<10 in the example) • An increment expression to change the value of the variable (i++ in the example) The i++ in the example adds one to the value of i. Always use = to assign a value to a variable. and == to test conditions.

the true power of functions is to execute several statements at once.write(“<br>”). the following for loop displays the numbers 1 through 10: for (i=1. As an example.write(i + “ “). Here’s an example: while (score < 10) { //statements to repeat go here } This statement would execute the block of code in braces over and over until the variable score’s value reached 10 or more. This type of loop can even crash some browsers.40 Hour 3 The for statement is followed by a block of statements enclosed in braces. } Using while Loops Sometimes. and to repeat the same statements with different values. This allows you to create modular programs. . until the condition is no longer met. You’ve already used built-in functions.write. } This function outputs a single HTML line break (using the <br> tag). In the example above. You can use the while keyword to create this type of loop. The following statements define a short function: function Linebreak() { document. you use the function keyword. Defining a Function To define a function. This is called an infinite loop. such as document. rather than executing statements a certain number of times. You can also define your own functions. Using Functions Functions are groups of JavaScript statements that have been combined under a single name. The loop itself doesn’t change the variable’s value. if none of the statements within the while loop change the value of the score variable. and should be avoided. While this uses a single statement. the loop will never exit. i++) { document. i<=10. you’ll want them to continue to execute until something happens. The statements are executed repeatedly as the variable changes.

then divides the total by three to get the average. return total / 3. you include one or more variable names within the parentheses. you can call the function from any script on the same page. a. For example. To define a function with arguments.c) { total = a + b + c.write(“The average is “ + z). with paragraph tags on either side. This statement calls the Linebreak function you created earlier: Linebreak(). If you are using more than one argument. It uses the variable total to add the numbers. separate them with commas.write(“<p>” + text + “</p>”). the following is the definition for a function to display an HTML paragraph: function Para(text) { document. .6). The return keyword returns a value. document. b. Variables you use for function arguments are always local variables.4. or variables passed to the function. simply specify the value of text in the parentheses: Para(“Welcome to my paragraph. This allows you to create functions that answer questions. } 3 This function displays the string you send it in the text variable. here is the definition for a function that returns the average of three numbers: function Average(a. Using Arguments Functions can have one or more arguments. and c. Here is an example of a script to call the Average function and display the result: z = Average(2. simply use its name followed by parentheses. To call a function. } This function accepts three arguments.b.”). For example. and can’t be used outside the function.Understanding JavaScript 41 Calling Functions Once you’ve defined a function. To call this function. Returning Values Functions can also return a value to the script that called the function.

The best place to define functions is in the <head> section of the document.com/”. including those in the DOM. strings and arrays in JavaScript are just special types of objects. you will now create a simple script and get it working on a Web page.42 Hour 3 To use a function. such as document. Understanding Objects JavaScript also includes objects.” Workshop: Adding a Script to a Web Page You should now have a basic understanding of JavaScript. In the previous hour’s Workshop section. Objects can have properties. You’ll begin to learn about the objects in the W3C DOM. the location. You’ve already used one of these: The document. To bring together what you’ve learned. or variables associated with the object. “Understanding the DOM.write function is actually the write method of the document object. it must be defined in the same HTML document with which you are working. their properties and methods in Hour 5. Appendix D includes a summary of the objects. In fact. . since the definitions themselves don’t create any output. a special type of variable that can store multiple data items and even functions to work with those items. You can now use JavaScript to add a feature: descriptions that appear in the status line when the user moves the mouse pointer over the links in the page. You can change this property to force the browser to go to another Web page: location. Object and property names are separated by periods. you created a simple HTML document for the Figby Industries Web page.mcp. Object Properties and Methods JavaScript supports a number of built-in objects.href=”http://www. or functions associated with the object. in the Level 0 DOM. Objects can also have methods. For example.href property contains the current document’s URL.

Listing 3. Putting It All Together By adding event handlers to the links in the original Figby Industries page.1 The Complete JavaScript Example <html> <head> <title>Figby Industries. properties and methods. you can make the status line display helpful descriptions.status=’’.” onMouseOut=”window. Adding Event Handlers To add descriptions to the links. The onMouseOut event handler assigns a null string to window.</title> </head> . See Appendix A for a list of Web sites and books with further information. which displays the message in the status line.status to clear the status line.html” onMouseOver=”window.status property is part of the Level 0 DOM.1 shows the complete example with all of the event handlers.status=’Learn about our products’.return true. Inc.Understanding JavaScript 43 This hour has presented a quick introduction to JavaScript. <a href=”products. The window. but there’s much more to learn. The return true statement tells the browser to keep this message in the status line rather than rewriting it with the link’s URL. LISTING 3.status property.return true. you can use two event handlers: • • onMouseOver—occurs onMouseOut—occurs when the mouse pointer moves over an object when the mouse pointer leaves an object The listing below shows one of the links from the Figby Industries page with both of these event handlers added.”> <b>Products</b></a> 3 The onMouseOver event handler assigns a value to the window. See Appendix D for a summary of Level 0 DOM objects.

html” onMouseOver=”window.return true. there’s no need for the <script> tag at all.” onMouseOut=”window.gif.return true. Since all of the functions are performed within event handlers. As with the other examples in this book.starlingtech.status=’Contact our sales department’.” onMouseOut=”window.”> <b>Products</b></a></td> <td width=”20%”><a href=”sales.status=’’. .return true.gif” width=”486” height=”180” border=”0” alt=””><br> <h1>Welcome to Figby Industries!</h1> <p>Welcome! This is the home page of Figby Industries.status=’Learn about our products’.status=’’.status=’Service and Support’. </p> <table border=”1” align=”center”> <tr> <td width=”20%”><a href=”products.” onMouseOut=”window. http://www.com/dhtml/. This example requires an image.html” onMouseOver=”window.</p> </body> </html> In this document.return true.” onMouseOut=”window. the links within the table include onMouseOver and onMouseOut event handlers.status=’Employment opportunities’.html” onMouseOver=”window. you can download this image and the HTML document itself from this book’s Web site.html” onMouseOver=”window. logo.return true.”> <b>Employment</b></a></td> </tr> </table> <p>Any truly legitimate company would have much more text in this part of the page than we have.html” onMouseOver=”window.status=’’.”> <b>Service</b></a></td> <td width=”20%”><a href=”staff. your source for all sorts of imaginary products.status=’’. Follow the links below to learn more about our company and our products.return true.44 Hour 3 LISTING 3.return true.”> <b>Sales</b></a></td> <td width=”20%”><a href=”service.” onMouseOut=”window.return true.status=’’.1 continued <body> <img align=”center” src=”logo.return true.return true.”> <b>Staff</b></a></td> <td width=”20%”><a href=”jobs.status=’Meet our staff’.

No.Understanding JavaScript 45 To try this example. Can JavaScript display text on a Web page after it’s already loaded? A. Q&A Q. FIGURE 3. . Can I use it with DHTML? A. you’ve reviewed the basics of JavaScript: its syntax. I already know Microsoft’s VBScript language. Yes. In the figure. You’ve also completed a simple JavaScript example. and how to use variables. However. VBScript includes access to the DOM. the mouse pointer is over the “Service” link. 3 Summary In this hour. and conditional statements. you’ll get down to business by creating a DHTML example. save it as an HTML document and load it into a browser. In the next hour. functions. but Dynamic HTML can do this and much more. Q. your applications will only work in Internet Explorer. You’ll use DHTML to change text within a page in the next hour.1 shows Internet Explorer’s display of this example. loops. Figure 3.1 Internet Explorer shows the complete JavaScript example.

b. numeric variable Answers 1. What’s the difference between JavaScript and JScript? A. a determined user can always view the source of your HTML document and its associated JavaScript code. Which JavaScript keyword would be the best choice if you need to create a loop that executes exactly five times? a.46 Hour 3 Q. . c. array b. string c. a. 3. c. if a==20 if (a=20) if (a==20) 3. b. Can I hide my JavaScript code from users using the View Source option? A. While there are a few complicated methods that obscure your code. 2. A for loop would be the best way to execute a loop exactly five times. Q. b. while for wherefore 2. Which type of JavaScript variable is ideal for storing a series of numbers? a. it is compatible with JavaScript. The correct statement is if (a==20). A JavaScript array is ideal for storing a series of numbers. Questions 1. No. JScript is Microsoft’s implementation of JavaScript. For most purposes. Notice that the equality operator (==) must be used. All of the JavaScript examples in this book will work in Internet Explorer or Netscape. Which of the following if statements correctly checks the variable a for the value of 20? a. and the parentheses around the condition are required. c. Quiz Test your knowledge of the material covered in this hour by answering the following questions.

• Try including the average function described earlier in this hour to the <head> section of an HTML document. You can use the text for the status line as an argument to the function. 3 . and 20. Add a <script> section within the body of the document to display the average of the numbers 7. 12.1 to use a function to handle the status line instead of assigning window. try the following exercises: • Modify Listing 3.Understanding JavaScript 47 Exercises If you’d like to practice using JavaScript before you continue.status directly.

.

Now you’re ready to delve into the details of DHTML in Part II.HOUR 4 Creating a Simple DHTML Example In the last three hours. you’ve learned the basics of what DHTML can do. The following topics will be covered in this hour: • Starting with a simple HTML document • Identifying DOM objects • Detecting DHTML-compatible browsers • Using event handlers with DHTML • Creating a working DHTML example . and you’ve reviewed the HTML and JavaScript you need to know. this hour will give you an idea of what’s in store by guiding you through a simple example. Before you do.

and browsers normally use it to display URLs.gif” width=”486” height=”180” border=”0” alt=””><br> <h1>Welcome to Figby Industries!</h1> <p>Welcome! This is the home page of Figby Industries. In Hour 3. LISTING 4. Inc.1 shows the original HTML document.1 shows how it appears in a browser. While this is a useful feature. </p> <table border=”1” align=”center”> <tr> <td width=”20%”><a href=”products. and Figure 4.html”><b>Service</b></a></td> <td width=”20%”><a href=”staff.html”><b>Sales</b></a></td> <td width=”20%”><a href=”service.50 Hour 4 Starting with an HTML Document Back in Hour 2. the status line is not the most obvious place for descriptions.” you used HTML to create the Figby Industries Web page. your source for all sorts of imaginary products. and allows the status line to display URLs and browser status as it was intended. This allows the descriptions to fit into the design of the site.html”><b>Employment</b></a></td> </tr> </table> <p>Any truly legitimate company would have much more text in this part of the page than we have. This time you will use DHTML to add link descriptions in a much more visible place within the body of the page. Follow the links below to learn more about our company and our products. Listing 4. “Reviewing HTML. “Understanding JavaScript. In this hour.html”><b>Products</b></a></td> <td width=”20%”><a href=”sales.</p> </body> </html> .</title> </head> <body> <img align=”center” src=”logo.html”><b>Staff</b></a></td> <td width=”20%”><a href=”jobs.1 The HTML Document Before Adding Dynamic Features <html> <head> <title>Figby Industries. you will start with the same HTML document.” you added JavaScript statements to display link descriptions in the status line.

Finding Objects Using DHTML. You can change the contents of the new table cell you created by finding its object within the DOM hierarchy. you can display your link descriptions anywhere you choose on the page. The cell’s <td> tag uses the colspan attribute to extend the cell across the entire row. and the align attribute to center the cell’s contents. This assigns an identifier (desc) to the table cell. Fortunately. this is easy ..Creating a Simple DHTML Example 51 FIGURE 4..1 The original HTML document as displayed in Internet Explorer. One convenient place is directly below the row of links. Using a DHTML Function You are now ready to start using DHTML. Your DHTML script will later change this to the appropriate link description. Notice the ID=”desc” attribute in the <td> tag. When it is initially displayed. You can use the following line of HTML to add a row to the table that holds the links: <tr><td ID=”desc” align=’center’ colspan=”5”>. This row contains a single table cell. the added table cell will display three periods. it will make it easy to add dynamic features. While this doesn’t affect the way the page is displayed.</td></tr> 4 The <tr> tag defines a new table row.

0.0 and Netscape 6. you’ll have to update your code when new browsers are released. “Understanding the DOM. Additionally. the new W3C DOM was first supported in Internet Explorer 5. This assigns the variable box to the appropriate object for the table cell with the identifier desc. You can avoid these issues by simply detecting browsers that support the DOM functions you will be using. and there’s no sense in leaving them out. without actually calling the function.getElementById(“desc”).52 Hour 4 to do when you have assigned an identifier to the object. or your dynamic features will stop working. Detecting Browser Support As you learned earlier in this book. You can do this in JavaScript with an if statement like this: if (document. You’ll learn more about these methods starting in Hour 5. In older browsers. You will use this method in your script to prevent errors on older browsers. there might be browsers besides the “big two” that support the W3C DOM. While you could use JavaScript to find out exactly which browser is in use.” Note the confusing spelling of the getElementById function: You might expect the initial g or the final d to be uppercase. your script should make sure it is dealing with a new browser before attempting to use the DHTML features of the W3C DOM. This statement uses the return command to exit from the current function if the getElementById method is not supported. It will only work if you type it exactly as shown here. this will simply return a false value without causing an error. You can also use the ! (not) operator to test the same value: if (!document. If you detect specific browsers. The following line of JavaScript returns the DOM object for your new table cell: box=document. . The getElementById function is one of the new methods supported by DOM-compliant browsers. this isn’t always the best way. Since many older browsers are still around.getElementById) { This checks for the presence of the getElementByID function.getElementById) return.

innerHTML=text. } This function accepts a parameter and stores it in the text variable. box. Finally.. The onMouseOver event calls Describe with a description for the link. Adding Event Handlers In the previous hour. and the onMouseOut event calls Describe with a default value. which will use DHTML to display descriptions. It then uses the browser-detection method you learned earlier to detect whether the current browser supports the DOM. with event handlers added: <td width=”20%”><a href=”products.getElementById(“desc”). you used the onMouseOver and onMouseOut events to execute a JavaScript function. 4 Creating the Describe Function You are now ready to create the Describe function.” onMouseOver=”Describe(‘Information about our exciting products’).’).Creating a Simple DHTML Example 53 You’ll learn more about ways to detect browsers and the differences between them in Hour 17.getElementById) return. Here is the section of the HTML document with the Products link. the return statement exits the Describe function immediately. If the DOM is supported.html” onMouseOut=”Describe(‘. The following is the complete Describe function: function Describe(text) { if (!document. If the getElementById function does not exist. box=document. The following sections will guide you through the process of adding DHTML to the Figby Industries Web page.” Creating the Script You should now know what you need to complete the DHTML example.innerHTML property. the value passed as a parameter is assigned to the box..”> <b>Products</b></a></td> The Describe function will place the text you send it in the table cell below the links using Dynamic HTML. . You can use a similar function to add DHTML features. the script uses the getElementById function to find the object (box) for the table cell with the identifier desc. “Dealing with Browser Differences.

dynamic version of the page.gif” width=”486” height=”180” border=”0”><br> <h1>Welcome to Figby Industries!</h1> <p>Welcome! This is the home page of Figby Industries. The innerHTML property represents the contents of an object.gif.getElementById(“desc”).” onMouseOver=”Describe(‘Information about our exciting products’). in this case the table cell.com/dhtml/.. </p> <table border=”1” align=”center”> <tr> <td width=”20%”><a href=”products.getElementById) return. This listing is a bit long. box.’). Listing 4. box=document. starlingtech.54 Hour 4 This is where the page becomes dynamic.</title> <script language=”JavaScript”> function Describe(text) { if (!document. your source for all sorts of imaginary products. Workshop: Putting It All Together Now that you have written the Describe function and determined how to call it using event handlers. you can download this and all of the book’s other examples at this book’s Web site.”> <b>Products</b></a></td> .innerHTML=text. required by this example is also available there. Inc. LISTING 4.2 shows the complete DHTML example.. http://www. When you assign new text to box. you can combine these with the original HTML document for the Figby Industries Web page to create a complete. The graphic. Follow the links below to learn more about our company and our products. To save some typing. } </script> </head> <body> <img align=”center” src=”logo. the text is displayed in the table cell in place of its original contents. logo.html” onMouseOut=”Describe(‘.innerHTML.2 The Complete DHTML Example <html> <head> <title>Figby Industries.

” onMouseOver=”Describe(‘Employment opportunities available’).0 or later to test this example and most of the DHTML examples in the rest of this book.” onMouseOver=”Describe(‘Contact our Sales Department’). Figure 4.. including the cell identified as desc that will display the item description..html” onMouseOut=”Describe(‘.” onMouseOver=”Describe(‘Find service and support information’). save it. This example will work equally well with either of these browsers.html” onMouseOut=”Describe(‘. ..html” onMouseOut=”Describe(‘.’). In the figure. • A new row has been added at the end of the table.0 or later or Internet Explorer 5.. • In the table.</p> </body> </html> In this listing.’).’).. type it in using a text editor. you should see a description in the lower row of the table. 4 You must use Netscape 6. three changes have been made to the original HTML document: • The <script> section in the header of the document defines the Describe function.2 continued <td width=”20%”><a href=”sales. When you move the mouse pointer over one of the links.” onMouseOver=”Describe(‘Learn about or contact our staff’).html” onMouseOut=”Describe(‘.. and load it into a browser.”> <b>Staff</b></a></td> <td width=”20%”><a href=”jobs.”> <b>Employment</b></a></td> </tr> <tr><td ID=”desc” align=’center’ colspan=”5”>.”> <b>Sales</b></a></td> <td width=”20%”><a href=”service... onMouseOut and onMouseOver event handlers have been added to each link to call the Describe function.’).Creating a Simple DHTML Example 55 LISTING 4. To try this example.2 shows the completed DHTML example as displayed by Netscape 6.”> <b>Service</b></a></td> <td width=”20%”><a href=”staff... the description for the Service link is being displayed.</td></tr> </table> <p>Any truly legitimate company would have much more text in this part of the page than we have.

Can I change the text in an object other than a table cell? A. Q&A Q. and use them to create several examples. and the developers plan to add more support. Summary In this hour. Q.opera.56 Hour 4 FIGURE 4. Congratulations—you’ve reached the end of Part I! In Part II. Yes. If you assign the ID attribute to a different object.2 Netscape shows the completed DHTML example. you can change its contents instead. you will learn more of the technical details of DHTML and the DOM. Absolutely. such as a paragraph or heading. Are there actually any browsers besides Netscape and Internet Explorer that support DHTML? A.com/) has limited support for the Level 2 DOM. you’ve learned how to use a JavaScript function and DOM functions and properties to add a simple dynamic feature to an HTML document. . You’ve also learned how to ensure that your script won’t cause errors in older browsers. The Opera browser (http://www.

JavaScript c. is a statement in which language? a. obj=GetElementById(“thirdline”). HTML function c.getElementById(“thirdline”). b. the language is still JavaScript. c.0 browsers? A. onMouseOver is an example of an event handler. HTML b. Quiz Test your knowledge of the material covered in this hour by answering the following questions. An event handler Answers 1. See Hour 17 for details on supporting older browsers.getElementByID(“thirdline”). While you can’t change the contents of a table cell in these browsers using the W3C DOM. Notice the lower-case g and d in getElementById. Is a dynamic page like this one possible in the version 4. a. The correct command is obj=document. 2. Yes.Creating a Simple DHTML Example 57 Q. . c. obj. While this statement uses a DHTML property.innerHTML=”test”. obj=document. HTML property b. Questions 1. Which of the following is the correct function to obtain the object for the HTML element with the identifier thirdline? a. 2. 3. obj=document. b. you could use a layer to display a description. DHTML 3 onMouseOver 4 is an example of what? a..getElementById(“thirdline”).

• Currently. if the Describe function in Listing 4. such as the <h1> tag at the top or the paragraph at the bottom.2 detects a browser that doesn’t support the DOM.2 by removing the ID=”desc” attribute from the table cell.58 Hour 4 Exercises If you’d like to explore this hour’s DHTML example a bit further before you move on. it doesn’t do anything. Try adding an else clause that displays the messages in the status line for older browsers. . Notice that the descriptions will now be displayed in the area you specified instead of in the table cell. and adding it instead to a different HTML tag. similar to what you did in Hour 3’s Workshop section. try the following exercises: • Try modifying Listing 4.

PART II Learning DHTML Basics Hour 5 Understanding the DOM 6 Creating Positionable Elements (Layers) 7 Working with DOM Properties and Methods 8 Responding to Events .

.

you’ll learn quite a bit more about the W3C DOM that enables cross-browser DHTML in the latest browsers. In particular. Hour 5 covers the following topics: • The structure of the Level 0 and Level 1 DOM • How the hierarchy of DOM objects represents a Web page • Relationships between DOM objects • Using DOM properties and methods • Hiding and showing objects using DHTML . this hour will introduce you to the DOM’s basic structure. To begin with. You’ll learn how the W3C DOM fits in with the older Level 0 DOM.HOUR 5 Understanding the DOM Welcome to Part II! In the next four hours. you’ll learn more about DHTML. and some of the properties and methods you can use with DOM objects.

62 Hour 5 Learning DOM Structure In the previous hour.1 The Level 0 DOM’s object hierarchy. self. Notice that the document object is at the top of the hierarchy for the document. The Level 1 DOM The Level 1 DOM is what makes cross-browser DHTML truly dynamic. when we refer to the DOM. the structure of DOM objects is something you’ll need to know as you pursue more advanced features. and Internet Explorer also supports. Figure 5. While you can do this without knowing how the DOM organizes objects.1 shows how the basic objects of the Level 0 DOM are organized. frames[ ]. This is where the W3C DOM connects with the Level 0 DOM. that the Level 0 DOM and Level 1 DOM are part of the same hierarchy. FIGURE 5. the Level 0 DOM allows you to access—and modify—any object on a page. While the Level 0 DOM only includes objects for certain parts of a document. documents. images. The Level 0 DOM As you learned earlier in this book. however. frames. window (parent. we are usually talking about the Level 1 DOM. Keep in mind. such as windows and images. top) links[ ] document anchors[ ] history images[ ] location forms[ ] form elements DOM Level 1 Objects Since this is a book about DHTML. . and forms. This DOM includes objects for working with windows. you used a DOM object to create a dynamic page. the Level 0 DOM is the informal label for the DOM objects that Netscape introduced with the JavaScript language.

Figure 5. Listing 5. and images. You can still use the objects in the Level 0 DOM to work with windows. it’s included in the Level 1 DOM specification.1 A Simple HTML Document <html> <head> <title>A simple HTML Document</title> </head> <body> <h1>This is a Heading</h1> <p>This is a paragraph</p> </body> </html> The DOM stores an object for each tag in the document in a hierarchy. and a single paragraph. a heading. document html head body 5 p title h1 "A simple HTML Document" "This is a Heading" "This is a paragraph" Although this book focuses on the W3C DOM.2 shows how this document would be represented in the DOM. frames. FIGURE 5.Understanding the DOM 63 To give you an idea of how the DOM organizes the objects within a Web page. “DOM Quick Reference.” includes a summary of Level 0 DOM objects. . keep in mind that the Level 0 DOM is not obsolete—on the contrary.2 How the DOM represents an HTML document. LISTING 5. Appendix D. and to obtain information about the current document. starting with the HTML element at the top.1 shows a simple HTML document that includes a title.

Possible node names include the tag name for HTML tag nodes. each of the boxes is a node. #document for the document node. and the lines form relationships between the nodes. This node is called a text node.64 Hour 5 Nodes Each container or element in a document is called a node in the DOM hierarchy.2. there is a further node that defines the text within the container. You can now start to learn how to deal with these objects in your scripts. The <h1> and <p> containers are children of the body object. you can also access any node based on its relationships with other nodes. DOM Object Properties Each object in the DOM has a number of properties. For container tags. and #text for text nodes. You’ve already worked with individual nodes using the ID attribute. The actual list of properties depends on the HTML tag the object represents. Siblings DOM objects can also be referred to as siblings. such as <p>. .2. A document’s DOM hierarchy includes a node for each HTML tag within the document. There are also several general properties that apply to every node: • nodeName is the name of the node (not the ID).2. As you might have guessed if you have siblings of your own. or attributes. the <h1> and <p> nodes are siblings under the <body> node. In Figure 5. However. Parents and Children Each object in the DOM can have a parent—the node above it in the hierarchy—and one or more children—the nodes below it in the hierarchy. and that’s usually the easiest way. Each object has properties that correspond to the HTML tag’s attributes. Using DOM Objects You should now have a basic understanding of how the DOM organizes objects. and the text within those containers forms a child node for each one. these are nodes that share the same parent object. In Figure 5. In Figure 5. the document object is the parent of all of the objects below it.

is the object that contains the current node. classname is the value of the class attribute for the node. and whether it’s hidden or visible. This means headings.Understanding the DOM 65 • • • nodeType is a number describing the node’s type: 1 for HTML tags. is the last child node for the current node. while the value of a text node is the text contained within it. and 9 for the document. each node has a number of properties that describe its relationship with other nodes in the DOM hierarchy. but not the document. “Working with DOM Properties and Methods. HTML tag nodes have a null value. 3 for text nodes. childNodes previousSibling nextSibling parentNode 5 is the sibling before the current node is the sibling after the current node. id is the value of the ID attribute for the node. You can use the style properties for any visible object on the page. Style Properties Each node in the DOM hierarchy has a style property. This attribute is typically used to assign the same style to a number of elements—you’ll learn more about it in Hour 9. paragraphs. These properties include the following: • • • • • • firstChild lastChild is the first child node for the current node. body.” Node Relationship Properties In addition to the basic properties. and other visible objects. Each style property corresponds to an attribute that can be used in a CSS style sheet. is the HTML contents of a container node.” • • nodeValue is the value for a node. images. innerHTML The nodeValue and innerHTML properties are explained in more detail in Hour 7. You used this property in the previous hour to change the text within a node. color. “Introducing Style Sheets. or other . is a list of all of the child nodes under a node. This is a child object whose properties describe how the object appears on the page: its position. which you can access as an array in JavaScript.

Several of the most important of these are methods of the document object: • • document. You can set this property to visible (default) or hidden to show or hide the object. document. “Working with Style Sheets. a percentage. Unlike visibility. inherit. and the value of none hides it. This property only affects the object. left top • controls the vertical position of the object. “Creating Positionable Elements (Layers). “Creating Positionable Elements (Layers). • also controls the object’s visibility. which you can access as an array. A value of block. You’ll learn more of the available style properties and practice using the left and top properties in Hour 6. right • and bottom provide an alternate way of setting the horizontal and vertical position of an object. and does not affect the page’s layout.” for information about the various display values. See Hour 6. for working with objects. it changes the page’s layout—objects below it on the page will move up into the empty space.getElementById(ID) returns the element with the specified identifier.getElementsByTagName(tag) . It supports the same values as left. or functions. means that the object will be visible if its parent object is visible. display • is the horizontal position of the object. auto to allow the browser to determine the position. You can use the asterisk (*) as a wildcard to return a collection of all of the nodes in the document. or list-item shows the object. if you hide an object with display. returns an array of the elements with a specified tag name.” Document Object Methods The DOM also includes a number of methods. The top and left properties have no effect unless the position property has been changed to a value other than static. inline. It can be a numeric offset from the main browser window.66 Hour 5 objects that don’t represent a visible part of the page. You used this function in the previous hour to manipulate objects on a page. or inherit to inherit the position of the parent object. Here are some of the most useful properties: • visibility controls whether the object is visible on the page. A third value.” and in Part III.

You can use this method to add content to a document. Internet Explorer 4’s DHTML model used a document. You can use these to add or remove elements within a page. replaceChild(newnode. “Working with DOM Properties and Methods. or false if it has none. These include the following: • • • • • appendChild(newnode) adds a new child node to the node after all of its existing inserts a new child node before the specified replaces the specified old child node with a children. 5 returns a Boolean value of true if the node has one or more children. .getElementsByTagName(*) to return a similar array in IE 5 or Netscape 6. For example.Understanding the DOM 67 • document. To use these methods.oldnode) existing child node. obj.createElement(tag) creates a new element with the specified tag name. this code finds an element with the ID attribute “lastone” and removes its first child node: obj=document. insertBefore(newnode. If you are used to this style of DHTML. you can use document. as you’ll learn in Hour 7. removeChild(oldnode) hasChildNodes() removes an existing child node. and the Workshop section of Hour 7 uses them to add and remove text within a Web page.removeChild(obj.createTextNode(text) • creates a new text node containing the specified text.” document.firstChild).oldnode) new child node. Hour 7 describes these methods in detail.getElementById(“lastone”).all array containing all of the objects in a document. you separate the node name and the method name with a period. Node Object Methods Node objects in the DOM also have their own set of methods.

getElementById(“head1”). In this example.checked. • Use the getElementById method to find the objects for the elements. var head1 = document. var head2 = document. While this example will hide or show headings. you can create a simple example that uses DHTML to hide and show objects on a page. if you want to manipulate just one child node you can continue to use the getElementById method to obtain an object for that node. to verify that the browser supports the needed DOM functions. • Use the style. . you can just as easily use any other object. The getElementsByTagName method is also useful if you want to work with more than one object—for example.visibility=(showhead2) ? “visible” : “hidden”. var showhead2 = document. Workshop: Hiding and Showing Objects Now that you’ve learned the basics of DOM properties and methods.visibility property of each object to control its visibility.head2.visibility=(showhead1) ? “visible” : “hidden”. all of the paragraphs on the page or all of the headings. it finds the objects for the two headings and stores them in the head1 and head2 variables.68 Hour 5 JavaScript and the DOM What do all of these properties and methods mean for practical scripting? Well.head1.style.getElementById) return. var showhead1 = document. You’ll use some of these methods to add and remove text within an existing Web page in Hour 7. Next. head2.checked. Two checkboxes in a form are used to control the visibility. The relationship properties and methods become useful if you want to create a script that works with more than one node on the page. Creating the JavaScript Function The ShowHide function will handle the actual showing or hiding of the objects on the page.form1. Here is the JavaScript code for this function: function ShowHide() { if (!document.style.getElementById(“head2”). You can accomplish this easily by doing three things: • Assign an ID attribute to the elements you want to show or hide. or even with all of the nodes. you’ll use these techniques to show or hide two headings. } This function first checks for the existence of the getElementById method. head1.form1.

var showhead2 = document. LISTING 5. Finally.style.getElementById(“head1”). it uses these values to assign either the visible or hidden values to the style.2 shows a complete HTML and JavaScript document for showing or hiding headings.”> <b>Show first heading</b><br> <input type=”checkbox” name=”head2” checked onClick=”ShowHide(). } </script> </head> <body> <h1 ID=”head1”>Now You See It</h1> <h1 ID=”head2”>Now You Don’t</h1> <p>The W3C DOM and DHTML allow you to hide or show the two headings on this page.</p> <form name=”form1”> <input type=”checkbox” name=”head1” checked onClick=”ShowHide().2 Hiding and Showing Objects <html> <head> <title>Dynamic Text in JavaScript</title> <script language=”Javascript”> function ShowHide() { if (!document.head2. Creating the HTML Document Listing 5.getElementById(“head2”).getElementById) return. . The onClick event handlers on lines 24 and 27 ensures that the ShowHide function is called each time one of the checkboxes is clicked.visibility=(showhead1) ? “visible” : “hidden”.form1. The two <h1> headers are assigned the ID attributes head1 and head2 so that they can be manipulated by the script.form1.visibility=(showhead2) ? “visible” : “hidden”.”> <b>Show second heading</b><br> </form> </body> </html> 5 This HTML document includes the ShowHide function in its <script> section.checked.style.checked. var showhead1 = document.Understanding the DOM 69 Next. var head1 = document.visibility property of the headings. it reads the checkboxes in the form and stores their values in the showhead1 and showhead2 variables. head2. head1. var head2 = document.head1.

type it into a text editor and save it as an HTML document. .70 Hour 5 To try this example. you will learn how to use layers in DHTML. Load the document into Netscape 6. you’ve begun to delve into more of the details of DHTML.0 or later.3 The example in action. You learned some of the properties and methods of the W3C Level 1 DOM. You’ll learn more about the positioning properties of objects. a technique you will use many times in later hours of this book. size. In the next hour. Can I use node properties to change the font. and much more. Q&A Q. and how to move objects on the screen. Yes. or color for text within a document? A. FIGURE 5. Summary In this hour. and you’ve learned how it fits in with the old Level 0 DOM. with both headings currently visible. you applied your knowledge to create an example that hides and shows objects. Finally. Figure 5.0 or later or Internet Explorer 5.3 shows this example in action with both of the headings displayed. You will learn the complete list of style properties in Part III.

0 browsers in Hour 17. Is there a way to get the entire HTML source code for the current page? A. Not exactly. “Dealing with Browser Differences. The object has no children . This is explained in detail in Hour 7. b. A text node with the paragraph’s contents c. c. You’ll learn how to use layers in 4. you can create layers containing HTML tags. If you define a simple paragraph of text in HTML. Is there a way to show or hide objects in the version 4. Yes. You can’t hide arbitrary objects like our example does with headings. style.Understanding the DOM 71 Q.documentElement. and show or hide the layers. which of the following is a child object of the <p> tag’s node? a. c. Which of the following functions is the easiest way of adding dynamic features to a single object on a page? a.hide style. for much the same effect. getElementById getElementsByTagName hasChildNodes 2. Questions 1. The </p> tag b. without affecting the layout of the remaining objects on the page? a. Q.innerHTML property.” Quiz Test your knowledge of the material covered in this hour by answering the following questions. b. it’s the value of the document. However.0 browsers? A. Which of the following properties can hide or show an object.display style.visibility 5 3.

c. You’ll need to add an ID attribute for the paragraph. 3. try the following exercises: • Modify Listing 5. 2. • Modify Listing 5. In a simple HTML paragraph. b.2 to allow showing and hiding of the text paragraph on the page as well as the headings. a text node containing the text within the paragraph. a. and modify the ShowHide function to support the additional object. The style. add a checkbox to the form. Exercises If you’d like some more practice working with the DHTML techniques you learned in this hour before you move on. the paragraph object has a single child object.2 to use the display property instead of the visibility property to show or hide the headings. moving the paragraph of text up. Notice that the page collapses when you hide them.visibility property can be used to hide or show an object without affecting the page’s layout. .72 Hour 5 Answers 1. Using getElementById is the easiest way to work with a single object on a page.

or groups of movable objects. the properties you can use. You can also use DOM properties to move any object within a Web page. You can create layers. Hour 6 covers the following topics: • Why layers are useful • Defining layers in HTML • Positioning properties for layers and other objects • Creating a simple layered document • Using JavaScript to make layers dynamic .HOUR 6 Creating Positionable Elements (Layers) One of the most useful features of DHTML is the ability to move objects around on the screen. In this hour. and how to work with layers and other positionable objects using JavaScript. you’ll learn how to define layers using the CSS standard. and position them using JavaScript.

Actually. they both included a feature called layers.” HTML Tags for Layers Typically. Another good reason to use layers is that you can create a script that works with the 4. or shown.0 browsers as well as newer browsers. Unfortunately. these two browsers supported entirely different ways of defining and using layers. In order for a division to act as a layer. Layers are still a useful concept when you want to define an area that contains content over which you want control. with the new W3C DOM. can overlap in whatever way you specify. The following is a simple layer definition: <div ID=”layer1” STYLE=”position:absolute. but the methods for working with layers in JavaScript differ. you used DHTML to hide and show headings on a page. You can define layers with CSS style sheets and attributes. Layers were the first DHTML feature available to the world. you need to specify certain positioning properties. or develop cross-browser code using both techniques. in the previous hour. left:100. This type of layer is supported by the 4. and can be manipulated using JavaScript. now known as positionable elements. you can position.0 browsers. You’ll also learn the properties for positioning objects in DHTML in this hour. you can now easily create layers and manipulate them using cross-browser code. You will create such an example in Hour 17. the W3C stepped in with a standard for layers. and you will continue to use them later in this book. Fortunately.74 Hour 6 Why Layers? When Netscape and Microsoft released their version 4. Webmasters who wanted to use this feature had to either settle on a single browser to support. which apply equally to layers and other objects. hidden. top:50”> <p>This text is contained in the layer.0 browsers. Layers are areas of a Web page that can be moved. show or hide anything in a Web page—for example.</p> </div> . When you combine the CSS layer standard with the new W3C DOM supported by Internet Explorer 5 and Netscape 6. “Dealing with Browser Differences. you create a layer using the <div> tag in HTML.

The most important of these is the position property. and left and top define its initial position. absolute relative allows you to position the item by specifying left and top coordinates. The style attribute in the layer definition sets up CSS style information. Setting Coordinates Layers and other positionable objects can be positioned anywhere within the browser window. 6 Along with position. but doesn’t scroll with the page contents. defines an item that is offset a certain amount from the static position.Creating Positionable Elements (Layers) 75 The position:absolute in the layer definition specifies that the layer will be positioned relative to the browser window. and cannot be moved. You can set these in the style sheet definition for a layer. you can assign a position attribute to any HTML tag that displays an object on the screen.position. or set them later using JavaScript. you can change the object’s position using JavaScript.style. or any positionable object. fixed All of the properties described here are style properties. with the W3C DOM. where it was laid out by the browser. This property is not supported by current browsers. These can also be set in a style sheet. This means you refer to them using the style object. You can also use the <span> tag to define layers. You’ll learn more about style sheets in Part III. Additionally. The position property can have one of four values: • • • • static (default) defines items that are laid out along with the rest of the HTML document. as in obj. and other style parameters. you can define one or more positioning properties in the object’s style definition. If you also assign an ID attribute. a number of other properties are available. which includes positioning as well as font. These properties are further explained in the next section. defines an item that can be moved like the absolute value. You can use the following properties to set an object’s location: .” Positioning Objects To define a layer. size. “Working with Style Sheets.

pixels are typically assumed. they start at the object’s original position. For objects containing text. coordinates start at the left side of the browser window. the text will wrap at the specified width. right. and relative to the original position for relative positioning. “Introducing Style Sheets. inherit to inherit the position of the parent object.2ex) width of the letter m in the current font (for example. z-index Using Units The left. and bottom properties can be set to auto to let the browser position the object. You can change this value to bring an object to the top. top • is the vertical position of the object. 150%) If you assign a numeric value to a property without specifying a unit. 1. . Numbers for all of these properties can be specified in several different units: • • • • • px: pt: Pixels (for example.76 Hour 6 • left is the horizontal position of the item. top.” Showing and Hiding Objects As you learned in the previous hour. 15px) Points (for example. 10pt) height of the letter x in the current font (for example. 1. Since these units are used for style sheets. Indexes are assigned in order. for relative positioning. there are two properties that allow you to control whether an element appears on the Web page: visibility and display. For absolute positioning. so layers defined later in the HTML document are “on top” of previous layers. You can use these when you need to align the object’s right or bottom edge on the page. and bottom are alternate ways to set the horizontal and vertical position.5em) ex: Approximate em: Approximate %: Percentage of the containing object’s value (for example. or a number. and height specify the object’s width and height. they are explained in more detail in Hour 9. This is relative to the top of the browser window for absolute positioning. • • • right width specifies how the object overlaps with other objects.

A value of inherit uses the visibility setting of a parent object. “Using Style Sheet Properties. or the keyword transparent. This can be a named color. or inherit. none Background Properties The following properties are used to specify the background of a layer. In this case. the content inside a layer will be larger than the size assigned to the layer can display. such as #FF3355. meaning that it is preceded and followed by line breaks. It can be set to visible (default). The display property specifies whether the object is visible in the page. background-color background-image • specifies a background image for the layer. the overflow property tells the browser what to do with the extra content: • • • visible hidden scroll will make the content visible even if it’s outside the layer’s box.” for more background-related properties. hidden. The page layout shifts to account for changes to this property. and adjusts the page layout to fill in the empty space. they are specified as backgroundColor and backgroundImage in JavaScript. meaning that any object below the layer will show through the background. without affecting the page layout.Creating Positionable Elements (Layers) 77 The visibility property controls the item’s visibility. The possible values for display include the following: • • • • block displays the object as a block-level element. such as blue. . formatted as a member of the current list defined by an <ol> or <ul> tag. hides the content outside the box and provides scroll bars to allow the user to see the entire content. a specific RGB color. with no line breaks. Since these attributes include a hyphen. hides the content outside the box. displays the object as an inline element. See Hour 10. 6 Handling Overflow Sometimes. removes the object from the page’s display. inline list-item displays the object as a list item. • specifies the background color for the layer.

1 shows a simple example that creates two layers and specifies their positions. You’ll use the overflow property to create a scrolling window in Hour 24. dotted. ridge. inherit inherits the overflow value from a parent object. Values include none (default). double. LISTING 6. groove. You can do this by assigning the following properties: • • sets the width of the border for all four sides.” Border Properties Sometimes you’ll want to place a visible border around your layer. Creating a Layered Document You can create a layered document using <div> tags and positioning properties. background-color:yellow”> <h1>First Layer</h1> . sets the style of border. or outset. This can be a numeric value or the keywords thin. There are actually a variety of more specific border properties. left: 280. top: 100. usually displaying scroll bars. inset. These are described in Hour 10. solid. Listing 6. height:150.78 Hour 6 • • auto lets the browser make its own decision about the overflow. medium. border-width border-style dashed. • border-color sets the color of the border. “DHTML Tips and Tricks. or thick.1 A Simple Document with Layers <html> <head><title>Layers Example</title></head> <body> <h1>Example Layered Document</h1> <div ID=”layer1” STYLE=”position: absolute. width:250.

and background-color to assign different colors to each one. width:250. although it was defined second.1 The simple layered document as displayed in Internet Explorer. 6 . </div> </body> </html> In this listing. FIGURE 6. left: 20. although it was defined first. Figure 6. background-color:Aqua”> <h1>Second Layer</h1> This is the second layer.Creating Positionable Elements (Layers) 79 LISTING 6. It appears on the left side. This example uses the left and top properties to position the layers.1 shows how this example appears in Internet Explorer. It appears on the right side of the page. </div> <div ID=”layer2” STYLE=”position: absolute. height:150. top: 100. width and height to set each layer’s size.1 continued This is the first layer. the two <div> tags define the layers.

<br> <input type=”radio” name=”what” value=”layer1” checked> Layer 1 <input type=”radio” name=”what” value=”layer2”> Layer 2 <input type=”radio” name=”what” value=”heading”> Heading <input type=”radio” name=”what” value=”control”>This Panel<br> <table align=”center”> <tr><td colspan=”2” align=”center”> <input type=”button” name=”up” value=”Up” onClick=”move(0. Creating the Control Panel To move the objects on the page.style. The control panel will use a form. Using this example. You used this technique in the previous hour to hide and show objects on a page.30.style.0).0).getElementById(“layer”).top=200. you can create a control panel in its own layer. the following JavaScript moves an object with the ID attribute layer to a new position: obj=document.left=100.”> </td> </tr> <tr><td colspan=”2” align=”center”> <input type=”button” name=”down” value=”Down” onClick=”move(0.”> </td></tr> <tr><td align=”left”> <input type=”button” name=”left” value=” Left “ onClick=”move(-30.”> </td> <td align=”right”> <input type=”button” name=”right” value=”Right” onClick=”move(30. For example. right.0.”> . obj.”> <br> <input type=”button” name=”zminus” value=”Z minus” onClick=”move(0. obj.-1).-30.0.80 Hour 6 Workshop: Manipulating Layers with JavaScript You can set the properties of a layer or other object dynamically using JavaScript.0). you can expand your layered document and add the ability to move the various layers around the page.0. up. and will include two basic sections: • A set of radio buttons to allow you to choose which object to move • Four buttons to move the chosen object left.0). or down • Two buttons to increase or decrease the z-index property The following is the HTML <form> section for the control panel: <form name=”form1”> Use these controls to move the layers and other elements on the page.

the control panel layer itself. } 6 Here’s a breakdown of how the move function works: • The function keyword lists the three arguments.left) + x.getElementById(tomove). and the if statement sets the variable tomove to the name of the object that should be moved. move. Z-plus. Creating the move Function Next.style. and move it the appropriate amounts.getElementById) return. Down.what[i].style. y. You will be able to choose to move Layer 1.zIndex) + z. and the Z index. with three parameters: the amount to move the left position.”> </td></tr> </table> </form> The <form> tag starts a form with the name form1. the top position. Here’s the JavaScript code for the move function: function move(x. x.style. Since browser coordinates start with zero at the top-left corner. Each one calls a function. y. Left.style.checked) tomove=document. .form1. This function will read the form to determine the object to move.i<4. The buttons in the control panel include an onClick event handler. obj. Right. and z-index properties and adds the numbers in the x.1).Creating Positionable Elements (Layers) 81 <input type=”button” name=”zplus” value=”Z plus” onClick=”move(0.top = parseInt(obj. obj. The <table> tag is used to lay out the Up. The name will be needed later to read the form’s contents.what[i]. and z. top. and z variables to them.i++) { if (document.top) + y. Layer 2.style. you need to create the move function itself.left = parseInt(obj.style. The document then defines four radio buttons with the name what and different values. • Finally. • The for loop finds out which of the radio buttons is checked. or a heading on the page.value.0. and negative numbers (subtraction) to move the object up or to the left. } obj=document. the move function will use positive numbers (addition) to move the object down or to the right.y. and Z-minus buttons in a user-friendly shape.zIndex=parseInt(obj. the function reads the current value of the left.z) { if (!document. for(i=0.form1. obj.

style.top) + y. and the move function into a single HTML document to create the complete example. left: 20.zIndex=parseInt(obj.i++) { if (document.style. width:250.left) + x. left: 280. width:250. </div> <div ID=”control” .style. left: 20. top: 50. With current browsers.z) { if (!document. height:150.82 Hour 6 This example reads the object’s current position from the obj. this technique will only work if you have already set the object’s position in a style definition or using JavaScript. Putting It All Together Finally.2 shows the complete dynamic layers example.checked) tomove=document.getElementById) return.top = parseInt(obj.2 The Complete Dynamic Layers Example <html> <head><title>Layers in DHTML</title> <script language=”JavaScript”> function move(x. background-color:Aqua”> <h1>Second Layer</h1> This is the second layer. you can’t read its position. you can combine the layered document.getElementById(tomove). obj.form1. the control panel. } obj=document.form1.style.what[i]. It started out on the left side of the page. obj.zIndex) + z.style.style. obj.left and obj. height:150. } </script> </head> <body> <h1 ID=”heading” style=”position: absolute.style.what[i].i<4.style. background-color:yellow”> <h1>First Layer</h1> This is the first layer.y.value. </div> <div ID=”layer2” STYLE=”position: absolute. for(i=0. top: 50. top: 5”> Controlling Layers with DHTML</h1> <div ID=”layer1” STYLE=”position: absolute. If the object was laid out by the browser.top properties.left = parseInt(obj. Listing 6. LISTING 6. It started out on the right side of the page.

0. height:255. background-color:lightblue”> <h1>Control Panel</h1> <form name=”form1”> Use these controls to move the layers and other elements on the page.-1). After you have loaded the document. Figure 6. and the second defines the layer2 layer.0. Finally. giving it an ID attribute and a position so that it can be moved later.3 shows Internet Explorer’s display of the example after all of the objects have been rearranged in this way.0).”> </td></tr> </table> </form> </div> </body> </html> In this listing. left: 20.0).”> <input type=”button” name=”zplus” value=”Z plus” onClick=”move(0. <br> <input type=”radio” name=”what” value=”layer1” checked> Layer 1 <input type=”radio” name=”what” value=”layer2”> Layer 2 <input type=”radio” name=”what” value=”heading”> Heading <input type=”radio” name=”what” value=”control”>This Panel<br> <table align=”center”> <tr><td colspan=”2” align=”center”> <input type=”button” name=”up” value=”Up” onClick=”move(0. The <h1> tag defines the heading. width:350.2 continued STYLE=”position: absolute. Figure 6.”> <br> <input type=”button” name=”zminus” value=”Z minus” onClick=”move(0. To try this example.30.2 shows the initial display of the document in Netscape 6. 6 .0. try moving different parts of the page using the control panel. save it as an HTML document and load it into a browser. The first <div> section defines the layer1 layer. the <script> section sets up the move function.0).1).”> </td> </tr> <tr><td colspan=”2” align=”center”> <input type=”button” name=”down” value=”Down” onClick=”move(0. the third <div> section sets up the control panel in a layer called control.-30.”> </td></tr> <tr><td align=”left”> <input type=”button” name=”left” value=” Left “ onClick=”move(-30.0).Creating Positionable Elements (Layers) 83 LISTING 6.0.”> </td> <td align=”right”> <input type=”button” name=”right” value=”Right” onClick=”move(30. top: 210.

3 The dynamic layer example after objects have been moved. .84 Hour 6 FIGURE 6.2 The dynamic layer example before any layers are moved. FIGURE 6.

If you want to read the position. <body> <div> <layer> .4 work in Netscape 4. Q. you’ve learned how to use DHTML to position objects on a page.0 or Internet Explorer 4. Quiz Test your knowledge of the material covered in this hour by answering the following questions. Finally. but you will need to replace the code that uses the getElementById method in the move function with the appropriate object for the browser. In the next hour. but not in Netscape 6 or Internet Explorer. I’ve seen the <layer> tag used before. be sure to assign an initial offset (zero is fine) when you define the layer. you created an example that allows you to move layers and other objects using JavaScript. Which of the following tags is a good way to create a layer? a. you’ll learn more about the structure of the DOM for a Web page. Q&A Q. a position of left:0 and top:0 refers to the original position. Yes. Yes. 6 Questions 1. b. Doesn’t this have something to do with layers? A. Can I move a layer or object that was defined using relative positioning? A.0? A. You can use the same layer definitions. Q. With these objects. <layer> was the tag used to define layers in Netscape when they were first introduced. c. Yes. groups of objects that can be dynamically positioned. You’ve learned about layers. and learned the positioning properties you can use for layers and for other objects. This technique still works in Netscape 4. Can I make the example in Listing 6.0.Creating Positionable Elements (Layers) 85 Summary In this hour. or remove existing objects. You’ll learn how to manipulate the nodes in the DOM to add new text or other objects to a page.

If you already have the object for a layer stored in the obj variable. When the button is clicked.. document. what’s the correct JavaScript statement to set a new horizontal position for the layer? a. Exercises If you’d like to practice using layers and positioning before you move on to the next hour.4. b.4 using relative positioning. startover.style.style. The correct syntax is obj. since it has little effect on the document’s formatting. <div> is a good tag to use to create a layer. b. The absolute value for the position attribute allows you to set its coordinates.86 Hour 6 2.left=100. c. c.obj.left=100. . b. obj. b. try the following exercises: • Add a “start over” button to Listing 6. Which value should you use for the position attribute in a layer if you want to position it at a specific coordinate? a. obj. that resets all of the objects to their original positions.left=100. • Try positioning one or more of the layers in Listing 6. an event handler should call a new function. absolute static relative 3. Answers 1. a.left=100. 3. 2.

You’ll learn how to dynamically add items to a page. and how layers can make dynamic pages. and modify the attributes of any part of a page. change anything. remove them. However. and watch the browser’s display update instantly. you’ll explore more of the properties and functions you can use to take full advantage of the new DOM in your dynamic pages. layers limit you to working with overlapping. In this hour.HOUR 7 Working with DOM Properties and Methods You have now learned the basics of the DOM objects that allow DHTML to work. The new W3C DOM overcomes this limitation—you can virtually rewrite the HTML of a page dynamically. rectangular areas of a page. This hour covers the following topics: • Working with DOM node properties • Using methods and properties of the document object • Creating new elements and adding them to a page .

you refer to the node’s object. there are two text nodes defining the text within the <h1> and <p> tags. and a p node defining a paragraph.tagName). In the HTML example above. The easiest way to do this is using the getElementById method.tagName after assigning the ID attribute. but this won’t work—you need to work with the object. as you learned earlier.getElementById(“head1”). The following example displays the tagName property of the heading: h=document. You can work with any of the nodes that make up a Web page by examining or modifying the node’s properties. “Understanding the DOM. not the identifier. In the following sections. consider the following fragment of HTML: <body> <h1 ID=”head1”>This is a heading</h1> <p>This is a paragraph</p> </body> This HTML defines the body of a page with a body node containing the remaining nodes. alert(“tag name is “ + h. In Hour 5. You might be tempted to simply refer to head1.” you learned a few of the most useful properties of DOM objects. an h1 node defining a heading. To access these properties. or by referring to its relationship with other objects.88 Hour 7 • Changing attributes of HTML tags dynamically • Adding and removing HTML elements Understanding Node Properties As you have learned earlier in this book. each element on a Web page is called a node. . You should always obtain the correct object using the getElementById method. In addition. you’ll take an in-depth look at more of the available properties. For example. notice that the <h1> tag included an ID attribute assigning the identifier head1 to the heading.

contained within the node. Notice that the paragraph itself doesn’t have a nodeValue property. You can change the contents of the paragraph directly. obj. you can change the nodeValue attribute for the text node: obj=document.getElementById(“para”). This creates a new text node. Offset Properties Although you can set any style property for an object using JavaScript. but it works for any node and can include HTML. The first of these is the nodeValue property. When using this property to add HTML elements.firstChild. there is no need to refer to a text node. which contains the actual text for a text node. obj.innerHTML=”This is the <b>new</b> text. or HTML. here is an alternate way to change the text of a paragraph: obj=document. The InnerHTML Property The innerHTML property is similar to nodeValue. This is one of the most powerful DOM properties available. 7 . including a bold section defined by the <b> tag. not just text. In Hour 4.left and style. the following HTML defines a paragraph: <p ID=”para”>This is a simple paragraph. you can drastically change the document—in fact. you can’t read its position with the style. For example.”. For example.getElementById(“para”). For example.firstChild in the example. With innerHTML. you can rewrite it completely.” you used the innerHTML property to change text within a page. you often can’t read the values of these properties.top properties. instead you need to refer to the text node contained by the paragraph. be sure to include all opening and closing tags and follow proper HTML syntax. so you don’t create a browser error.nodeValue=”New Text”.</p> To change the text within this paragraph. “Creating a Simple DHTML Example. By adding HTML tags to the innerHTML property. unless an object is positioned absolutely.Working with DOM Properties and Methods 89 The nodeValue Property Each node has properties that define any text. obj.

offsetWidth offsetHeight Unfortunately. Using Document Methods and Properties The DOM also includes a number of useful methods that you can access from the document object. you will need to insert the node somewhere on the page. such as a table. The offset properties are not style properties. the way these properties are supported is not consistent. as described later in this hour. although they don’t include the page margins. This creates a new text node and stores its object in the variable n. In Netscape.90 Hour 7 While not part of the W3C DOM standard. Creating Text Nodes The document.getElementById gets the object for an element. document.getElementsByTagName The following sections will introduce you to some other useful things you can do with methods of the document object. You have already learned about two of these: • • document. it does not display the text on the page—to do that. In Internet Explorer. is the vertical position of the object. For example. this statement creates a node containing a simple line of text: n=document. gets a collection of objects with the specified tag name. which you can access as a JavaScript array. the offset values are always measured from the edges of the browser window. However.”). when an object is laid out within another object. . is the height of the object. is the width of the object. and are accessed directly under an object rather than under its style property.createTextNode(“This is the text. both Internet Explorer and Netscape support a number of properties that allow you to overcome this limitation: • • • • offsetLeft offsetTop is the horizontal position of the object.createTextNode method allows you to create a new text node. the offset properties are relative to the containing object.

The parameter defines the type of node by specifying its HTML tag.innerHTML to access the entire HTML document for the current Web page.lastChild is the BODY object. you can use document. As with the previous method. For example.nodeName is the name of the HTML tag that defines the document: HTML. Instead. the following statement creates a new node defining a paragraph and stores its object in the variable p: p=document. It also represents the root of the hierarchy and allows access to all properties.documentElement.createElement method creates a new HTML element. The documentElement object Although the document object is at the root of the DOM hierarchy. document.createElement doesn’t include any content within the paragraph you created. The following sections describe some of the most useful node methods. without the angle brackets: simply P instead of <p>. you need to use the documentElement object. For example. you can’t look at the nodeName or nodeType properties for the document itself. and document. Notice that document.documentElement. Using Node Methods Along with the document methods.createElement(“P”). you can’t access its properties directly.documentElement. For example. referring to the <html> tag.documentElement. The documentElement object includes some powerful features. document. the DOM provides a number of methods that work directly on individual nodes. 7 . firstChild is the HEAD object. For example. This object is a child of the document object. You can add text to the paragraph using the innerHTML property or by adding a text node under the paragraph.Working with DOM Properties and Methods 91 Creating Elements The document. the new element is not placed on the Web page yet—you’ll need to insert it.

as a child of the span: span=document. To use insertBefore. the new node is simply stored in a variable (newobj in the example) that you can later use to insert the node. For example. For example. you can also use the cloneNode method. Inserting a New Node The insertBefore method provides another way to insert a new child node. if the value is false. except that you also specify an existing child node. and the existing child node as the second parameter. you specify the new node as the first parameter. In this case. effectively adding a node to the document. which you have previously created. the object the node represents will move to the new position. If its value is true. You can also use appendChild with a node that is already on the page. Appending a New Node The appendChild method adds a new child object for a node. It works similarly to appendChild.appendChild(newobj). this statement creates a copy of the obj object: newobj=obj. or createTextNode to the document. This is one way to add a node you have created with cloneNode. suppose you have a span defined within an HTML document.cloneNode(true). span. As with the other methods that create nodes. For example. the child objects are not cloned. createElement.getElementById(“addhere”). like this: <span ID=”addhere”></span> The following JavaScript statements would add the newobj node. The parameter for cloneNode is a Boolean value.92 Hour 7 Cloning a Node You have already learned how to create new nodes using document methods. If you want to create a node similar to one that already exists. The new node is inserted before the node you specify. any child objects of the node are also copied to the clone. the following statements use .

replaceChild(newobj. it works directly on a node rather than a child object.replaceNode(newobj).getElementById(“para”). the replaceNode method can also replace a node. span. span.”.insertBefore(newobj.createElement(“H1”). and create a new object for the heading.p). suppose you defined a span containing a paragraph like the previous example: <span ID=”changeme”><p ID=”para”>This is a paragraph</p></span> 7 . newobj=document. For example. Replacing Nodes The replaceChild method is another way to add an object to a document. The replaceNode method is not part of the W3C DOM standard. p=document. newobj. You can also remove part of a page using the removeChild method. Since the heading is created without any text.Working with DOM Properties and Methods 93 appendChild to add a child object to a span. In this case. These statements get objects for the span and the paragraph. I recommend using replaceChild instead to avoid browser issues.getElementById(“changeme”). the replaceChild method swaps the objects.appendChild(obj). and then use insertBefore to add another object before the one already inserted: span=getElementById(“addhere”). This statement could be used in place of the replaceChild method in the example: p. Alternately.innerHTML=”This is a heading. In this case. and at this writing. you can add it using the innerHTML property. The replaceChild method has two parameters: the new object and the one it should replace. Removing Nodes You have now learned how to add elements to a page in various ways. Finally. For example. span. is supported only by Internet Explorer for Windows. the new object replaces an existing child object. suppose you have defined a span like this: <span ID=”changeme”><p ID=”para”>This is a paragraph</p></span> The following statements would replace the paragraph with a heading: span=document.obj).

These include the following: • • • • getAttribute(attribute_name) gets the value of the attribute you specify and sets the value of an attribute. The removeNode method works similarly.94 Hour 7 The following statements remove the paragraph from the span.firstChild). These are parameters specified in the HTML tag. For example. I recommend you avoid using it until it is better supported by browsers. setAttribute(attribute_name. Working with Attributes Along with the nodes that represent HTML tags.0 or later and Internet Explorer 5. this image tag has align and src attributes: <img align=”center” src=”line.0 or later. Notice the shortcut here: Rather than get the object for the paragraph. you can also work with attributes in DHTML. the child objects remain. stores it in a variable. simply returns true if the node has attributes. the hasAttributes method only works in Netscape 6. The removeNode method is not part of the W3C DOM standard. and false if it has none. The parameter for removeNode is a flag: If it is true. span. you can simply refer to it as span. value) removeAttribute(attribute_name) hasAttributes() removes the attribute you specify. Currently. but works directly on a node. and is currently supported only by Internet Explorer for Windows. span. any child objects of the node are also removed. leaving it empty: span=document. paragraph and all: span=document.removeChild(span.getElementById(“changeme”).getElementById(“changeme”).firstChild since you know it is the only child object of the span. For example. these statements would delete the span in the previous example.gif”> The DOM includes several methods you can use on nodes to manipulate their attributes. . If it is false.removeNode(true). The other methods discussed here work in Netscape 6.

”>centered</a> using the links in this paragraph.”>left</a>. 7 .”>right</a>. you can create a script that allows the user to change the align attribute of a heading. LISTING 7. Notice that the links in lines 16–18 begin with javascript:.getElementById(“head1”). <a href=”javascript:AlignMe(‘right’). Listing 7. You can change the alignment of the heading above to <a href=”javascript:AlignMe(‘left’).setAttribute(“align”. and we will use it throughout this book.Working with DOM Properties and Methods 95 As a simple example of using attributes.getElementById) return. This is an easy way to prevent errors on browsers that do not support DHTML. h. } </script> </head> <body> <h1 ID=”head1” align=”left”>Modifying Attributes</h1> <p>This is a demonstration of changing HTML attributes using DHTML.1 shows the HTML and JavaScript document for this example. This is an easy way to make a link call a JavaScript statement or function without using an event handler.1 Changing Attributes of HTML Tags <html> <head> <title>Modifying Attributes with DHTML</title> <script language=”JavaScript”> function AlignMe(a) { if (!document. You might recognize the first line in the AlignMe function: if (!document. This accepts a parameter. and sets the align attribute for the heading with the ID head1 to the value specified.getElementById) return. </p> </body> </html> In this listing.a). and the links within the body text call the AlignMe function to change the attribute. The <h1> tag defines the heading itself. the AlignMe function changes the heading’s alignment. h=document.. or <a href=”javascript:AlignMe(‘center’).

or horizontal lines to the page or delete items from the page.1 Netscape shows the attribute changing example in action. Add Heading. headings. you will be able to add paragraphs. This is simply a text field. and Delete a Node functions: .1 shows Netscape’s display of this example after the heading’s alignment has been moved to the right side. you can start with the HTML you will need. you will need a place to insert the new nodes on the page. Add Line. The <span> tag is an ideal way to set aside a space for the new nodes: <span ID=”addhere”> </span> Next. FIGURE 7. you can create an HTML document that can modify itself—using a form.96 Hour 7 Figure 7. and buttons for the Add Paragraph. Setting Up the HTML Document To begin creating this example. you will need the HTML form that allows the user to add and remove nodes. In particular. Workshop: Adding and Removing Text on a Page As a way to demonstrate some of the methods you learned in this hour.

if (tag != “HR”) { txt = document.form1. } s=document.innerHTML=txt. The DeleteNode function finds the object for the span and removes its last child node: function DeleteNode() { if (!document. element.lastChild). If the tag is not an <hr> tag.”> </form> The AddNode Function When the buttons in the form are clicked. the appendChild method adds the new element to the page. The DeleteNode Function The Delete a Node button will simply delete the last node that has been added. Here is the JavaScript code to define the AddNode function: function AddNode(tag) { if (!document.getElementById(“addhere”).newtext.getElementById) return.createElement(tag).2 shows the complete HTML document. Finally.Working with DOM Properties and Methods 97 <form name=”form1” ID=”form1”> <input type=”text” name=”newtext” size=”70”><br> <input type=”button” value=”Add Paragraph” onClick=”AddNode(‘P’).getElementById) return. element = document.”> <input type=”button” value=”Add Heading” onClick=”AddNode(‘H3’). } Putting It All Together You can now combine the functions and HTML you have created into a single HTML document to create the complete example.getElementById(“addhere”). } This function creates a new element using the tag name specified as a parameter. All of the buttons that add an element use the same function.appendChild(element). they will call a JavaScript function using the onClick event handler. Listing 7. s.”> <input type=”button” value=”Delete a Node” onClick=”DeleteNode(). s=document. it also creates text for the element based on the form’s text field.value.”> <input type=”button” value=”Add Line” onClick=”AddNode(‘HR’).removeChild(s. 7 . s.

lastChild). Once you load this document into a browser.”> <input type=”button” value=”Add Line” onClick=”AddNode(‘HR’).”> </form> </body> </html> <span> In this listing. .</p> <span ID=”addhere”> </span> <form name=”form1” ID=”form1”> <input type=”text” name=”newtext” size=”70”><br> <input type=”button” value=”Add Paragraph” onClick=”AddNode(‘P’).form1. element. } s=document. s.getElementById) return.getElementById) return. if (tag != “HR”) { txt = document. } function DeleteNode() { if (!document.getElementById(“addhere”). s.appendChild(element).”> <input type=”button” value=”Delete a Node” onClick=”DeleteNode().getElementById(“addhere”). } </script> </head> <body> <h1>Adding and Removing Nodes</h1> <p>Enter some text and use the buttons below to add or remove nodes from this page’s DOM hierarchy.newtext.2 The Complete Example to Add and Remove Nodes <html> <head> <title>Adding and Removing Nodes</title> <script language=”JavaScript”> function AddNode(tag) { if (!document.removeChild(s.value. The tag provides a place for the added content.98 Hour 7 LISTING 7. and the <form> section creates the form that allows you to change the document. Figure 7.2 shows Internet Explorer’s display of the example after several nodes have been added. element = document.createElement(tag). the <script> section defines the AddNode and DeleteNode function.”> <input type=”button” value=”Add Heading” onClick=”AddNode(‘H3’). you can add or remove nodes using the form.innerHTML=txt. s=document.

including the body of the page itself. so you should test with several browsers. This allows you to create dynamic pages that can change in any way you choose. you’ll learn more about event handlers and how they can be used with DHTML.0 browsers? A. 7 . You can sometimes do similar things using layers. or removing them. Q. you’ve started to learn some of the truly powerful things you can do with DHTML: adding elements to a page. Which attributes of HTML tags can I change using DHTML? A. No. moving. In theory. browsers might not support all attributes. replacing them. Summary In this hour. Q. Do I have to use a span to create an area to add or remove nodes? A. not at all. However. but the flexible DHTML features of the W3C DOM aren’t available in older browsers. You can use any object on the page that can have child objects. any of them.Working with DOM Properties and Methods 99 FIGURE 7. In the next hour.2 The document with several added nodes. Q&A Q. Is there a way to add and delete nodes that will work with version 4. No.

b. • Add a new button labeled Add Line Break to the form in Listing 7. use document. b. b.createNew 2. try modifying the Delete Node button to delete the first added node instead of the last one.getAttribute(“src”). x = getAttribute(“src”.image1). and make it add a <br> tag to the page.100 Hour 7 Quiz Test your knowledge of the material covered in this hour by answering the following questions.getAttribute(“src”). Which of the following is the correct command to get the SRC attribute of an image stored in the object image1? a. c. document. a.SRC x = image1. c. Which method should you use to create a new paragraph? a. The appendChild method adds a new node as the last child of an existing node. a. Which method adds a new node as the last child of an existing node? appendChild appendNode insertBefore 3.createTextNode document. x = image1. .createElement document. Questions 1. The correct command is image1.2. b. 3.2. 2. try the following exercises: • In Listing 7. Answers 1.createElement. To create a new paragraph. Exercises If you’d like more practice using the DHTML techniques you learned in this hour. b. c.

You’ll also create an example that uses DHTML to log events as they happen. In this hour. this hour deals with events. In the last seven hours. you’ve learned much of what you need to know to get started with DHTML.HOUR 8 Responding to Events You’ve nearly reached the end of Part II. As a final subject before you move on to other topics. This hour covers the following topics: • The basics of event handlers • Using the event object to find out about an event • Using Dynamic event handlers • Using Mouse events • Using Keyboard events • Using the onLoad event • Using events with forms . you’ll review the available event handlers and how they can be useful in your dynamic pages.

the browser calls the StartHere function. However.type. you can’t use double quotation marks (“) in your JavaScript statements here. separated by semicolons. } Unfortunately. JavaScript includes an event object that provides this information. this statement defines an onKeyPress event that passes the event object to a function: <body onKeyPress=”getkey(event). while both Internet Explorer and Netscape support the event object. .102 Hour 8 Understanding Event Handlers You’ve already used event handlers in many of the scripts in this book.”> This example is an HTML <body> tag.”> You can then define your function to accept the event as a parameter: function getkey(e) { . This particular event occurs when the document first loads. the type of event. One property that is the same in both browsers is event. with an onLoad event defined with an event handler. The following sections list some additional useful properties for each browser. they support different properties. When the event is detected. you can pass it on to your event handler function. An event handler is used to detect when an event (such as the user clicking the mouse) occurs for an object (such as a link or image. you might need to know more about the event—for example. Because the event handler attribute is enclosed in double quotation marks.) Here is the basic HTML for an event handler: <body onLoad=”StartHere().. and keypress for an onKeyPress event. for a keyboard event. you can use single quotation marks (‘). This is simply the name of the event.. you can also include one or more JavaScript statements directly in the event handler. While functions are useful for event handlers. Using the event Object When an event occurs. For example. such as mouseover for an onMouseOver event. To use the event object. you need to know which key was pressed.

event.) were held down during the event.clientY: event. This value is 1 for the left button and usually 2 for the right button. The x-coordinate (column. The W3C DOM Level 2 standard defines a browser-independent way of detecting events. flag that indicates whether the ALT key was pressed during the event.shiftkey: event. event.pageY: event. event. 8 Internet Explorer event Properties The following are some of the commonly-used properties of the event object for Internet Explorer 4. ALT. or the button that was pressed for mouse events (1 for the left button.button: The mouse button that was pressed.ctrlkey: Indicates whether the CTRL key was pressed.srcElement: Netscape event Properties The following are some of the commonly-used properties of the event object for Netscape 4. etc. . The y-coordinate (row.0 and later: • event.clientX: event. but it is not yet well-supported. The y-coordinate of the event within the Web page.Responding to Events 103 The workshop section of this hour demonstrates how to deal with browser differences when using these properties.target: The object where the element occurred.0 and later: • • • • • • • • event. 3 for the right). in pixels) where the event occurred. The object where the element occurred.modifiers: Indicates which modifier keys (SHIFT. CTRL.pageX: event. This value is an integer that combines binary values representing the different keys. The key code (in Unicode) for the key that was pressed.keyCode: event. Indicates whether the SHIFT key was pressed.altkey: A event. The keycode for keyboard events (in Unicode). in pixels) where the event occurred. event.which: • • • • The x-coordinate of the event within the Web page.

onMouseOver worked only with links and images. you can assign the event handler dynamically using JavaScript. . list items. is triggered when the mouse pointer moves out of range of an object it previously entered. Be sure to test any event handler you create in the latest browsers. Your scripts can detect when the mouse pointer moves. Rather than specifying an event handler as an HTML attribute.pageX and event. Using onMouseOver and onMouseOut Events One of the common mouse event handlers used is onMouseOver. This event is triggered when the mouse pointer moves over an object within the browser window. This is useful for undoing whatever action you performed on the onMouseOver event. onMouseOut. headings. and when a mouse button is clicked or released. you specify the property for the object with the same name as the event handler. this event can be detected for any object in the HTML document: paragraphs. To change an event handler.pageY properties are based on the top-left corner of the element where the event occurred.104 Hour 8 The event. or activate or deactivate one. This technique is useful if you wish to change an event handler. However. Traditionally. you must separately define the HandleKeys function using the function keyword. in the new DOM-based browsers. Dynamic Event Handlers Event handlers are stored as objects in the DOM. corresponding with the objects for which they handle events. For this to work. Using Mouse Events A number of the available events deal with the mouse.onkeypress = HandleKeys. For example. and so on. Remember that different browsers support events differently. The opposite handler. not always the exact position of the mouse pointer. and some events aren’t detected in all browsers. this statement makes the function HandleKeys the event handler for onKeyPress events within the document: document.

buttons. and then coming back up. and images—but in the DOM-compliant browsers. is to set a function as the onMouseMove handler for the document. beginning in Part IV.Responding to Events 105 You used the onMouseOver and onMouseOut event handlers in Hour 4. “Creating a Simple DHTML Example. This is similar to the dynamic events technique you learned earlier in this hour. which must be defined in the same page: document. A mouse click really consists of two actions: the button going down.MOUSEMOVE). you need to use event capturing. “Dynamic HTML in Action. For example. “Creating Complex Animations. but requires an extra step for Netscape browsers. You can detect these two events separately using the onMouseDown and onMouseUp event handlers.” 8 Using the onMouseMove Event The onMouseMove event occurs any time the mouse pointer moves. As you might imagine. In Hour 22. To enable it for a page. this statement sets the onMouseMove handler for the document to a function called MoveHere. Detecting Mouse Clicks Your scripts can also detect clicks of the mouse on a particular object.captureEvents method: document. Additionally. for both browsers. You can also detect double-clicks using the onDblClick event handler.onMouseMove=MoveHere. this happens quite often—the event can trigger hundreds of times as the mouse pointer moves across a page.captureEvents(Event. onMouseMove The basic syntax to support this event. or another object. . Netscape requires that you specifically enable the event using the document.” you’ll create an example that captures the onMouseMove event in both Netscape and Internet Explorer. Because of the large number of generated events. this event handler only worked with clickable items—links. The basic handler for this is onClick.” You will use them again later in this book. In earlier browsers. it works on any object. browsers don’t support the event by default.

and thus the onClick event only occurs when the left button is clicked. Rather than checking for a particular browser. the event.button property indicates the button clicked. As mentioned earlier in this hour.106 Hour 8 When a mouse button event occurs. • For Internet Explorer. To support both browsers. a keypress really consists of two events: the key coming down. Internet Explorer displays a context menu when the right button is clicked. you’ll need to use the if statement when checking buttons.which. you can use the properties of the event object to determine which button was clicked. while Internet Explorer 5 and later generate onMouseDown and onMouseUp events. You can detect these separately using the onKeyDown and onKeyUp event handlers. This checks for the existence of the event. . The example in the Workshop section of this hour uses this technique to detect mouse buttons browser-independently. indicating that the browser follows Internet Explorer’s model.which instead. Using Keyboard Events You can also detect keys being pressed using event handlers. here is the shell of an if statement to handle buttons: if (event. Internet Explorer 4 doesn’t generate any events for the right button. This only works on the onMouseDown and onMouseUp events. it’s better to detect the event properties directly. 1 for the left button and 3 for the right.button) button=event.button. or to form elements.button property. the event. to detect keys pressed within a field. this depends on the browser in use: • For Netscape. As with mouse clicks. 1 for the left button and 2 for the right. such as text fields. For example. not on onClick.which property indicates the button clicked. If this property doesn’t exist. it uses the Netscape model’s event. and going back up. else button=event. The basic event handler for this is onKeyPress. You can attach this handler to the <body> tag to detect any keypress.

the key code is a numeric value representing the key. but supports 32-bit codes to handle international characters. typically moving the cursor there). This can be used on the Window object as well as form elements.fromCharCode method. alert(“Key pressed: “ + String. and displays the character for the key: if (event. Form Events Last but not least. 8 The key codes used in JavaScript are in the Unicode format. the script you specify is called as soon as the HTML document is fully loaded by the browser. occurs when an element loses focus. and so on.Responding to Events 107 You can use the properties of the event object to determine the key that was pressed. buttons. For example.keyCode. This is useful for initializing variables in a script or starting an animation. In this case. As with mouse events.fromCharCode(key)). the event. This is similar to the old ASCII code.which property stores the key code for the key pressed. The onLoad Event The onLoad event handler is one you will use often. In both cases. occurs when a text field or <select> drop-down value is changed. the event handler will be called when the image finishes loading. determines the key code browser-independently. there are a few events that are only used on form elements—text fields. These include the following: • onFocus occurs when an element gets focus (when it is clicked on. this code detects a key. • For Internet Explorer. else key=event. how you do this depends on the browser: • For Netscape. the event.which. You can also specify an onLoad event for an <img> tag. If you specify an onLoad event handler for the <body> tag of a document.keyCode property stores the key code for the key pressed. • • onBlur onChange . You can convert this to a character using the String.keyCode) key=event.

• occurs when a reset button for the form is pressed.fromCharCode(keycode).appendChild(document. the form is not submitted.1 The Event Logging Example <html> <head> <title>Event Handlers Example</title> <script language=”JavaScript”> function DisplayEvent(e) { span=document. else button=e.starlingtech. span. This handler is attached to the <form> tag itself. logentry= e. logentry += “ key=” + key. If the event handler returns false.keyCode) keycode=e.appendChild(txt).keyCode. key=String.1 shows the complete HTML document for this example. } txt=document.button) button=e.108 Hour 8 • onSubmit occurs when a submit button for the form is pressed. } </script> </head> <body onKeyPress=”DisplayEvent(event).which.type.which.type==”mouseup”||e. LISTING 8. if (e. Listing 8. else keycode=e. span.”> .getElementById(“addhere”). You can download the HTML file for this example from this book’s Web site: http://www.com/dhtml/.type==”mousedown”||e.type==”keypress”) { if (e. } if (e. you can create a page that demonstrates events by displaying event names as they happen. onReset Workshop: Displaying an Event Log Using the event handlers you learned this hour and a bit of DHTML. This handler is attached to the <form> tag itself.createElement(“BR”)).type==”click”) { if (e.button. logentry += “ button=” + button. the form fields are not reset.createTextNode(logentry). If the event handler returns false.

1 continued <h1>Event Handlers Example</h1> <p>Move the mouse in and out of the heading below. and pressing keys. This is where the log entries will be added. • The body ends with an empty <span> tag with the ID attribute addhere. but the onMouseDown and onMouseUp events correctly specify the button. Notice that the event detection isn’t perfect in current browsers—for example.</p> <h1 style=”color:blue” align=”center” onMouseOver=”DisplayEvent(event). To test the example. .” onClick=”DisplayEvent(event). clicking on it.” onMouseOut=”DisplayEvent(event). all set to call the DisplayEvent function when events occur. The events that occur will be listed below.Responding to Events 109 LISTING 8. the button for onClick events is undefined.1 shows Netscape’s display of this example after a few events have occurred. DHTML is used to insert the log entries into the document. Figure 8.” onMouseDown=”DisplayEvent(event). • The body begins with a <h1> header with a large number of defined event handlers. • The <body> tag assigns the onKeyPress event handler for the entire document to the DisplayEvent function. It displays the event type. or click on it. load it into a browser and try generating events by moving the mouse over the blue text. and uses the techniques you learned earlier in this chapter to determine the key or mouse button that was pressed. in Internet Explorer.” onMouseUp=”DisplayEvent(event).” > Generate Events Here </h1> <b>Event Log:</b><hr> <span ID=”addhere”></span> </body> </html> 8 Here is a breakdown of how this example works: • The DisplayEvent function displays each event.

Yes. DOM Level 2 defines a standard way of capturing and referring to events. and how to control them dynamically. you have the best chance of supporting older browsers. If you can use a link as the target for the event handler. Q&A Q. . Congratulations—you’ve reached the end of Part II! In Part III. Summary In this hour. and used DHTML to create an event log. If I can specify an onMouseOver event handler for any object. Yes. This is currently supported by Netscape 6. Doesn’t the W3C DOM do something about the differences between Internet Explorer and Netscape event handlers? A. are some objects better choices than others? A. you’ll learn about style sheets: how to create and use them effectively. you’ve reviewed the events that are available to your DHTML scripts. You’ve learned how to obtain information about events.110 Hour 8 FIGURE 8. You’ll begin in the next hour by learning the fundamentals of style sheets. Q.1 Netscape 6 displays the event logging example.

Which of the following indicates which mouse button was clicked in Internet Explorer? a. Which is the correct statement to display the key that was pressed as a character. The correct statement is alert(String..which property performs the same function in Netscape. 3.fromCharCode(key)). . event.fromCharCode()). a. c.which event. The onMouseOver event occurs when the mouse pointer moves into the area used by an image (or any other object). c. 8 Quiz Test your knowledge of the material covered in this hour by answering the following questions.button 3.onClick event. When I use an onSubmit event handler. b. The event. alert(String. 2.button property indicates the mouse button used in Internet Explorer. alert(key. You need to make sure you include return true as the last statement in the event handler. onMouseMove onMouseOver onMouseEnter 2. b. c. why is the form no longer submitted? A. alert(toCharCode(key)). Answers 1. presuming you have stored the keycode in the key variable? a. b.fromCharCode(key)). c. The event. b. Questions 1.Responding to Events 111 Q. Which event handler is triggered when you move the mouse into the area an image uses? a. Otherwise the submission is cancelled.

try the following exercises: • Modify Listing 8. and make any changes needed to the script to display these events in the log.1 to display the mouse button pressed as “left” or “right” rather than a number. • Add onKeyDown and onKeyUp event handlers to the <body> tag in Listing 8. Keep in mind that different browsers might use different values for the right button.112 Hour 8 Exercises If you’d like to practice using event handlers further before you move on. .1.

PART III Working with Style Sheets Hour 9 Introducing Style Sheets 10 Using Style Sheet Properties 11 Controlling Styles with JavaScript 12 Creating Consistent Styles .

.

fonts. The CSS (Cascading Style Sheets) standard defines ways to control a document’s style—colors. the formats you can use to create style sheets. margins. and so on—while staying within the bounds of the HTML standard. In this hour. you will focus on style sheets. and some of the basic style properties you can use in your documents.HOUR 9 Introducing Style Sheets Welcome to Part III! For the next four hours. This hour covers the following topics: • Why style sheets are useful • How style sheets fit in with HTML documents • Using external style sheets • Basic properties for style sheets • Creating a simple style sheet . you’ll learn the basics of style sheets—the rules they use.

colors. If you look at the majority of HTML tags. not the presentation. or a link to another page. a list. the margins. The fact that HTML doesn’t focus on font sizes or colors means that a single HTML document can be displayed on vastly different browsers—ranging from high-end computers to TV-based systems to tiny screens on mobile phones. . chances are it will display differently for users with certain browsers or computers. fonts. or spacing with HTML. There are even some highly specialized browsers—for example. it’s not very attractive to the graphic designers and marketing folks who have moved to the Web. Content versus Presentation You can’t precisely control the layout. It’s hard to understand why you can easily create a flyer or magazine ad in the exact style you want. probably larger than that of an <h2> heading. The HTML language’s emphasis on content makes this possible. you’ve undoubtedly noticed that it isn’t always easy to give your document the exact appearance you desire using HTML—in fact. This sounds like a deficiency of HTML. you’ll notice that they describe part of the content of a document—a paragraph. There’s a reason for this—HTML is a language meant to specify the content of a document. but your Web page has to resemble all of the others. you just know it will be displayed in large text. even when you’ve created the perfect page. HTML’s structure also makes it easy for search engines to find headings and other important text in a document. typically using different voice styles to speak headings. but it’s actually a good thing. The Traditional Approach While HTML’s emphasis on content is noble. a heading. without having to make judgments based on font sizes. You don’t know the exact font or size that will be used. When you specify an <h1> heading.116 Hour 9 Why Style Sheets? If you’ve created a Web page or two. They don’t specify exactly how to present these items. browsers for the blind can read an HTML document using a speech synthesizer. paragraphs. and other components.

you can create a stylish document that will work in any standards-compliant browser. For example. Inline Styles One simple way to use CSS styles is to use the STYLE attribute in one or more individual HTML tags. Users can configure their browsers to ignore your style sheet if they wish. Rather than change the HTML language. The version 4. Adding Style to Substance Fortunately. 9 Another important aspect of style sheets is that they are separate from HTML and optional. and can even specify their own style sheet for all of the HTML documents they view. Some. Integrating Style Sheets with HTML You can add style sheets to your HTML documents in several ways: • Using inline styles within HTML tags • Using the <style> tag within a document • Creating an external style sheet The following sections explain each of these options. and the support in newer browsers is even more complete. Designers focused on style have even gone overboard at times—for example.”>This is a blue heading.</h1> You’ve seen this method earlier in this book. This effort resulted in the CSS (Cascading Style Sheets) standard. Using CSS styles.Introducing Style Sheets 117 This has led to a variety of techniques for making HTML into a presentation language. they created a way of defining styles that gives you full control over presentation without compromising HTML’s ability to focus on content. and it’s very easy to use.0 browsers began to support style sheets. this method doesn’t give you the full advantage of style sheets—using the same style for a number of different elements. like the <font> tag. were introduced by browser makers. before things like this got too far out of control. the following HTML defines a heading that is blue in color: <h1 STYLE=”color:blue. However. making the entire Web page one huge graphic image in order to use the fonts and layout they prefer. the W3C decided that there should be a standard way of adding style to HTML. .

The first sets headings using the <h1> and <h2> tags to be centered and blue in color.118 Hour 9 The <style> Tag A more sophisticated way of using style sheets is by using the <style> tag within the <head> section of your HTML document. and the second sets paragraphs using the <p> tag to be red. For example. Creating Rules Rules within a style sheet use a set syntax. you might wish to use HTML comment tags (<!-. you might want all of the text within your page’s menu to have a specific style. • One or more property names (color in the example). as in this example: <style TYPE=”text/css”> H1. Netscape 4. text-align: center} P {color: red} </style> This style sheet includes two rules.menu class for this purpose in the style sheet: .menu {color: blue} .and -->) to enclose the contents of your <style> tags. You can create a .0 supported an alternate type known as JavaScript Style Sheets. Using Classes Rather than specifying an HTML tag in a CSS rule. You can enclose a block of rules between the <style> and </style> tags. To avoid errors in older browsers. but these were proprietary and are not supported in Netscape 6.H2 {color: blue. • A value for each property name (red in the example). or only to certain tags. you can also create a class and specify rules for the class. Consider this simple rule from the earlier example: P {color: red} Each rule includes three components: • A selector (P in the example) describing which HTML tags will be effected. This allows you to create styles that can apply to several different HTML tags. The TYPE=”text/css” attribute in the <style> tag tells the browser to use the CSS standard for styles.

10pt). handheld computers) the browser might rescale this value to fit the device. In some devices with non-typical resolutions (for example. ex: Approximate • height of the letter x in the current font (for example. 1.menu {color: black} 9 This rule sets the color to black for any <h1> tag that has been assigned the menu class. used to assign a unique identifier to a particular HTML element. . To assign the class. include the CLASS attribute in one or more HTML tags: <p CLASS=”menu”> For more complex styles. 15px).menu tells the browser that this is a class selector rather than a specific HTML tag.2ex). You’ve seen the ID tag already. Pixels are the smallest addressable units on a computer screen or other device. Using IDs You can also assign a style sheet rule to a specific ID. Points are equal to 1/72 of an inch. Anything with the specified class will be displayed as blue. Points are a standard unit for font size. This might be assigned to a heading tag like this: <h1 ID=”head1”>No Time to Lose</h1> You should only assign each unique ID to one HTML tag. or types of values you can specify. use a class instead. Using Units Style sheet properties support a wide variety of units. If you want to assign a style to two or more tags. pt: px: • Points (for example. you can also specify a rule for a class and a specific HTML tag: h1.Introducing Style Sheets 119 The period at the beginning of . The following rule sets the style for a specific ID: #head1 {color: red} This sets the color to red for the HTML tag with the ID head1. The size of text of a specified point size varies depending on the monitor resolution. Most properties that accept a numeric value support the following types of units: • Pixels (for example.

this rule sets the URL for the background-image property: body {background-image: url(path/background.css”> You can link more than one external style sheet to a document. You can also use inline styles or the <style> tag in the document to override styles in an external style sheet. You can use the <link> tag within the <head> section of your document to do this: <link rel=”stylesheet” href=”styles. Whenever possible.120 Hour 9 • • em: Approximate %: width of the letter m in the current font (for example. em. To use an external style sheet.} External Style Sheets While a simple style sheet is easy to include within an HTML document using the <style> tag. This uses a special syntax. without the opening and closing <style> tags. or ex sizes. Percentage of the containing object’s value (for example. This will make values relative to the current font. for example styles. type your list of style rules into a text file. Some style properties accept a URL as their value.5em). 150%). you need to link it to one or more HTML documents. 1. Save the document with the css extension. pixel units for the size and position of layers or other objects. and the styles will be combined. . Once you have an external style sheet.gif). For example. This allows you to separate all of the styles into their own file. you can use the same external style sheet for several pages or even an entire site. This is usually equal to the font-size property for the current element. Point sizes are commonly used for fonts. More importantly. and will scale if the user has specified their own font. and so on. you might find it useful to create an external style sheet instead. use percentages. Which unit you choose to use is generally a matter of convenience.css.

you to move the element up or down to align with other elements on the same line. styles in a <style> block. along with inherited styles. For example. can be used for any tags. and this is the method browsers use to combine styles you have specified.Introducing Style Sheets 121 Cascading Styles The “C” in CSS stands for cascading. the browser might need to combine styles from one or more external style sheets. This is done using a set of rules for cascading styles. In a complex situation. and inline styles. You’ll learn more of the available style properties in Hour 10. such as text colors.”> The style you specify here is inherited by all of the children of the <body> tag—the entire document.” Aligning Text One of the most useful features of style sheets is the capability to change the spacing and alignment of text. the following is an important rule to set the color of paragraph text: P {color: black !important} 9 Basic Style Properties There are a wide variety of properties you can use in defining styles. This will ensure that the style overrides others that would control the style of the same elements. . You can ensure that a rule you specify comes out on top in the cascade process by specifying the !important attribute. Some. The following properties are available: • • letter-spacing—Specifies vertical-align—Allows the spacing between letters. The following sections describe some of the most useful properties. it overrides the inherited style. For example. Most of these features aren’t available using standard HTML. “Using Style Sheet Properties. But if you specify a style for one of these elements. while others are specific to certain types of HTML tags. suppose you use the following <body> tag to specify a style: <body STYLE=”color: red.

background-image—Specifies the URL of an image to be used as the background for the element. such as #12AA05. you can make paragraphs. background-attachment—Controls whether the background image scrolls when you scroll through the document. background-position—Allows you to offset the position of the background image. vertically. If you specify a background image. and bottom for vertical positioning and left. background-repeat—Specifies • • • You can specify color values using named colors.122 Hour 9 • • • text-align—Specifies the justification of text. background—This provides a quick way to set all of the background elements in this list. . scroll means the image scrolls with the document. such as red and blue. line-height—Allows you to specify the distance between the top of one line of text and the top of the next. By setting this value. and right for horizontal positioning are also supported. This is useful for emphasizing text or for using a specific color scheme for the document. The image can be repeated horizontally. center. green. CSS includes the following properties for this purpose: • • color—Specifies the text color of an element. right. or no-repeat. The value can be repeat. background-color—Specifies the background color of an element. and blue color levels. as with background images on normal Web documents. text-indent—Allows you to specify the amount of indentation for paragraphs and other elements. The value can be a color or transparent for a see-through background. or justify. This can be left. You can specify horizontal and vertical values. or none for no background image. you should also specify a matching background color in case the image can’t be accessed. repeat-x for horizontal tiling. Defining Colors and Background Images You can also use style sheets to gain more control over the colors and background images used on your Web page. The keywords top. center. or RGB combinations. You can specify all of the attributes in a single background rule. table cells. center. fixed means that the background image stays still while the document scrolls. separated by a space. • • whether the background image is repeated (tiled). These use three hexadecimal numbers to represent the decimal values 0-255 for red. and other elements with unique background colors. repeat-y for vertical tiling. or both.

hidden. • • • right and bottom allow you to position objects by lining up the right-hand or bottom edges rather than the left and top. 9 • is the horizontal position of the item. the text will wrap at the specified width. Values include none to hide the object. These same properties can be used in style sheets to specify the position of any object: • position specifies how the element will be positioned. visibility • controls the item’s visibility. For objects containing text. The page layout shifts to account for changes to this property. z-index display • specifies whether the item is visible in the browser. Values include visible (default). so layers defined later in the HTML document are “on top” of previous layers. “Creating Positionable Elements (Layers). and relative defines an item that is offset a certain amount from the static position. Indexes are assigned in order. coordinates start at the left side of the browser window. where it was laid out by the browser. left top • is the vertical position of the object. and relative to the original position for relative positioning. block for a block element. . inline for an inline element. You can change this value to bring an object to the top. absolute allows you to position the item by specifying coordinates. This is relative to the top of the browser window for absolute positioning. and an example of using some of these positioning properties in a script. For absolute positioning.Introducing Style Sheets 123 Positioning Objects In Hour 6. for relative positioning. and cannot be moved.” you learned how to use positioning properties to control the position of layers. and list-item for a member of a list. they start at the object’s original position. specifies how the object overlaps with other objects. A value of inherit uses the visibility setting of a parent object. and inherit. Review Hour 6 for more details about the display property. width and height specify the item’s width and height. This property can have one of three values: static (default) defines items that are laid out along with the rest of the HTML document. without affecting the page layout.

you created a simple Web document for a fictional company.html”>Staff</a></td> <td width=”20%”><a href=”jobs. LISTING 9.} .</p> </body> </html> . </p> <table border=”1” align=”center”> <tr class=”menu”> <td width=”20%”><a href=”products.gif” width=”486” height=”180” border=”0” alt=””> </div><br> <h1>Welcome to Figby Industries!</h1> <p>Welcome! This is the home page of Figby Industries. text-align: center. and colors of the document in a browser-independent way.html”>Products</a></td> <td width=”20%”><a href=”sales.} </style> </head> <body> <div align=”center”> <img src=”logo. Figby Industries.1 shows the HTML document with an included style sheet.</title> <style type=”text/css”> BODY {color: yellow.124 Hour 9 Workshop: Creating a Simple Style Sheet Back in Hours 2–4.html”>Service</a></td> <td width=”20%”><a href=”staff. You can use style sheets to control the alignment. Follow the links below to learn more about our company and our products.menu {font-weight: bold.} P {color: black. Listing 9.} H1 {color: black.1 A Simple Web Document with a Style Sheet <html> <head> <title>Figby Industries.html”>Employment</a></td> </tr> </table> <p ID=”bottomtext”>Any truly legitimate company would have much more text in this part of the page than we have. text styles. your source for all sorts of imaginary products. text-align: center.html”>Sales</a></td> <td width=”20%”><a href=”service.} #bottomtext {font-style: italic. Inc.

. #bottomtext.1 shows Internet Explorer’s display of the styled document.Introducing Style Sheets 125 This example requires a graphic.starlingtech. This document uses the following styles. logo.menu. • A class. However. notice that no yellow text appears on the page.com/dhtml/. is set to have italic. load it into a browser. You can also download the HTML document there. defined in the <style> block: • The <body> tag is set to have yellow text.0 or later and Internet Explorer 4. To test this example. • <h1> 9 headings are set to be displayed in black and centered. • An ID.0 and later. . • Paragraphs are set to be displayed in black.1 The styled document as displayed by Internet Explorer. Figure 9. centered text. This is because each item has its color set by another style.gif. which you can download from this book’s Web site: http://www. FIGURE 9. This is used in the <tr> tag of the table. and is inherited by all of the link text in the <td> tags. is set to have bold text. This ID is assigned to the final paragraph in the body of the page. It should work in Netscape 4.

Use Stylesheet from the menu.126 Hour 9 Summary In this hour.css”> <p STYLE=”color: blue.” Quiz Test your knowledge of the material covered in this hour by answering the following questions. you can change these options by selecting Tools. How can I set my browser to ignore style sheets on the sites I visit. In Netscape 6. Q. “Controlling Styles with JavaScript. Q&A Q. In the next hour. b. but remember that the <font> tag is deprecated in HTML 4. if you want to change the font or color for all of the headings in your site. can I change it later using JavaScript? A.”> P {color: blue. c. and some of the properties you can use in a style sheet. margins. Internet Options from the menu. In Internet Explorer 5. There are also advantages to using style sheets now— for example. how to combine them with HTML documents. Yes—the DOM includes a full set of objects for working with dynamic styles. Which of the following is an example of an inline style? a. You’ve also created a simple style sheet within an HTML document. select View.} . then clicking the Accessibility button. You’ll learn about these in Hour 11. <link rel=”stylesheet” href=”styles. you’ve learned the basics of style sheets—why they’re important. Yes. Questions 1. or format them using my own style sheet? A. you can change a single line in the style sheet rather than changing hundreds of <font> tags. and other aspects of your Web pages. Once I have set up a style sheet. borders. Q.0 and later. These will give you control of fonts. and might not work with future browsers. you’ll learn more of the specific properties you can use in style sheets.0. Can’t I use the <font> tag rather than messing with style sheets? A. I just want to set a few font sizes and colors. links.

in what color will it be displayed? Add a list to the document and display it in a browser to see if you are correct.”> 3. Before you display the document. To each ID attribute used in the sidebar section c. • If you add a bulleted list using the <ul> and <li> tags to Listing 9. What would be the best place to assign styles? a. CLASS=”code”> 2. This sidebar will contain paragraphs and links. b. b. <p STYLE=”. .1. c. The correct statement is: <p 3. try the following exercises: • Add a new paragraph at the end of Listing 9.”> is an example of an inline style. <p STYLE=”color: blue.Introducing Style Sheets 127 2.1. Suppose you want to create a sidebar on the right-hand side of your Web page. To each <p> and <a> tag in the sidebar section b. b.code”> <p CLASS=”code”> <p STYLE=”class: code. Which of the following HTML tags correctly specifies a class called code? a. c. try to figure out in what color and style the new paragraph will be displayed. and assign the elements within the sidebar to that class. assign styles to the class. and assign it the menu class. The best way to assign styles would be to create a class. Exercises If you’d like to gain a bit of experience with style sheets before you move on. To a class assigned to each tag in the sidebar section 9 Answers 1. and you want them all to use a certain font size.

.

In this hour. This hour covers the following topics: • Creating styled text • Using fonts in CSS • Setting margin and border properties • Using CSS for centering • Setting link. mouse pointer. fonts. In particular. margins. and list styles • Creating and using an external style sheet . and how you can use them to control colors. you’ll delve deeper into the list of available properties and values you can use in style sheets. and other aspects of your Web pages. text formatting. and borders. you’ll learn how to set text alignment.HOUR 10 Using Style Sheet Properties You have now learned the basics of how style sheets work.

precise spacing and height. em. and bottom. but is supported by Netscape 6 and Internet Explorer 5. Values include left. Values include normal (default). Values include normal (default) or a length. middle. This value is also referred to as kerning. or a percentage. This value can be specified as an exact number in pixels or other units. white-space—normally. or nowrap to prevent word wrap. Set this property to pre to display the spaces exactly as you have included them. and justify for right-justified text. or a percentage.0 browsers. the browser displays only one space. The default value is normal. center. typically in pixels. . letter-spacing—specifies the spacing between letters. —specifies the vertical alignment of text relative to other text. You can use this property to indent the first line of a paragraph. The value can be normal (default) or a length in pixels. or ex units. a specified number of pixels. or ex units. Currently. but Netscape 6 does.5 does not support the pre value. top. super for superscript. The justify value is not supported completely by the version 4. vertical-align • Spacing CSS includes a number of properties that set the spacing and indentation of text: • • word-spacing—sets the spacing between words. • if you include two or more blank spaces. These text effects are widely supported by the most recent browsers. text-indent—specifies • the amount of indentation for a block of text. and other effects. This is known as the leading value. Alignment The CSS specification includes two properties for alignment of text: • text-align right. em or ex units. text-top. em. Internet Explorer 5. —specifies the horizontal alignment of text. • line-height—Specifies the height of text lines. sub for subscript.130 Hour 10 Creating Styled Text One of the benefits of style sheets is that you can apply some of the same techniques used in desktop publishing to the Web—aligned text. text-bottom. Values include baseline.

Decorating Text The text-decoration property allows you to set underlining and other effects. times. serif. you can also specify a list of fonts—the browser will use the first one on the list that it can support. Several different properties allow you to choose a font.” includes lists of commonly-available fonts for various computer platforms. Values include none (default). and add attributes such as bold and italics. Alternatively. set its size. but you can set fonts for certain tags or for the entire document without multiple rules. Working with Fonts The <font> tag first appeared in Netscape 2. 10 Choosing a Font The font-family property allows you to choose a font. line-through. and allows you to specify a font for text. and blink. supported by all CSS browsers. Values include none (default). you can specify a generic name. and a generic font (serif).Using Style Sheet Properties 131 Capitalization The text-transform property allows you to force text to be uppercase or lowercase. overline. the browser will use it if none of your specific choices are available. Hour 12. CSS allows you to specify fonts in a similar way. underline. but they will only work if the user has the exact font installed. it’s deprecated in HTML 4.0 versions. sans-serif. . a Macintosh font (Times). and lowercase.0. The generic fonts available include serif. If you list a generic font last. Like the <blink> tag.0. “Creating Consistent Styles. it’s inconvenient to include separate <font> tags each time you wish to change fonts. uppercase.0—more importantly. To combine the best of both of these options. While a welcome addition. the blink value is supported only by Netscape 4. For example. This property is supported by Netscape and Internet Explorer starting with the 4.} This tag lists a Windows-specific font (Times New Roman). You can specify exact font names. the following rule sets the font for paragraphs: P {font-family: “Times New Roman”. capitalize (first letter is uppercase).

xx-small. In Netscape 6. If you set a specific numeric size. medium. xx-large.} Pixel and point values are typically used to set specific font sizes. Additionally.} (percentage value. See Hour 19. and monospace. Using Bold. “Using Dynamic Fonts.} P {font-size: 10px.” for an explanation of this feature.132 Hour 10 cursive. x-large. or a generic value: small.} P {font-size: 12pt. they are actually treated as two separate properties in CSS. a percentage. a pixel value. The ultimate in font control is to specify an entire font that will be downloaded. 120% of normal size) (value in pixels) (value in points) (value in em units. A pixel value is more likely to display in the same size on different computers. large. Italics. although this will vary based on monitor resolution. The following are examples of font size rules: • • • • P {font-size: 120%. 120% of normal size) P {font-size: 1. Different browsers might use different fonts to represent the generic fonts. Its values can be a number. you can choose your own fonts for each of the generic types.2em. Setting Font Size The font-size property controls the size of letters. fantasy. Notice that you should enclose font names that include spaces within quotation marks. you can use the values smaller or larger to set the size of an element relative to its parent element. in fact. you can set it to a percentage. x-small. Here are three properties that affect the appearance of the text: . or a point value. and Small Capitals While you might think of bold and italics as similar ways to emphasize text.

or a numeric weight from 100 to 900 in increments of 100. Values include none. right. Can be set to auto. left. float—Allows the text to flow around an element. lighter. 10 Properties for Margins The following properties affect margins. The default value. Values include left. with slightly larger capitals for uppercase letters. This is particularly useful with images or tables. or none. lets the browser set the margins. that the text should stop flowing around a floating image or element. height—Specifies the height of an element. such as an image. • • • • margin—Allows you to specify a single value for all four of the margins. font-variant Setting Margins and Borders CSS includes a number of properties you can use to set margins and borders. and to center or indent objects within a Web page. Can be set to auto. You can specify the margins as an exact number or as a percentage of the page’s width. borders. but you can be sure normal or bold will always work. • clear—Specifies . right. or both. or four values separated by spaces for the top. width—Specifies the width of an element. bold. bottom. margin-left. The effect is similar to the align=left or align=right attributes for the <img> tag. or a numeric value. margin-bottom. a percentage. bolder. • can be set to normal (the default). You can use these properties to gain more control over text layout. or oblique (slanted) font-weight can be set to normal (the default). margin-right—These properties specify the margins of the element. right. a percentage. Whether some of these values are supported could depend on the fonts the user has installed.Using Style Sheet Properties 133 • • font-style can be set to normal (the default). or small-caps to display the text in small capital letters. auto. and the width and height of elements on the Web page: • margin-top. italic. or a numeric value. and left values.

groove. border-color—Specifies border-style—Sets the color for the border. padding—Specifies the amount of space between the border and the content of the element. This property’s value specifies four coordinates to form a rectangle. displays scroll bars to allow the user to view all of the content. dashed. 10px. bottom-border-width. • • • padding-left. inset. separated by spaces. hides the content outside the box. lets the browser decide how to handle overflow. width—Allow • • left-border-width. and outset. padding-right.134 Hour 10 Border Properties The following properties allow you to set up the border for an element: • border-width—Allows you to specify a single value for the width of the border. dotted. padding-bottom—Allow you to set the four padding values individually. and left values. Additionally. right. right. solid. or four separate values for top. or four values for the top. double. and left borders. ridge. The following example sets the clipping area of paragraphs at ten pixels in from the paragraph’s edge on all sides: P {clip:rect (10px. its content will not all fit in the available area. bottom. } The four values for the rectangle specify the top. you can use the clip property to specify a different area for clipping than the default. Scroll bars are usually displayed. bottom. You can specify one color value for all four borders. bottom. right. the style of the border. or four values for top. Values include none. The overflow property allows you to specify what happens to the content outside this area: • • • • overflow:visible overflow:hidden overflow:scroll overflow:auto shows the content outside the box. 10px. . right. This can be one value for all four sides. padding-top. You can also specify four values for the top. and left borders. and left borders. right-border-width. and left borders. You can specify one value for all four borders. top-border- you to set the four side borders individually. Overflow and Clipping Sometimes. right. bottom. separated by spaces. when you’ve defined margins or a size for an object. bottom. 10px).

Using Style Sheet Properties 135 Centering with CSS When Netscape introduced the <center> tag. the text-align attribute can be set to center. defines styles for a link when the mouse pointer is over it. defines styles for links that have been previously visited. but some objected as it’s a tag for defining presentation rather than content. it’s deprecated in HTML 4. defines styles for links when they are being clicked. red when clicked. and to control the appearance of items within lists. a:hover a:active a:visited For example. While <center> was added to the HTML specification.0. set the margin-left and margin-right values both to auto. or special selectors. to control the mouse pointer’s appearance.} a:hover {color: blue. These methods of centering aren’t supported consistently in all but the most recent browsers. • For other elements. Setting Link Styles Links are defined with the <a> tag. 10 Setting Other Style Attributes You can also use CSS styles to set the styles for links. background-color: yellow. The CSS standard includes four pseudo-classes. You might have noticed that there isn’t an obvious replacement for the <center> tag in the CSS properties. this style sheet makes links blue by default. There are actually two ways to center in CSS: • For text elements. Web designers rejoiced as it created an easy way to center anything. but not all <a> tags are links. One alternative for now is to simply use <div align=”center”> instead of the <center> tag. that you can use to define styles for links in various states: • • • • a:link defines default styles for links.} a:active {color: red. and highlights them with a yellow background when the mouse pointer hovers over them: <style> a:link {color: blue. } </style> .

and are various cursors used for resizing objects. The following values are available: • • • • • • • • • is the default setting.} </style> The cursor styles are part of the CSS2 specification and are supported by Netscape 6. such as the <ol> or <ul> tag. usually an arrow. depending on the compass e-resize. se-resize. For example. Setting List Styles The following style attributes can be applied to lists. However.0 and later. these classes are supported only by Netscape 5. to set the style of list items: . When you set this attribute for an element or class. default pointer move text wait help is the pointer for moving objects. is the default cursor for the operating system. the cursor will change to the shape you specified when the mouse pointer is over that element. auto none hides the mouse pointer. nw-resize direction. usually a hand.136 Hour 10 Using the hover pseudo-class is a great way to create rollover effects without using JavaScript. typically a watch or hourglass.0 and later and Internet Explorer 4. is the pointer for links.0 and later and Internet Explorer 4. is a help cursor. n-resize. Setting Cursor Styles The cursor attribute allows you to set the style of the mouse cursor. this style sheet changes the pointer to a question mark when it moves over any image: <style> img {cursor: help. w-resize. typically a question mark. is a waiting cursor. s-resize. ne-resize. is a text cursor.0 and later. and lets the browser change the mouse pointer according to standard user interface rules. sw-resize.

list-style-image—Specifies • • the URL of an image to be used as the list item marker. circle. You’ll find these listed in Appendix A. “Other JavaScript and DHTML Resources. or outside to place all rows of text to the right of the marker. This overrides the list-style-type property. and upper-alpha for ordered lists. you’ll probably find it useful to work on the style document and the HTML concurrently until you’ve created the look you’re after. Values include inside to place lower rows of text and the marker at the same column. lower-alpha. To use it. . and square for unordered lists. list-style—Provides a quick way of setting the previous three list properties. upper-roman. You will link an HTML document to this style sheet in the next section.css or the name of your choice. In practice. lower-roman. and inside or outside for positioning. or decimal. Workshop: Creating a Styled Document To practice using the style sheet properties you’ve learned in this hour and the previous hour.Using Style Sheet Properties 137 • list-style-type —Sets the type of marker displayed before the list item. Rather than create style sheets manually. Values include the various marker types. and also makes it easy to link more than one document to the same style sheet. Listing 10.1 shows the CSS file. the position of the marker relative to the text. you can create a style sheet document that will be used with an HTML document. This keeps your HTML document short. Values include disc. you can use a number of tools to automate the process. a URL for the image. Items within HTML lists have this property set by default. list-style-position—Specifies • 10 The list styles apply to items with the display property value list-item. save it as style.” Creating the Style Sheet As a first step. you can create a styled document using an external style sheet.

These values will be inherited by all elements in the body unless we specify otherwise.com/dhtml/. They are not required in a CSS file. LISTING 10. sans-serif.} UL {margin-left: 20%.} H1 {font-size: 300%.} This style sheet sets the following properties: • The body of the document is set to use a sans-serif font. • Headings using the <h1> tag are set to be three times the normal size. text-align: center. text-indent: 3%. margin-right: 20%. with a 12-point size. Helvetica. margin-right: 10%.starlingtech. font-size: 12pt. • Paragraphs using the <p> tag are set to have left and right margins of 10%. • Elements in bulleted lists using the <li> tag are set to have a top margin of 10 pixels. providing a space between list items. and capitalized. • Italic text is set to be dark violet in color. and could cause an error if included. rightjustified.} B {color: red.138 Hour 10 The style sheet and HTML files for this example are available from this book’s Web site: http://www.} P {margin-left: 10%. • Bold text is set to be red in color.} LI {margin-top: 10px. • Bulleted lists using the <ul> tag are set to have left and right margins of 20%. Notice that the <style> tags aren’t included in the style sheet document. . text-transform: capitalize.1 The External Style Sheet body {font-family: Arial. text-align: justify. and indented 3% at the first line. centered.} I {color: DarkViolet.

css”> Listing 10. LISTING 10. tag is in lowercase. Colors have been set for <b>bold</b> and <i>italic</i> elements within paragraphs.Using Style Sheet Properties 139 Creating the HTML Document Now you can create an HTML document that uses the external style sheet you created. and the text is right-justified. . It is displayed in a 12 point sans-serif font. Each word in the heading has been capitalized by the style sheet.1 shows the styled document as displayed in Netscape 6. linking to the style sheet: <link rel=”stylesheet” href=”style. tags nested within it. It should display in a nearly identical way in Internet Explorer and other CSS-compliant browsers.h1&gt. the text in this bulleted list is displayed in that font. tag to add a bit of space in between each item in this bulleted list.</li> <li>Since the <b>font-family</b> value was set for the body tag. </p> <ul> <li>All of this was accomplished using an external style sheet. The right and left margins are set at 10%. The most important part will be to include the <link> tag in your document. with a font size 300% of the normal size. </li> <li>The list has a margin of 20% on the left and right. Be sure that you save it in the same directory as the style sheet.2 shows a complete example HTML document that links to this style sheet. Paragraphs are also set to be indented. </p> <p>The H1 heading above has been set to a sans-serif font. and that the <link> statement’s filename matches the name you used to save the style sheet. and are thus inherited by the &lt. even though the actual &lt. These were set for the &lt.</li> </p> </body> </html> 10 Figure 10.li&gt.2 The HTML Document for the Style Sheet Example <html> <head> <title>Style Sheet Example</title> <link rel=”stylesheet” href=”style.li&gt.</li> <li>We have added a top margin for the &lt. tag.ul&gt. It is displayed centered.css”> </head> <body> <h1>style sheet example</h1> <p>This is a standard paragraph of text.

140 Hour 10 FIGURE 10. What is a good font size for readable text on my page? A. and some users might have . you’ll learn how you can dynamically control these properties using JavaScript. Summary In this hour and the previous hour.” includes a list of these fonts. While a size of 10–12 points is typical for printed pages. “Creating Consistent Styles. Hour 12. you don’t really know what text size will be displayed on each user’s monitor. position. you’ve learned the properties and values you can use in CSS style sheets. In the next hour. Q&A Q. While you can never be sure which fonts are installed by your users. You should now know how to control color. Q. font. and other attributes using style sheets. How do I know which fonts each user has installed? Are there any fonts that are safe to use? A. creating useful and sometimes dramatic effects.1 Netscape displays the styled document. there are certain fonts included with the Windows and Macintosh operating systems that you can expect to find on most computers.

color: red.} <H1> {font-size: 24px. 3. paragraph-spacing word-spacing margin-top 2. c. What is the difference between italic and oblique text styles? A. Which of the following is the correct rule to set H1 headings to have a font size of 24 pixels and a color of red? a. The correct rule is H1 {font-size: 24px. and oblique text is a slanted version of the standard font produced by the computer. a. . While these are both basically slanted text.}. and percentages of this size for other elements. b. italics usually refers to a separate font that has been designed with a slant. color: red. H1 {font-size: 24px. and instead use the default size for the body. 2. and choice C specifies points (24pt) instead of pixels (24px).Using Style Sheet Properties 141 different ideas than you of what’s readable. Which of the following could be used to center an image within the page? text-align margin-auto margin-left and margin-right 3. 10 Questions 1. Choice B incorrectly uses angle brackets around <H1>. The margin-top property could be used to add space between paragraphs. b. c. c.} H1 {font-size: 24pt. The text-align property only works on text elements. c. Quiz Test your knowledge of the material covered in this hour by answering the following questions. It’s best to avoid setting an exact size.} Answers 1. c. b. Setting margin-left and margin-right to auto is one way to center an image. a. color: red. Q. Which of the following properties could you use to control the amount of space between paragraphs in a document? a. such as paragraphs. color: red.

fineprint class that has smaller than normal text and is displayed in italics. • In the style sheet in Listing 10. try the following exercises: • Create another HTML document that links to the styles. Assign one of the paragraphs in Listing 10.1.css style sheet in Listing 10. . Observe how the style rules format your document. create a .2 to this class.1.142 Hour 10 Exercises If you’d like to gain a bit more experience with style sheets before you move on to the next hour.

HOUR 11 Controlling Styles with JavaScript You have now learned many properties and values you can use to format pages using CSS. styles. This hour covers the following topics: • Formatting properties for dynamic styles • Controlling colors dynamically • Changing text properties dynamically • Dynamic styles in action . The DOM stores all of these values. fonts. and other aspects of a document—anything that you can control with style sheets. you’ll learn how you can use JavaScript and the DOM’s style objects to change the colors. and you can use JavaScript to manipulate them dynamically. In this hour.

” includes an example using visibility properties.leftBorderWidth margin-left font-family left-border-width One exception to this pattern is the float property. In this hour. Here are a few examples: • • • • text-align becomes style.marginLeft becomes style. In this case.” shows an example of the positioning properties. Translating Property Names The DOM includes objects that correspond with all of the style properties you learned about in the previous hours. You’ve used some style properties already.144 Hour 11 Dynamic Styles In the previous hours of this book you’ve learned two things: how DHTML and the DOM can make pages dynamically.style. and how you can use CSS to control the formatting of your pages. the property name (color) is the same as the style property name. This change is because float is a reserved word in JavaScript. However. . Hour 5. the DOM object has a slightly different name—it includes the same words. you’ll learn to combine these two ideas and create documents that can be restyled dynamically.fontFamily becomes style. h. These are stored under the style object for each HTML element. “Creating Positionable Elements (Layers).color=”red”. but with no spaces and with capitals on all but the first word. suppose you have defined a heading with this HTML: <h1 ID=”head1”>This is a Heading</h1> You can use the following JavaScript statements to change the color of this heading: h=document. Its corresponding JavaScript property name is style.textAlign becomes style.getElementById(“head1”). For example. “Understanding the DOM.cssFloat. with any property name that includes two or more words. and Hour 6.

getElementById(“head1”). For each one. The following are the color and background properties available from the DOM: • • • • • • color—The text color for an element background scroll setting background color for an element or document background image for an element or document offset of the background image position tile setting for the background image backgroundAttachment—The backgroundColor—The backgroundImage—The backgroundPosition—The backgroundRepeat—The These properties are the same as the style properties. formatted as DOM properties. } } This example uses the document. and changes its color to the value specified in the function’s parameter. it checks for a CLASS attribute value of para. You can also create a function to change the color for more than one object: function PColor(c) { paras=document. . These properties are explained in detail in Hour 9. “Introducing Style Sheets.color=c.length. } This simply finds the object for the heading. i++) { if (paras[i].” 11 Using Color Properties One easy way to manipulate colors is to create a function to change the color of an object.className==”para”) paras[i]. i<paras. This function changes the color of the heading with the ID attribute head1: function HColor(c) { h=document.getElementsByTagName(“P”).style. h. and if this value is found.color=c. it changes the color of the object to the value specified in the function’s parameter.Controlling Styles with JavaScript 145 Working with Colors As one example of using style properties in JavaScript. for (i=0. you can change colors dynamically in a document.style.getElementsByTagName method to get an array of objects for all of the paragraphs in the document.

be sure to use double quotes around the entire href attribute of the <a> tag. Listing 11.length.color=c. Changing Colors Dynamically You can now create a simple HTML document that includes the functions you created and a variety of links that test the dynamic color functions. } function PColor(c) { paras=document.1 shows the complete document. For example.”>blue</a> When using javascript: links.className==”para”) paras[i]. i++) { if (paras[i].style. the following <a> tag defines a link that sets the heading’s color to red: <a href=”javascript:HColor(‘red’). for (i=0. and single quotes for any parameters within the JavaScript statement itself. i<paras.getElementById(“head1”).146 Hour 11 Calling the Functions Now that you have created two color-changing functions.style.getElementsByTagName(“P”).1 The Complete Color Changing Example <html> <head> <title>Dynamic Colors</title> <script language=”JavaScript”> function HColor(c) { h=document.”>red</a> The following example changes the color of the paragraphs to blue: <a href=”javascript:PColor(‘blue’).color=c. one simple way is to use javascript: links. you can easily call them from JavaScript. LISTING 11. } } </script> </head> <body> <h1 ID=”head1”>Dynamic Colors</h1> <p CLASS=”para”>This document inclues a short script that . While you could use event handlers to do this. h.

you can change some of the same properties in the 4.0 or later. These paragraphs also include links to manipulate the various parts of the document. or <a href=”javascript:HColor(‘black’).”>blue</a>. This particular paragraph doesn’t change color since it doesn’t have a CLASS attribute. • The PColor function changes the color of all paragraphs with the CLASS attribute para. • The first two <p> tags define two paragraphs in the para class. • The <h1> tag defines a heading with the head1 identifier. but isn’t too dramatic. save it as an HTML document and load it into a browser. <a href=”javascript:PColor(‘blue’)”>blue</a>. <a href=”javascript:HColor(‘blue’). “Creating Drop-Down Menus.</p> </body> </html> To use this example.” and to create blinking and fading text in Hour 15.”>red</a>. or <a href=”javascript:PColor(‘green’)”>green</a>.Controlling Styles with JavaScript 147 LISTING 11. “Creating DHTML Text Effects. While this example requires Internet Explorer 5.1 continued uses DHTML to change the colors of objects by manipulating style properties.</p> <p CLASS=”para”>You can change this page’s heading to <a href=”javascript:HColor(‘red’).”>black</a>.0 or later or Netscape 6.1. You can also change the color of these two paragraphs of text to <a href=”javascript:PColor(‘red’)”>red</a>.” 11 This example quickly illustrates how the color properties work.0 browsers using the techniques you’ll learn in Hour 17. “Dealing with Browser Differences. Internet Explorer’s display of this example is shown in Figure 11. </p> <p>The paragraphs can all change color at once because they are in the same class.” Here is a breakdown of how this listing works: • The HColor function changes the color of the heading with the ID head1. . The same concept is used to create rollovers in Hour 13.

You can manipulate any style property in a script. For example. remember to translate the names: text-align becomes textAlign. 200%) in quotation marks to avoid creating JavaScript errors. Also.getElementById(“para1”).style.148 Hour 11 FIGURE 11.starlingtech. Here’s the URL: http://www.style. 12pt. p. As usual. and other text styles dynamically.fontSize=”16px”.1 Internet Explorer displays the dynamic colors example. and so on. Changing Text Styles Dynamically Colors aren’t the only thing you can change dynamically. Suppose you have defined a paragraph with the ID para1 like this: <p ID=”para1”>This is a paragraph. p. . As with color properties.</p> The following statements change the alignment and font for the paragraph: p=document. alignment. you can change fonts.textAlign=”center”.com/dhtml/. you can download this hour’s examples from this book’s Web site rather than typing them.style. you should enclose any value that includes a unit (for example.fontFamily=”sans-serif”. 16px. p.

getElementById(id).style[p]=v. obj=document. } ID This function accepts three parameters: id.style. LISTING 11.Controlling Styles with JavaScript 149 Workshop: Using Dynamic Styles As a more sophisticated example of dynamic styles.getElementById) return. They simply indicate a child object: obj.style[“color”] would be the same as obj. Creating the Function Rather than working with any specific object.p. Creating the HTML Document You can now create an HTML document that includes the function you created and a variety of links to test the function. This provides an easy way for you to experiment with different property values and examine how they are displayed in the browser. 11 Notice the brackets in the statement obj. } </script> </head> . p. then sets the property p for that object to the value v.getElementById(id). it’s much simpler than the functions you created earlier in this hour: function Change(id.color.style[p]=v. Listing 11.style[p]=v. obj. you can create a function that will change any property of any object.v) { if (!document. It finds the object with the specified attribute.v) { if (!document.2 shows the complete HTML document. obj. Using the brackets allows you to use a variable for the property name. Sound complicated? Actually.getElementById) return. and v.p.2 An HTML Document Including Dynamic Style Functions <html> <head> <title>Dynamic Styles</title> <script language=”JavaScript”> function Change(id. you can create an HTML document with a simple function that can easily change any style property. obj=document.

’fontWeight’.”> serif</a>. or <a href=”javascript:Change(‘para2’.”>bolder</a>.’sans-serif’).’textAlign’.’monospace’). </p> <p ID=”para2”> This paragraph’s alignment can be changed to <a href=”javascript:Change(‘para2’.’fontWeight’.’fontWeight’. <a href=”javascript:Change(‘para2’.’fontSize’.”>large</a>.’left’).’fontFamily’.’fantasy’).’lighter’). For example.”> sans-serif</a>. or <a href=”javascript:Change(‘para1’.”>normal</a>. <a href=”javascript:Change(‘head1’. Notice that bold is the default setting for a heading. </p> </body> </html> This listing includes the Change function you created.”>normal</a>. <a href=”javascript:Change(‘para1’. and include links that use the javascript: format to change various attributes.”>justify</a>.”>left</a>. The paragraphs and heading within the document have ID attributes.’center’).’fontFamily’.’fontWeight’.’right’).2 continued <body> <h1 ID=”head1”>Dynamic Styles</h1> <p ID=”para1”> This document includes a simple function that can change any style property.”> fantasy</a>.’fontSize’.’50%’).’textAlign’. <a href=”javascript:Change(‘para2’.’fontSize’.’normal’).’100%’).’textAlign’.’textAlign’. <a href=”javascript:Change(‘para2’. or <a href=”javascript:Change(‘head1’.’bold’).”>center</a>. </p> <p>The weight of the heading at the top of the page can be set to <a href=”javascript:Change(‘head1’. Try the links in different browsers and notice the different choice of fonts.’serif’).”>right</a>.’fontFamily’.’cursive’).’fontFamily’.”>lighter</a>. and the <b>lighter</b> value is the same as <b>normal</b> in the current versions of Netscape and Internet Explorer.”>small</a>. . <a href=”javascript:Change(‘para2’. <a href=”javascript:Change(‘para2’.”> cursive</a>. <a href=”javascript:Change(‘head1’.’bolder’).150 Hour 11 LISTING 11.”>bold</a>.’fontFamily’.’justify’).”> monospace</a>.’200%’). You can also change the font of this paragraph to <a href=”javascript:Change(‘para2’. or <a href=”javascript:Change(‘para2’. you can change this paragraph’s font size to <a href=”javascript:Change(‘para1’.

. In the next hour. FIGURE 11. You’ll also learn how to use JavaScript to enable and disable style sheets. and monospace fonts are very similar. Q&A Q. and other properties of your document. Why are the fonts different between Netscape and Internet Explorer? Neither cursive font is actually cursive. browser-friendly Web pages. Fortunately. the basic sans-serif. A. Combined with CSS. colors. The rules for CSS don’t say exactly what these generic fonts should look like.Controlling Styles with JavaScript 151 To try this example. serif. so don’t expect consistency.0 or later or Internet Explorer 5. you’ve learned how you can use JavaScript and the DOM to dynamically change text styles. and Netscape’s fantasy font looks normal.2 shows Netscape’s display of the document after a few changes have been made.2 Netscape displays the dynamic styles example. You’ll use these properties to create several practical examples in the remaining hours of this book.0 or later. This example requires Netscape 6. you’ll take a final look at CSS style sheets and learn the best ways to use them to create readable. 11 Summary In this hour. these give you sophisticated control of how users see your pages. Figure 11. save it as an HTML document and load it into a browser.

You’ll use them throughout the rest of this book.style. Child objects and siblings 3. Quiz Test your knowledge of the material covered in this hour by answering the following questions. firstline. Questions 1. You should test on several current browsers to be sure your styles have the effect you intended. Which of the following is the correct statement to change the firstline object’s font size to 20 pixels? a.margin-right 2. c. starting with the drop-down menu application in Hour 13.marginRight firstline. b.style. . Are there any practical reasons to use dynamic styles? A. c. Are dynamic styles supported by all browsers? A. b. firstline.style. style properties are an important part of many DHTML applications. firstline. Text alignment c.0 and later and Internet Explorer 4. Which of the following is the correct way of referring to the margin-right style property for the firstline object within a script? a.152 Hour 11 Q. Netscape 4.style. Which of the following properties are not included under the style object? a. Aside from special effects. but no browser’s support for style properties is perfect.fontsize=20.fontSize=”20px”. Q. Visibility b. firstline.marginRight firstline.fontSize=20px.0 and later support the styles discussed in this chapter.

you must use quotation marks around it. The correct statement is firstline.Controlling Styles with JavaScript 153 Answers 1. 3. a. and any other properties you’re curious about.style. Since the pixel value isn’t an integer.fontSize=”20px”. 11 . and notice any differences in the way the properties are interpreted. firstline.style. text decoration. siblings. Include links to change font style (normal or italic). Exercises If you’d like further practice using dynamic styles before you move on to the next hour.2. They are properties of each node itself. • Try your modified version of Listing 11. try the following exercises: • Add a couple of paragraphs to Listing 11. 2. b.marginRight is the correct property. The node relationship properties (child objects. and so on) are not stored under the style object.2 in at least two different browsers. c.

.

In this hour. you’ll learn some guidelines for using style sheets consistently and tastefully. You’ll also learn how you can use JavaScript to give users a choice of different styles.HOUR 12 Creating Consistent Styles You’ve now learned just about everything that can be done with style sheets. This hour covers the following topics: • Using style sheets effectively • Choosing appropriate colors • Selecting fonts for Web pages • Choosing margin and border sizes • Supporting older browsers • Creating multiple-choice styles . With powerful features like these. you should make sure you are not creating styles that will annoy your users.

• Don’t hide your links from visitors. screen resolution. it’s easier than ever to create a page that annoys or confuses visitors.156 Hour 12 Using Restraint The history of the Web is filled with events that put powerful tools in the hands of Web designers—and often they fell into the wrong hands. and your site might need to break a rule or two to look and work its best. and a good design will work with a wide range of settings. • Don’t tell your visitors that they need a certain browser. Just make sure your audience is impressed by the styles and features you use. and are clearly labeled with text. and dynamic features. rather than annoyed or confused. As Web pages and sites become more complex. Don’t make users scan the mouse around the screen or decipher bizarre icons just to see what content is available on the site. or use graphic links or other navigation methods—but when you do. it’s important to keep them readable and navigable. make sure you’re not increasing the time it takes visitors to load your site too much. Test your pages using a slow Internet connection and watch for long pauses. make sure the links are immediately identifiable as links. but you still can use them to create poorly designed pages. Of course. there are exceptions to every rule. you’ll learn some guidelines to help you create pages that fit three important criteria: • Readability and Usability • Consistency between browsers that support CSS • Usability in older. . styles. Style sheets are a step in the right direction. Netscape’s <blink> tag. and clearly state where they go. When you start adding CSS and DHTML to your pages. Nobody will change these settings just for your site. or video mode to fully appreciate your site. JavaScript scrolling messages. Styles that would fit perfectly well in a site that reviews video games would look garish and overdone on a site that offers financial reports for stockholders. In this hour. non-CSS browsers Usability Tips Web usability is a relatively new concept. • Make sure your most important links aren’t buried in the site design. Here are a few tips to avoid common usability mistakes: • Know your audience. but an important one. You can use CSS to make links take any appearance. • When you add graphics. and the <font> tag resulted in an epidemic of bad Web pages.

If your site is graphically oriented and only has a few words of text per page. Text and Background Colors The text and background colors you choose greatly affect readability. yellow on black would work just fine. . and there was no way for Web designers to use alternate colors. If you’re careful. you probably automatically think of blue text as a link. you’ve probably run into a few Web pages with such frightening color choices you’ve wished for black on gray. Black and white aren’t the only choices. Choosing Colors Color is a vital part of Web pages—anyone who was around when the first browsers came out knows that they displayed black text on a gray background by default. and might fit right in with the design of the site you’re working on. Your users think the same way. or with monitors that aren’t as clear as yours. but there’s a reason the vast majority of literature is printed in black on white: it’s easier to read. Of course. If you follow a few simple guidelines. you can avoid giving users headaches with your color choices. 12 Link Colors If you’ve spent much time browsing the Web. there are a number of equally readable choices: black on light blue. and neither is the same as the regular text on your page. That doesn’t mean you should avoid changing the link colors entirely. be sure you are consistent throughout your site. or even white on dark blue. there are exceptions to any rule. Of course.Creating Consistent Styles 157 To know your audience better. and purple text as a link you’ve visited. talk to them. dark blue on light gray. but if you do. Yellow text on a black background might look cool. and if you’ve changed the color of links you can create confusion. The Web has come a long way since then. Be sure both visited and non-visited links are different colors. let users view the new version and give you their feedback before you replace the old version. Just keep readability in mind when you use colors. If you have to squint to read the text on your page. When you redesign a site. imagine how it must look for users with imperfect vision.

they can make reading very difficult if you’re not careful. Background Images If reading text displayed over a bright background color is hard. Another way is to use a background that doesn’t cover the entire page— use CSS positioning or a table to place your text in areas where the background is one solid color. Choosing Fonts The font options of CSS bring typography to the Web. don’t forget that with power comes responsibility—choosing the wrong fonts is another way to make a page virtually unreadable. If you list a Windows font. watermark-like company logo. there are three big mistakes you can make with your font choices: • Choosing a difficult to read font—cursive fonts. or remove underlines from links. imagine trying to read text displayed over a brightly colored. you also can create confusion if you underline other text. and calligraphy are common examples • Choosing a specific font that might not be available on all browsers or computers • Using several different fonts in the same page. However. handwriting-style fonts. a Macintosh font. One way to avoid problems with background images is to use a very simple background: a texture with mostly a single color. In general. While background images are a great way to give a page a unique style. you can be sure all users will see your page the way you intended. detailed background image. and you can now choose fonts to match the design of your site. especially fonts that don’t match (serif and sans-serif fonts. Avoid these changes whenever possible. or a solid color with a very faint. for example) Common Font Choices One way to avoid running into trouble with users who don’t have the same fonts installed as you is to use a list of commonly available fonts. and a generic font.158 Hour 12 Since most browsers display links as underlined text. .

• Arial. While users can always add or remove fonts. Windows Fonts The following fonts are installed by default in Windows 95 and later versions: • Arial (sans-serif) • MS Sans Serif (sans-serif) • Copperplate Gothic Bold (serif) • Copperplate Gothic Light (serif) • Courier New (monospace) • Terminal (monospace) • Times New Roman (serif) 12 Macintosh Fonts The following fonts are installed by default in Mac OS 7 and later versions: • Chicago (sans-serif) • Courier (monospace) • Geneva (sans-serif) • Helvetica (sans-serif) • Monaco (monospace) . serif • Times New Roman. and generic CSS font name that are roughly equivalent. serif • Courier New. Times. you might find it useful to know which fonts are commonly installed on Windows and Macintosh systems. Geneva.Creating Consistent Styles 159 Here are a few basic font lists you can use. Macintosh font name. monospace Available Windows and Macintosh Fonts When choosing fonts. Courier. the fonts in the lists below are installed by default and generally are available. Don’t forget to enclose any font name that includes spaces in quotation marks when you use it from CSS or JavaScript. Each includes a Windows font name. Helvetica. sans-serif • MS Sans Serif. sans-serif • MS Serif. New York.

While anywhere from 10 to 14 point sizes will be readable. you should allow your page to be resized whenever possible. but not least. and different users will prefer different sizes. Supporting Older Browsers Last. If you set an exact size. This means avoiding using exact pixel amounts in margin. While CSS is designed to avoid this problem. Use relative units to specify font sizes. border. . you still can cause problems through misuse of CSS. Margins and Borders Many Web designers have puzzled over the issue of what size of monitor to design for. users who have carefully set their browsers’ font size to their liking will be surprised.” for a discussion of the different units available. While these guidelines will help with graphics and other elements that can’t be resized. While 640×480 resolution was common a couple of years ago. and width settings.160 Hour 12 • New York (serif) • Palatino (serif) • Times (serif) Choosing Font Sizes You also should be careful when choosing font sizes. but users with higher-resolution screens will be able to take advantage of the space they have available and stretch your page to fit their browser width. you don’t create a page design that requires a CSS browser to be readable at all. “Introducing Style Sheets. and use percentage sizes to set the size of any headings. and ex units. not only will users with lower-resolution screen be able to read your page. 800×600 is now the most popular size and higher resolutions are much more commonplace. you should be sure that as you add CSS features to your pages. These include percentages. and in the sizes for table columns. If you avoid exact sizes. fine print. Instead. em units. The best advice about font sizes is not to set one. or other special text. This way the fonts can be resized easily by the user. let the default size be used for body text. See Hour 9. you should keep in mind that the actual size will depend on the browser and monitor in use.

and use DHTML to enable only one of them based on the user’s preference.} LI {margin-top: 10px.} UL {margin-left: 20%. LISTING 12.Creating Consistent Styles 161 For example. the lines of text are all displayed one at a time.} . The style sheets will be external.1 shows the first style sheet. It isn’t just older browsers you should worry about—some users with current browsers might have style sheets turned off. Remember that external style sheets do not require the <style> tags. they’ll be readable whether your styles are used or not. text-indent: 3%. sans-serif. text-transform: capitalize. or specify their own custom style sheet. This sets fonts.} B {color: red. If you design your pages carefully. margin-right: 10%. Save this document as style1.} H1 {font-size: 300%. Workshop: Creating Multiple-Choice Styles One way to avoid alienating users with your bold design choices is to give the user a choice. Helvetica. or in your normal browser with style sheets turned off. Creating the First Style Sheet The first step in creating multiple-choice styles is to create the first style sheet. You can create a document with two or more style sheets defined. you can use CSS positioning to overlap several identical lines of text. margins.} I {color: DarkViolet.1 The First Style Sheet 12 body {font-family: Arial. text-align: center. margin-right: 20%.css or a name of your choice. text-align: justify. you should always test your pages that use CSS in an older browser that doesn’t support CSS. and fonts for several HTML elements. so you should save them as css files. font-size: 12pt. To avoid problems like this. creating a nifty shadow effect—but when you view the page in a non-CSS browser. Listing 12.} P {margin-left: 10%.

you’ll need another style sheet that provides a second choice. “Times New Roman”. However. margin-right: 30%. text-transform: uppercase. text-indent: 0%.} I {color: red. sans-serif. You later can enable the style sheet using JavaScript. shown in Listing 12.2 The Second Style Sheet body {font-family: Times. . You can use an attribute of the <link> tag to accomplish this: <link rel=”stylesheet” href=”style2.css. Creating the Function Last. margin-right: 20%.css” DISABLED> This tag uses the DISABLED attribute of the <link> tag to define a style sheet that will not be used by default. and the final script you create will work in both Netscape 6 and Internet Explorer 5 and later.starlingtech. background-color: yellow. The current version of Netscape 6 does not support the DISABLED attribute.} UL {margin-left: 30%. This style sheet will be disabled by default in our example. but not least.com/dhtml/.2.} Save this style sheet as style2.} B {color: black.} P {margin-left: 20%. or a name of your choice. background-color: aqua. Creating the Second Style Sheet Next. text-align: left. uses some more extreme style choices and probably isn’t ideal for all users.} H1 {font-size: 200%. This style sheet. text-align: right. you need a way to switch style sheets dynamically. you still can disable a style sheet using JavaScript. you can download the CSS and HTML files for this example from this book’s Web site: http://www. LISTING 12.162 Hour 12 As usual.} LI {margin-top: 20px. font-size: 14pt.

This prevents errors from occurring on browsers that do not support DHTML.disabled=!enable. and enable. the number of the stylesheet to enable (0 or 1).3 shows the complete HTML document.3 The HTML Document for the Multiple Choice Styles Example 12 <html> <head> <title>Style Sheet Example</title> <link rel=”stylesheet” href=”style1. If enable is true. . Listing 12. The disabled property is a bit confusing. links[n]. and assigns the disabled property of the other style sheet to true. if enabled is false.disabled=!enable. links=document.getElementsByTagName) return.css”> <link rel=”stylesheet” href=”style2.disabled=true. It assigns the link specified in the n parameter’s disabled property to the opposite of the enable parameter.getElementsByTagName property. This function first checks for the document. links=document. links[n]. both are disabled.getElementsByTagName) return. Next.getElementsByTagName(“link”). Creating the HTML Document Finally. LISTING 12.enable) { if (!document. you can use a simple DHTML function: function Style(n. since it will be used later.css” DISABLED> <script language=”javascript”> function Style(n.enable) { if (!document. links[1-n]. the function uses the getElementsByTagName method to store an array of <link> objects for the document in the links variable.getElementsByTagName(“link”).Creating Consistent Styles 163 To enable and disable styles. some text to serve as an example. you can create an HTML document that includes your Style function. } The Style function uses two parameters: n. This allows you to provide the user with the option of turning off style sheets altogether. one of the style sheets is enabled. and links to allow the style sheet to be changed. a flag to indicate whether to enable the style sheet. Remember that a value of true disables the style sheet and a value of false enables the style sheet.

This paragraph includes some text in <b>bold</b> and <i>italics</i>. be sure that the href attributes of the <link> tags match the filenames you used for the two style sheets. and other attributes depend on the style sheet you select.disabled=true. • The list items in the <ul> section define three links that call the Style function: one for the first style sheet.3 continued links[1-n]. one for the second. and a third to turn off both style sheets.true). it will be displayed using the first style sheet. When you first load the document.”>Style sheet # 1</a></li> <li><a href=”javascript:Style(1.true). • The Style function is defined in the <script> section. without changing any HTML.”>Style sheet # 2</a></li> <li><a href=”javascript:Style(0.</p> </body> </html> To test this document. and save this document in the same directory. margins.1 shows Internet Explorer’s display of this example with the default style. fonts. • The last line in the <script> section calls the Style function to enable the first style sheet and disable the second when the page is displayed. • The rest of the document includes a heading and paragraphs that will be styled according to the style sheet you select. </script> </head> <body> <h1>multiple-choice styles</h1> <p>This is a standard paragraph of text. Here is a breakdown of the components of this HTML document: • The <link> tags include both external style sheets. Its font. .true). } Style(0. You can edit the style sheets to style this document in two different ways. Figure 12. </p> <p>You can select one of three styles for this document: </p> <ul> <li><a href=”javascript:Style(0.164 Hour 12 LISTING 12. The second style sheet is disabled by default. justification.false).”>No style sheet</a></li> </ul> <p>These links call a short JavaScript function that enables one of this document’s two linked external style sheets. This is necessary because Netscape 6 doesn’t support the DISABLED property of the <link> tag.

you should see the styles of the document change dynamically. When you click the links.3 shows the document with the styles turned off. FIGURE 12. 12 . Figure 12.2 The multiple-choice styles example displayed using the second style sheet.Creating Consistent Styles 165 FIGURE 12. and Figure 12.1 The multiple-choice styles example displayed with the first style sheet.2 shows the document styled with the second style sheet.

but be sure to provide alternatives from our basic list and generic CSS fonts.5 and later. You’ll begin in the next hour by using DHTML to create drop-down menus for site navigation. In Part IV. . Aren’t there more fonts available on most computers than those listed here? A. If you’re really picky about fonts. In particular. Yes. Additional Mac fonts are installed by default in MacOS 8. readable pages that will display consistently on CSS browsers.3 The multiple-choice styles example displayed without styles.166 Hour 12 FIGURE 12. several are included with Windows 98 and later. you can assemble a much larger list. you’ve learned some basic guidelines for using styles to create usable. Q&A Q. and some are installed with Internet Explorer. Summary In this hour. and still will be readable on browsers without CSS support. you’ll apply what you’ve learned so far to create several impressive and useful examples of DHTML in action. Congratulations! You’ve reached the end of Part III.

In Internet Explorer 4. The technique in this hour using <link> tags is a bit more complex. Why was this not used in the example in this hour? A.styleSheets object used to disable style sheets.Creating Consistent Styles 167 Q. enabled disabled stylesheet 12 . There is no way to do this in Netscape 4. Helvetica. the enable/ disable script can work the same way. serif b. Can I enable or disable style sheets in Netscape 4 or Internet Explorer 4? A. Arial. Questions 1. Courier. you can use document. Once you’ve obtained the array. Helvetica. Arial c. Which of the following fonts is guaranteed to work on all CSS-compliant browsers? a. This object is supported only by Internet Explorer 5 and 6. I’ve seen the document. b. sans-serif 2.tags(‘link’) instead of the getElementsByTagName method. sans-serif c. What is the name of the property of a <link> element you change to enable or disable an external style sheet? a. c. Times New Roman. Arial.all. Q. but works in Internet Explorer 5 and later and Netscape 6. Which of the following lists includes three fonts that are roughly equivalent? a. Quiz Test your knowledge of the material covered in this hour by answering the following questions. monospace 3. Courier b.

and two or more style sheets to switch between. try the following exercise: • Try creating your own page with multiple-choice styles. Exercises If you’d like some final practice using CSS style sheets before moving on. and the generic sans-serif are all sans-serif fonts. Of course. You can use the disabled property of a <link> element to enable or disable an external style sheet. c. it will work on all CSS-compliant browsers. Arial. Helvetica. its appearance isn’t guaranteed to be identical between browsers. b. 3.168 Hour 12 Answers 1. 2. b. Since monospace is a CSS generic font. .

PART IV Dynamic HTML in Action Hour 13 Creating Drop-Down Menus 14 Creating a Menu Tree 15 Creating DHTML Text Effects 16 Using DHTML for Animation .

.

and should be comfortable with the basics of DHTML and CSS. In this hour. This is a popular application of DHTML and isn’t hard to accomplish. In the next four hours. practical examples. you’ll apply what you’ve learned about DHTML to create some useful. This hour covers the following topics: • Planning objects and events • Creating the menu bar • Creating menu layers • Creating JavaScript functions • Completing and testing the example .HOUR 13 Creating Drop-Down Menus Welcome to Part IV! You’re halfway through this book. you’ll begin by creating a menu-based navigation system for a Web page.

You can use this object to change each menu item’s color as the mouse pointer moves over them. a layer will be used to display the menu under the term. You can create a similar menu for your site. changing the menu term’s color when the mouse pointer is over it.172 Hour 13 Overview In this hour. it’s useful to get an idea beforehand of which HTML elements you’ll be treating as objects. You will use this tag’s object to create a rollover effect. Using DHTML. . there’s another important step—plan the structure of the site and how the menu will be organized. • When the mouse is over one of the menu terms. Of course. “Reviewing HTML. Service. In a large site with many pages. A poorly organized menu system can actually be more confusing to users than a simple list of links. In this example. You then can be sure to use the ID attribute on these elements to make them easy to manipulate. In a site with only a few pages. a DHTML menu like this can create more confusion than it solves. you’ll learn how you can use DHTML to create a user-friendly navigation system for a Web site. Sales. The menu itself will be a table.” The original page included several links to navigate to different sections of the site: Products. You also will use this object to determine the menu term’s position within the browser window. so you can position the menu directly below the term. you’re familiar with the menu bar at the top of an application’s window. you’ll use objects for the following HTML elements: • Each menu term will be displayed in a table cell. a well-organized menu makes the perfect navigation system. created with a <td> tag. and so on. you will use the Figby Industries Web page that you created in Hour 2. on the other hand. you can create a menu that offers several further choices under each item. If you’ve used a Windows or Macintosh computer. and each cell in this table also will be assigned an ID attribute. if you’re designing a menu system for a non-fictional site. As an example in this hour. Objects and Events When planning a DHTML project like this.

Creating the HTML Document This will be the largest DHTML application you’ve worked with so far. you can organize them in a table. and it involves quite a bit of HTML and JavaScript. 13 Creating the Menu HTML The menu bar will simply be a horizontal group of links. both the menu terms and each item within each menu will need onMouseOver and onMouseOut event handlers. you can use the SRC attribute of the <script> tag to keep the JavaScript code in a separate document. then proceed to create the JavaScript portion. Using a separate file for the JavaScript code also would make it easy to use the same code on several different pages.Creating Drop-Down Menus 173 Layers are a good choice for the menus because they will be small square areas that overlap the other content of the page.js”> You will create the HTML portion of the document in this section. To display them in a neat layout with a box around each link. To make things easier. You will use these for two reasons: • To open each menu when the mouse pointer is over the menu’s term • To highlight each menu term or item with a rollover effect To accomplish this. in the same directory as the HTML document: <script language=”JavaScript” src=”menu.js. The table will begin with these tags: <table border=”0” cellpadding=”4”> <tr> .0 browsers if you choose to do so later. each with a different menu. Event Handlers As you might have guessed. Using layers also will make it easier to make your menus compatible with the 4. this example will use the onMouseOver and onMouseOut event handlers. The following tag defines a script that is stored in the file menu.

calls the Timeout function. This link can be used by older browsers that don’t display the menu of more specific links. The border=0 attribute removes the standard border between table cells. Each menu term will be a single table cell.” onMouseOut=”Timeout(‘products’). here is the definition for the Products term within the menu bar: <td ID=”menu-products” width=”100” bgcolor=”Silver” onMouseOver=”Menu(‘products’).html”><b>Products</b></a> </td> This code defines a table cell with the <td> tag. which will close the menu if it is no longer in use.174 Hour 13 The <table> tag starts the table. The menu will display as a simple bar across the top of the document. . For example. and the cellpadding=4 attribute adds some padding around the menu text.”> <a href=”products. This tag defines a background color for the cell and has an explicit width specified. The <tr> tag defines the table’s single row. FIGURE 13. which will open the menu under this term. Figure 13. Each menu term uses two event handlers: • • onMouseOver onMouseOut calls the Menu function. so all of the menu terms will have the same width (100 pixels).1 shows Internet Explorer’s display of the example before any of the menus are opened.html).1 The HTML document with menu bar. The menu term (Products) is linked to an HTML document (products.

For example. Each table row contains a single cell with a menu item.1 The Complete HTML Document 13 <html> <head> <title>Figby Industries.’p2’). This will simply be a combination of the HTML components explained in the previous sections. which will return the background color to normal.Creating Drop-Down Menus 175 Defining the Layers Next. so none of the menus will be displayed until the user moves the mouse over the menu terms.”> <a href=”equip. the following is the HTML code for the Products menu: <div ID=”products” STYLE=”position:absolute. Finishing the HTML Document You now can create the complete HTML document for the example.1 shows the complete HTML document.” onMouseOut=”UnHighlight(‘products’. defined with the <div> tag. Each item in the menu is defined with a <td> tag. Inc. • The onMouseOut event handler calls the UnHighlight function.html”>Equipment</a></td></tr> <tr> <td width=”100%” ID=”p2” onMouseOver=”Highlight(‘products’.’p2’). there are two items in the Products menu. visibility: hidden”> <table width=”100%” border=”0” cellpadding=”4” cellspacing=”0”> <tr> <td width=”100%” ID=”p1” onMouseOver=”Highlight(‘products’. Along with a link. The layers will use the visibility style attribute set to hidden. LISTING 13.html”>Supplies</a></td></tr> </table> </div> Within the <div> tag that defines the layer. you’ll need to define the menus themselves.</title> <script language=”JavaScript” src=”menu. This will change the menu item’s background color. In this example. Each <td> tag should have a unique ID attribute.’p1’). Each menu will be a layer. the menu is defined as a table.’p1’).”> <a href=”supplies.js”> </script> .” onMouseOut=”UnHighlight(‘products’. Listing 13. each menu item has two event handlers: • The onMouseOver event handler calls the Highlight function.

” .” onMouseOut=”Timeout(‘service’).”> <a href=”prices.’p1’).” onMouseOut=”Timeout(‘jobs’).”> <a href=”staff.html”><b>Products</b></a> </td> <td ID=”menu-sales” width=”100” bgcolor=”Silver” onMouseOver=”Menu(‘sales’).html”>Equipment</a></td></tr> <tr> <td width=”100%” ID=”p2” onMouseOver=”Highlight(‘products’.1 continued </head> <body style=”margin-left:0.html”><b>Staff</b></a> </td> <td ID=”menu-jobs” width=”100” bgcolor=”Silver” onMouseOver=”Menu(‘jobs’).” onMouseOut=”UnHighlight(‘sales’.”> <table border=”0” cellpadding=”4”> <tr> <td ID=”menu-products” width=”100” bgcolor=”Silver” onMouseOver=”Menu(‘products’).” onMouseOut=”Timeout(‘products’).”> <a href=”service.’s1’).html”><b>Sales</b></a> </td> <td ID=”menu-service” width=”100” bgcolor=”Silver” onMouseOver=”Menu(‘service’).”> <a href=”order.”> <a href=”sales.” onMouseOut=”UnHighlight(‘products’.”> <a href=”jobs. visibility: hidden”> <table width=”100%” border=”0” cellpadding=”4” cellspacing=”0”> <tr> <td width=”100%” ID=”s1” onMouseOver=”Highlight(‘sales’.html”>Price List</a></td></tr> <tr> <td width=”100%” ID=”s2” onMouseOver=”Highlight(‘sales’.” onMouseOut=”UnHighlight(‘products’.’p1’). margin-top:0.’s2’).”> <a href=”products.”> <a href=”equip.’s2’).”> <a href=”supplies.” onMouseOut=”Timeout(‘sales’).html”><b>Service</b></a> </td> <td ID=”menu-staff” width=”100” bgcolor=”Silver” onMouseOver=”Menu(‘staff’).’s1’).’p2’).’p2’).html”>Supplies</a></td></tr> </table> </div> <div ID=”sales” STYLE=”position:absolute.” onMouseOut=”Timeout(‘staff’).html”>Order Form</a></td></tr> <tr> <td width=”100%” ID=”s3” onMouseOver=”Highlight(‘sales’.” onMouseOut=”UnHighlight(‘sales’. visibility: hidden”> <table width=”100%” border=”0” cellpadding=”4” cellspacing=”0”> <tr> <td width=”100%” ID=”p1” onMouseOver=”Highlight(‘products’.176 Hour 13 LISTING 13.html”><b>Employment</b></a> </td> </tr> </table> <div ID=”products” STYLE=”position:absolute.’s3’).

” onMouseOut=”UnHighlight(‘service’.html”>Specials</a></td></tr> </table> </div> <div ID=”service” STYLE=”position:absolute.html”><b>Staff</b></a></li> <li><a href=”jobs. Follow the links below or use the menu above to learn more about our company and our products.’j1’).’r1’). </p> <ul> <li><a href=”products. visibility: hidden”> <table width=”100%” border=”0” cellpadding=”4” cellspacing=”0”> <tr> <td width=”100%” ID=”r1” onMouseOver=”Highlight(‘service’. your source for all sorts of imaginary products.” onMouseOut=”UnHighlight(‘service’.’r2’).Creating Drop-Down Menus 177 LISTING 13.gif” width=”486” height=”180” border=”0” alt=””><br> <h1>Welcome to Figby Industries!</h1> <p>Welcome! This is the home page of Figby Industries.”> <a href=”staff.’t1’). visibility: hidden”> <table width=”100%” border=”0” cellpadding=”4” cellspacing=”0”> <tr> <td width=”100%” ID=”t1” onMouseOver=”Highlight(‘staff’.html”>Support</a></td></tr> <tr> <td width=”100%” ID=”r2” onMouseOver=”Highlight(‘service’.”> <a href=”cservice.html”><b>Employment</b></a></li> </ul> </body> </html> 13 .” onMouseOut=”UnHighlight(‘jobs’.” onMouseOut=”UnHighlight(‘staff’.html”>Meet the Staff</a></td></tr> </table> </div> <div ID=”jobs” STYLE=”position:absolute.html”>Job Listings</a></td></tr> </table> </div> <img align=”center” src=”logo.html”><b>Sales</b></a></li> <li><a href=”service.html”>Contact Us</a></td></tr> </table> </div> <div ID=”staff” STYLE=”position:absolute.’r2’).’s3’).”> <a href=”specials.html”><b>Service</b></a></li> <li><a href=”staff.html”><b>Products</b></a></li> <li><a href=”sales.1 continued onMouseOut=”UnHighlight(‘sales’.’r1’).’t1’).”> <a href=”jobs.’j1’).”> <a href=”support. visibility: hidden”> <table width=”100%” border=”0” cellpadding=”4” cellspacing=”0”> <tr> <td width=”100%” ID=”j1” onMouseOver=”Highlight(‘jobs’.

You can download this image. Save the HTML document now. Staff. While this is a long HTML document. the remainder of the body of the page includes a bulleted list of links to provide an alternative navigation system. and to highlight menu items. You will assemble all of these functions into a JavaScript file in this hour’s Workshop section. since the JavaScript functions aren’t available until you create the JavaScript file. Creating the JavaScript Functions Next. logo. Sales. All of these will be hidden by default. it really just repeats the same familiar HTML code.com/dhtml/. you’ll need to create the JavaScript functions to open and close the menus. This will be the name of the menu to open. The following are the components of this document: • The <script> tag in the <head> section includes a script called menu. along with the HTML and JavaScript files for this example. • After the menu bar are five <div> sections that define the five menus. The menu now has five terms: Products. from this book’s Web site: http://www. Displaying a Menu The Menu function will display a menu. The if statement checks the document. The next portion of the function sets some variables to keep track of which menu is currently open: . • The menu bar is defined between the first <table> and </table> tags.getElementById) return. The function has one parameter. You will create this file in the next section with the required JavaScript functions. • After the menu is defined.getElementById object and exits the function if the browser does not support this needed W3C DOM function. but the browser will display JavaScript error messages.gif.starlingtech.178 Hour 13 This example uses an image. current. and Employment.js. each defined with a separate <td> tag. You can load it into a browser to test. Here is the beginning of the function: function Menu(current) { if (!document. Service.

style. box=document. The m object is the table cell for the menu term. which you’ll create later.getElementById(“menu-” + current).style. the function obtains the needed objects: m=document. we calculate the position where the menu should be displayed: box. This completes the Menu function. This portion of the function sets inmenu to true. lastmenu=current. we use the value 108 here.offsetTop + m. The top position is set to the menu term’s top position plus its height. We also set its background color. if (oldmenu) Erase(oldmenu).backgroundColor=”Aqua”. When the user moves the mouse pointer out of a menu term.style.style.left= m.getElementById(current). you need a function to erase a menu when it’s no longer in use.style. This sets the left position of the layer (box) to the same position as the menu term (m). box. highlight the menu term with the same background color. oldmenu=lastmenu. and set the width of the menu. Next. It saves the previously opened menu name in the oldmenu variable. } The visibility attribute makes the layer appear.top= m. box. The inmenu variable is a global variable that indicates whether a menu is currently open or not. Next. 13 Although the menu terms have a width of 100 pixels. to erase the previous menu.offsetHeight.Creating Drop-Down Menus 179 inmenu=true. m. the previous menu might still be displayed. box. This is because the cellpadding=4 attribute in the menu bar’s definition adds four pixels of padding on each side. and the box object is the layer for the appropriate menu. We call the Erase function. and the lastmenu global variable keeps track of the most recently opened menu.width=”108px”. Erasing Menus Next.visibility=”visible”.style. then sets the lastmenu variable to the new value. we set some other style attributes: box.backgroundColor=”Aqua”.offsetLeft. the Timeout function is called: . If the oldmenu variable is set. so the layer should appear directly below the menu term. Next.

getElementById(“menu-” + current). the menu shouldn’t be erased. obj.500). Next.getElementById(item).item) { if (!document.backgroundColor=”Silver”. If they’re set. } This function first sets the inmenu and lastmenu variables to ensure that the menu is not erased by the Timeout function. } This function simply sets the inmenu variable to false.style.backgroundColor=”Aqua”. it finds the object for the current menu item. } . The UnHighlight function is equally simple: function UnHighlight(menu. it might be moving into the menu itself.getElementById) return. you’ll need two simple functions to highlight the menu items as the mouse pointer moves over them.setTimeout(“Erase(‘“ + current + “‘). First. so the function aborts. it finds the m and box objects as in the Menu function. obj=document.getElementById) return. These will be set each time the mouse pointer moves over a menu item.backgroundColor=”Silver”.180 Hour 13 function Timeout(current) { inmenu=false. lastmenu=menu. box. Next.item) { if (!document. This delay is necessary because when the mouse pointer moves away from the menu term.”. the menu is still open.getElementById) return. obj. Timeout(menu). Here’s the Erase function: function Erase(current) { if (!document.style. window.setTimeout method to call the Erase function after a half-second delay.style. and sets its background color. m=document.getElementById(item). The layer is hidden. obj=document.getElementById(current).style.visibility=”hidden”. and uses the window. box=document. and the menu term’s background color is returned to normal. If so. Highlighting Menu Items Finally. inmenu=true. the Highlight function: function Highlight(menu. if (inmenu && lastmenu==current) return. m. } This function uses an if statement to check the inmenu and lastmenu variables.

LISTING 13. obj=document.style.getElementById(current).getElementById(“menu-” + current). window.backgroundColor=”Aqua”. m=document. box=document. if (oldmenu) Erase(oldmenu).left= m.Creating Drop-Down Menus 181 This function calls the Timeout function for the current menu. function Menu(current) { if (!document.offsetLeft.width=”108px”.offsetTop + m.top= m. box.style.getElementById) return.style. m.style.500). Workshop: Creating the Complete Example You now can combine all of the JavaScript functions you have created into a JavaScript file with the . } function Highlight(menu. } function Timeout(current) { inmenu=false. Listing 13. } 13 . var lastmenu=0. lastmenu=current. m=document. box.style.visibility=”visible”.setTimeout(“Erase(‘“ + current + “‘).getElementById) return. Save this file as menu.style. m.getElementById) return. obj.visibility=”hidden”.getElementById(item).js in the same directory as the HTML document.”.backgroundColor=”Aqua”. } function Erase(current) { if (!document. because the mouse pointer might have moved out of the menu entirely.style. box.style. inmenu=true. box.2 The Complete JavaScript File var inmenu=false. it finds the object for the current menu item and returns its background color to normal. box. box=document.2 shows the complete JavaScript file. oldmenu=lastmenu.style. lastmenu=menu.backgroundColor=”Silver”.item) { if (!document. Next.getElementById(current).js extension to complete the example. box. inmenu=true. if (inmenu && lastmenu==current) return.getElementById(“menu-” + current).backgroundColor=”Silver”.offsetHeight.

Notice that the JavaScript file does not include <script> tags.backgroundColor=”Aqua”. “Dealing with Browser Differences. the Sales menu is open and the Order Form link is currently selected. Menu items should change color as you move over them.getElementById(item). you can load the HTML document into a browser and test the menu. and the menu should be erased when you move away from it.style.2 shows Netscape 6’s display of the example. This example works in Internet Explorer 5. obj.getElementById) return.0 or later and Netscape 6 or later. Now that you have completed the HTML document and the menu. Timeout(menu).js file.item) { if (!document. However. You can use only JavaScript statements within the JavaScript file.0 browsers. } The first two lines of this document declare the global variables inmenu and lastmenu.2 continued function UnHighlight(menu. Erase. When you move the mouse pointer over a menu term. See Hour 17. Highlight. its corresponding menu should appear. it is possible to adapt it to work in 4.182 Hour 13 LISTING 13. The remainder of the document includes the Menu. In the figure. Timeout. Figure 13.” for details. obj=document. . These are included in the HTML document. and UnHighlight functions.

If the margins are non-zero. In the next hour. This is one of the most popular uses of DHTML. you’ll create another real-world DHTML example: a hierarchical menu tree with items that can expand and collapse. Q&A Q.Creating Drop-Down Menus 183 FIGURE 13. Summary In this hour. 13 . Just add additional <td> sections for each menu item. but Netscape’s values will be measured from the margins. Internet Explorer’s values for the offset properties will be measured from the edge of the browser window. you’ve created a menu system using DHTML. To customize this example for my site. Q. Be sure each one has a unique ID attribute. Why does the example’s <body> tag set the left and top margins to zero? A. Yes.2 Netscape displays the menu in action. The only way to avoid this issue is to use zero margins or to adjust the position of the menus based on the current browser. can I have more than three items in a menu? A. and a great way to simplify navigation for a Web site. This is to avoid a discrepancy between Internet Explorer and Netscape.

box. when I click on an item within the menu nothing happens.visibility=”visible”. box. When you click on a link to a file that does not exist. The <script> tag. Quiz Test your knowledge of the material covered in this hour by answering the following questions.style. Which HTML tags are typically used to define layers? <div> <div> or <body> or <span> or <script> <span> Answers 1.style. a. c. Which of the following statements correctly makes a layer. Questions 1. b.style. The correct statement assigns the value “visible” to the box. some versions of Netscape display an error message and others do nothing. What’s wrong? A.visibility property. defined by the box object. You are most likely testing the document in a local file rather than on a Web server. In Netscape 6. b. If you are placing JavaScript code in a separate file. 3. with the SRC attribute. box. a. b. The JavaScript file can contain only JavaScript statements. since the links would point to actual files.184 Hour 13 Q. 2. In a real site.visibility=”true”. . this wouldn’t be a problem. should appear in the HTML document. 3. not HTML tags.visibility=1. c. Layers are typically defined using the <div> or <span> tags. The JavaScript file c. c. Neither file 2. visible? a. which document contains the <script> tag? a. The HTML file b.

try the following exercises: • Add an additional item to the Products menu in the example. 13 .Creating Drop-Down Menus 185 Exercises If you’d like to practice what you learned in this hour before moving on. • Combine the Staff and Employment menus in the example into a single menu.

.

Fortunately. DHTML can overcome this limitation—you created one kind of navigation system in the previous hour. HTML is limited to simple lists of links. you’ll create a hierarchical.HOUR 14 Creating a Menu Tree One of the major limitations of HTML is that it can’t support dynamic navigation systems. tree-style menu that could be used as a Web site’s navigation system. In this hour. This provides a way to view a map of the entire site at a glance. Hour 14 covers the following topics: • How the menu tree will appear • Planning the objects for the menu • Creating the HTML document • Creating the JavaScript functions • Finishing and testing the example . such as those used in computer operating systems.

You might have seen this technique used on the Web—and you’ve certainly seen it used on your PC. and X-Windows systems use a system like this to allow you to navigate through the directories and files on a disk. Specifications.188 Hour 14 Overview In this hour. Nested Categories While this structure of categories and items provides a well-organized navigation system for small sites. Windows. When you click on the [+] icon. At the top level. a section of the menu might look like this: [+]Products [-]Support Technical Support Support Forum Contact Support This example shows two categories. Each has a [+] icon to its left indicating that the category can be expanded. For example. . and the icon changes to a [-] symbol. One of these. Macintosh. “Using DHTML for Animation.” you’ll create a menu tree that uses image icons. and the Support category is currently displayed. You can then click on the icon to return the category to its collapsed (hidden) state. the Products category contains four items. In Hour 16. you’ll create a hierarchical tree of options for site navigation. can be further expanded with two sub-items under the category. main categories are listed. the items under the category are listed. Products and Support. the Products category might look like this: [-]Products Product List Order Form [-]Specifications Old Products New Products Price List In this example. The Products category is currently collapsed. Here’s how this menu system works. in a larger site you might want to go further and create subcategories. As an example. You also can use images rather than [+] and [-] icons.

The browser will handle the links in the normal way. and you can use javascript: links to call a script when the icons are clicked.html”>Technical Support</a><br> <a href=”sforum. you will use the SRC attribute of the <script> tag to keep the JavaScript code in a separate file.display property to control whether the category is expanded or collapsed. margin-left:2em. and clicking on the individual item links. For example. here is the HTML code for the Support category: <b><a ID=”xsupport” href=”javascript:Toggle(‘support’). and the <a> tag will be assigned an ID attribute.html”>Support Forum</a><br> <a href=”sforum. • Each [+] icon will be enclosed within a link element (<a> tag). it’s actually simple to create.”>[+]</a> Support</b><br> <div ID=”support” style=”display:none.”> <a href=”tech.Creating a Menu Tree 189 The tree navigation system you will create in this hour can actually have any number of nested levels of categories. the category name. This will allow your script to manipulate the object’s innerHTML property. the user will interact with the navigation system in two ways: clicking the [+] and [-] icons.html”>Contact Support</a><br> </div> 14 . Each item will include a linked [+] icon. Creating the HTML Document The first step in creating the menu tree is to create the HTML document. As with the previous hour’s example. and change the expand ([+]) icon to a collapse ([-]) icon when the category is expanded. and a <div> that defines the menu items. As you might have guessed. Defining the Menu Items The bulk of the HTML document will consist of the menu items. You can create it by using a <div> element to enclose each category’s contents. You’ll use objects for two HTML elements to create the menu: • Each <div> that contains a category will be assigned an ID attribute. You then can find its corresponding object and manipulate the style. and vice versa when the category is collapsed. Objects and Events While this menu system might sound sophisticated.

Listing 14.”> <a href=”prodlist. margin-left:2em. Completing the HTML Document By combining several menu category definitions in the <body> section. showing only the category names. and add x to the name of each for the ID of the corresponding link tag.html”>Product List</a><br> <a href=”order. LISTING 14. The menu tree will be collapsed by default. margin-left:2em”> .} </style> <script language=”javascript” src=”tree.190 Hour 14 The <div> is assigned the ID attribute support.html”>Order Form</a><br> <a ID=”xspecs” href=”javascript:Toggle(‘specs’). make sure you create unique ID values for each <div>.1 shows the complete HTML code for this example. You can make it expanded by default by changing the display style property to the value block and the [+] icon to a [-] icon.”>[+]</a> Products</b><br> <div ID=”products” style=”display:none.1 The Complete HTML Document <html> <head> <title>Creating a Navigation Tree</title> <style> A {text-decoration: none.”>[+]</a> Specifications<br> <div ID=”specs” style=”display:none. you can create a complete HTML document. Using a name based on the <div> tag’s identifier will make it easy to find this object in your script. and the Toggle(‘support’) command calls a JavaScript function to expand or collapse the category. The [+] icon’s <a> element is given the ID attribute xsupport. You could use this in a frame to provide a sophisticated navigation system for a site.</p> <hr> <b><a ID=”xproducts” href=”javascript:Toggle(‘products’). If you add additional items or customize the menu.js”> </script> </head> <body> <h1>Navigation Tree Example</h1> <p>The navigation tree below allows you to expand and collapse items.

Notice the <script> tag that references the JavaScript file tree.”> <a href=”tech. Creating the JavaScript Functions The JavaScript functions for the menu tree are actually quite simple.”>[+]</a> Contact Us</b> <div ID=”contact” style=”display:none.”> <a href=”contact1. This function expands or collapses a menu item.js. To use this HTML document.html”>Old Products</a><br> <a href=”specs2.”>[+]</a> Support</b><br> <div ID=”support” style=”display:none.html”>Contact Support</a><br> </div> <b><a ID=”xcontact” href=”javascript:Toggle(‘contact’). save it using any name.Creating a Menu Tree 191 LISTING 14.html”>Price List</a><br> </div> <b><a ID=”xsupport” href=”javascript:Toggle(‘support’). Here is the JavaScript code for the Toggle function: 14 .html”>Support Forum</a><br> <a href=”sforum. You also can create links that expand or collapse all of the categories using simple JavaScript functions.html”>Marketing Department</a><br> </div> <p> </p> <a href=”javascript:Expand(). margin-left:2em.html”>Technical Support</a><br> <a href=”sforum.1 continued <a href=”specs1. margin-left:2em. and defining this is as simple as nesting a <div> tag within the <div> for the Products menu.html”>Sales Department</a><br> <a href=”contact2.html”>New Products</a><br> </div> <a href=”pricelist. Hiding and Showing Menus The Toggle function is called when the user clicks on the [+] or [-] icon.”>[Expand All]</a><br> <a href=”javascript:Collapse(). You will create this script file in the next section.html”>Service Department</a><br> <a href=”contact3. You can nest any amount of items in this manner. You will use a single function to expand or collapse a category. and changes the icon appropriately.”>[Collapse All]</a> </body> </html> Notice that the Products menu contains a subcategory.

Expanding All Items The HTML document you created already contains links for two additional functions: <a href=”javascript:Expand(). It then changes the icon to the [-] symbol. the script assigns the value block to the display property. key. key.style. The visible variable is assigned the value true if the category is currently displayed. . In this example. you use the display property to hide and show the menu items.innerHTML=”[+]”.style.length.getElementsByTagName(“DIV”). } } This function first gets the object for the category’s <div> element in the obj variable. revealing the category’s contents.display=”block”. When you use this property. visible=(obj.style.getElementById(“x” + item). } else { obj. The Expand function expands all of the categories: function Expand() { divs=document. if (visible) { obj. and the value false if it is currently hidden.i<divs.style.display!=”none”) key=document. If the category is currently hidden. hiding the contents of the <div> element. for (i=0.”>[Collapse All]</a> These will provide an easy way to show or hide all of the menu items.i++) { divs[i].”>[Expand All]</a><br> <a href=”javascript:Collapse().192 Hour 14 function Toggle(item) { obj=document.display=”none”.innerHTML=”[-]”.display=”block”. The visibility property wouldn’t work here because it would leave a blank space for all of the items that are not currently shown. and the object for the [+]icon in the key variable. If the category is currently visible. the script assigns the value none to the display property. It also changes the icon to a [+] symbol.getElementById(item). the page expands and collapses as the items are revealed or hidden.

2 The JavaScript File for the Menu Tree 14 function Toggle(item) { obj=document. . visible=(obj.display=”none”.2 shows the complete JavaScript file. It changes their display properties to block. key.i<divs. of all of the <div> elements in the document. For simplicity.js file.i++) { divs[i]. This works for the example.getElementsByTagName(“DIV”). } } This function uses the getElementsByTagName method to get an array.id). LISTING 14. key. the Expand and Collapse functions show or hide every <div> element in the document.innerHTML=”[-]”. The only difference is that it assigns the value none to their display properties. Listing 14.Creating a Menu Tree 193 key=document. and changes it to the [-] symbol.getElementById(“x” + divs[i]. Workshop: Finishing and Testing the Menu To complete this example. it might affect other <div> elements on the page. Be sure you modify the functions to account for this. Collapsing All Items The Collapse function will collapse all of the categories in the menu tree. you can combine the JavaScript functions you have created into a . key=document.getElementById(item). divs.getElementById(“x” + item). } } This function also uses an array of <div> elements.getElementById(“x” + divs[i].innerHTML=”[+]”.style.display!=”none”) key=document.style. and changes their corresponding icons to [+] symbols. gets the object for their corresponding icon. It uses a for loop to iterate through each of these elements. It is very similar to the Expand function: function Collapse() { divs=document.length.id). for (i=0. but if you include the menu in a larger HTML document.

display=”none”.display=”block”.i++) { divs[i].starlingtech. .1 shows Internet Explorer’s display of this document with several categories expanded. for (i=0.id). } } To test the example.2 continued if (visible) { obj. Don’t forget that you can download all of the listings for this book.style. When you load the document into a browser. including this hour’s HTML and JavaScript files.getElementById(“x” + divs[i]. the main categories are displayed.display=”none”.i<divs.getElementsByTagName(“DIV”). } } function Expand() { divs=document.com/dhtml/.js. This example requires Internet Explorer 5 or later.getElementById(“x” + divs[i].length. key. Figure 14.id). You can expand or collapse categories using the icons.style. } } function Collapse() { divs=document.innerHTML=”[-]”. save this JavaScript file as tree.style.i<divs.i++) { divs[i]. be sure you modify the SRC attribute of the <script> tag in the HTML document to use the same name.display=”block”. } else { obj.style. Save the JavaScript file in the same directory as the HTML document. If you use a different name. from this book’s Web site at http://www.194 Hour 14 LISTING 14. key=document.innerHTML=”[+]”. key. for (i=0.getElementsByTagName(“DIV”).innerHTML=”[-]”.length.innerHTML=”[+]”. or Netscape 6 or later. key=document. key. key.

Simply replace the icons in the HTML document with image tags. you’ve created a tree-style navigation system that could easily be adapted to any Web site. 14 . Yes. Expand. you’ll learn how to create various effects with text—moving. This is easy to do with DHTML and provides an ideal navigation method for large Web sites. In the next hour.Creating a Menu Tree 195 FIGURE 14. Specifically. and change the Toggle. blinking. You can avoid this issue by placing the navigation system in a frame within the page. Summary In this hour. If I use this form of navigation on my site. Q. and scrolling.1 The menu tree as displayed by Internet Explorer. See Hour 16 for a modified version of this hour’s example with images. fading. or even in a column of a table. and Collapse functions to change the image sources. How can I use graphic symbols rather than the [+] and [-] icons? A. you’ll explore some more examples of DHTML in action. if the entire site is in a single window. Q&A Q. won’t the entire content move up and down as the sections are expanded and collapsed? A.

Which of the following is the correct command to change the linked text within an <a> tag? a. Quiz Test your knowledge of the material covered in this hour by answering the following questions.getElementsByTagName(“DIV”).collapse 2. . divs=document. How can I prevent the Expand and Collapse functions from hiding or showing other <div> elements within my page? A. Questions 1.” for an explanation. “Dealing with Browser Differences. divs=document. Which is the correct command to find objects for all of the <div> elements in a document and store them in an array? a.196 Hour 14 Q. Hour 16 includes a modified version of this hour’s example that includes this feature. divs=document. style. You then can modify the Expand and Collapse functions to check for that character in each division’s id attribute before modifying it. key. key. Q. If that isn’t practical. using a special character in the names that won’t be expanded or collapsed. However.0 browsers? A.style. c. b. 3. One easy way is to keep the navigation tree in its own frame. Which of these properties can you use to hide or show an element of a document and have the remainder of the document expand or collapse accordingly? a.textValue=”[+]”. so you might run into problems. c.visibility style.display style. b. c.innerHTML=”[+]”.getElementsByTagName(“DIV”). the 4.0 browsers don’t consistently support the display attribute. Can this example be adapted to work in the version 4. you can modify the ID attributes to have a common value: for instance. Yes—see Hour 17. b.linkText=”[+]”. key.getArrayByTagName(“DIV”).

a. 3. The style.1. c. b. One easy way to do this is to place the entire menu in a <span> tag. Test it in a browser and verify that it works correctly. 14 . Create script functions to hide or show the entire menu. or a different imaginary site.getElementsByTagName(“DIV”). See Hour 16 for a more complex example that uses animation to hide and show the menu.display property allows you to expand or collapse the display of items within a Web document. The innerHTML property is one way to change the text within a link tag.Creating a Menu Tree 197 Answers 1. using this hour’s example as a basis. Exercises If you’d like to work further with this example before moving on. This is the correct statement: divs=document. and change that element’s display property. try the following exercises: • Create a menu for your own site. • Add “Show Menu” and “Hide Menu” links to the example in Listing 13. 2.

.

HOUR 15 Creating DHTML Text Effects While DHTML can do complex things like setting up a navigation system for a site. it’s also well-suited to simple tasks. and scrolling messages. You can add a bit of style or life to a Web page with a simple DHTML script. This hour covers the following topics: • Creating blinking text • Moving text within a page • Fading text in and out • Creating a scrolling message . fading text. moving text. In this hour. you’ll explore some simple ways to use DHTML to draw attention to text within a page: blinking text.

style. and then set a timer for the next blink: function Blink() { obj=document. you should avoid blinking text except when absolutely necessary—for example. If the text is currently hidden. Wisely.500).”. Be warned. window. Smaller numbers speed it up. Internet Explorer never supported <blink>. } This function first finds the object for the text with the ID “blink”. else obj. it quickly gained a well-deserved bad reputation.visibility=”hidden”.style. . if (obj.style. Nonetheless. the Blink function uses the window. not part of the HTML standard. in an error message or an online game. and larger numbers slow it down. Next.0.getElementById(“blink”). and you can easily accomplish this using DHTML.visibility attribute. though. Creating the Script To make the text blink. Between the proprietary nature of the tag and the headaches it caused. This tag.200 Hour 15 Creating Blinking Text Netscape created quite a buzz when they introduced the <blink> tag in version 2. it is made visible. Finally. To avoid annoying your readers.visibility==”hidden”) obj. otherwise. This causes the function to be called again in 500 milliseconds (half a second). Change the 500 in this function to change the rate of blinking. you’ll need a simple JavaScript function. and even Netscape stopped supporting it in Netscape 6. it checks the text’s style. text that blinks too quickly can give viewers headaches.visibility=”visible”.setTimeout method to repeat itself. Remember. caused its contents to disappear and reappear at regular intervals. it is hidden. the title of your page is not important enough to blink. there are a few situations in which you might still want blinking text. The Blink function will toggle the text’s visibility attribute.setTimeout(“Blink().

and Fading text examples in this hour require Internet Explorer 5. all you need to do is include it in an HTML document and assign the ID attribute “blink” to some text. if (obj. LISTING 15. } </script> </head> <body onLoad=”Blink().setTimeout(“Blink(). The Blinking Text.” you learned the positioning properties that make this possible. but they could easily be adapted to 4.1 The Complete Blinking Text Example 15 <html> <head> <title>Blinking Text Example</title> <script language=”javascript”> function Blink() { obj=document.getElementById(“blink”).0 or later or Netscape 6 or later.”> <h1>Blinking Text Example</h1> <p>This is a quick example of blinking text.style.visibility=”visible”. and the onLoad event handler for the <body> tag starts the blinking.</p> </body> </html> This HTML document includes the Blink function you created. In Hour 6. .style. window. Listing 15.” Moving Text Another way to draw attention to text is to move it.style.visibility=”hidden”.”. <span ID=”blink”>This sentence is blinking</span> because a DHTML script is manipulating its visibility property. and you can easily do this with DHTML. The sentence that will blink is contained in a <span> tag with the ID attribute set to “blink”. “Dealing with Browser Differences.Creating DHTML Text Effects 201 Completing the Blinking Text Example To use the Blink function.0 browsers using the techniques in Hour 17. else obj.visibility==”hidden”) obj. “Creating Positionable Elements (Layers).500). Moving Text.1 shows the complete example document.

function Move() { obj=document. all you need to do is add it to an HTML document and assign the ID head1 to an object within the page. It first finds the variable for the head1 object. Next.left=pos. The Move function will be called again every 25 milliseconds. The pos variable will store the current position of the heading. it switches directions.left property for the heading to the pos value and uses the setTimeout method to repeat itself. the heading will be 100 pixels to the left of its original position. pos += direction.style. which can range from –100 to 100. which will be a heading on the page. window. } This script first declares two variables.getElementById(“head1”). the Move function sets the style. var direction=1. The Move function handles the actual moving. . Completing the Moving Text Example To use the moving text script.2 A Simple Example of Moving Text <html> <head> <title>Moving Text Example</title> <script language=”javascript”> var pos=0.direction. The position of the text ranges from –100 to 100 because the heading will use relative positioning. if (pos >= 100 || pos <= -100) direction = 0 .202 Hour 15 Creating the Script Only a small script is required to move the text: var pos=0. The if statement checks the position. and the direction variable indicates the current direction of motion: 1 moves to the right.”. Listing 15. it increments or decrements pos by adding the direction variable.2 shows the complete moving text example.setTimeout(“Move(). Finally. pos and direction. and –1 moves to the left. When the position is –100.25). If the position reaches the edge of this boundary. LISTING 15. obj.

”> <h1 align=”center” style=”position:relative.setTimeout(“Move().</p> </body> </html> 15 The <h1> heading is assigned the ID head1.”. the message has just reached the right-hand side and is now moving to the left. Figure 15. This is done using DHTML and the style attributes that control positioning. window.” ID=”head1”> Moving Text Example</h1> <p>The heading of this page moves back and forth across the page. function Move() { obj=document.Creating DHTML Text Effects 203 LISTING 15.left=pos. Its position style attribute has been set to relative so that the motion will be relative to its original (centered) position. pos += direction. The onLoad event handler for the <body> tag calls the Move function to start the motion. obj. if (pos >= 100 || pos <= -100) direction = 0 .2 continued var direction=1. .25).getElementById(“head1”). In the figure.1 The moving text example in action. FIGURE 15.style.direction. } </script> </head> <body onLoad=”Move().1 shows this example running in Internet Explorer.

”. and #F1F1F1 are three different shades of gray. green. if (hcolor >= 0 && hcolor < 256) { hex=hcolor. #050505. The Fade function handles the actual fading. This example changes the color to green using a numeric value: h=document. Creating the Script You can create a simple script that allows text to be faded either in (white to black) or out (black to white): var hcolor=255. direction. An if statement verifies that hcolor falls within the legal range of zero to 255. obj. and changes the heading’s color.color=”Blue”. and blue components. you can cycle through color values that have equal red.toString(16). This example changes the color of the head1 object to blue.204 Hour 15 Fading Text You also can draw attention to text by fading it in or out. If it does. function Fade(direction) { obj=document. This function’s parameter. For example. You might recall using code like this to change a text color earlier in this book: h=document. if (hex. you also can use a hexadecimal number that specifies the red. green. .1). } } This script first declares a global variable.getElementById(“head1”).length==1) hex=”0” + hex. the function continues.getElementById(“head1”).style. To fade text from white to black using shades of gray. and blue values. This is easily accomplished in DHTML by changing the text color. hcolor. hcolor += direction. h.setTimeout(“Fade(“ + direction + “). Along with color names. After finding the object for the head1 heading.color=”#” + hex + hex + hex. and –1 for white to black. The hex variable is assigned to the hexadecimal equivalent of hcolor using the toString method. the Fade function adds the direction value to hcolor. #101010. window.getElementById(“head1”).color=”#00FF00”.style. specifies the direction of the fade: 1 for black to white. The function then builds a string with the # symbol followed by the same hexadecimal number three times. h.style. to store the current color of the heading.

the Fade function uses window.toString(16).”. LISTING 15. If the value has only one digit.style. assign the identifier head1 to an object. such as 5.1).setTimeout(“Fade(“ + direction + “). This is accomplished by changing the color of the heading using DHTML.”>back in</a> using these links. You can use a longer delay for a slower fade. Completing the Fading Text Example To use the fading text script. function Fade(direction) { obj=document. if (hcolor >= 0 && hcolor < 256) { hex=hcolor.”>fade it out</a> or <a href=”javascript:Fade(-1).Creating DHTML Text Effects 205 The if statement that checks hex. hcolor += direction. 15 Last.3 shows the complete fading text example. Listing 15. and you can <a href=”javascript:Fade(1).color=”#” + hex + hex + hex.3 The Complete Fading Text Example <html> <head> <title>Fading Text Example</title> <script language=”javascript”> var hcolor=255.getElementById(“head1”).length==1) hex=”0” + hex.”> Fading Text Example</h1> <p>The heading of this page fades in gradually when you load the page. but not least. an initial zero is added. would produce an invalid color string (#555). obj.setTimeout to repeat itself in one millisecond.”> <h1 ID=”head1” style=”color:#FFFFFF. and trigger the Fade function. if (hex. simply add it to an HTML document. window.length is necessary because a single-digit value of hcolor. } } </script> </head> <body onLoad=”Fade(-1). or use larger values of direction for a faster fade that skips some shades.</p> </body> </html> .

and the pos variable. they have been traditionally limited to scrolling within the status line or a form field. Since the W3C DOM allows you to modify any text within the page.setTimeout(“ScrollMessage()”.substring(0. . pos = 0. you easily can create a scrolling message within the contents of any HTML tag. obj = document. . pos). “. The ScrollMessage function handles the actual scrolling. “. obj. which will store the current scrolling position. containing the entire message to scroll. Fading text can be a relatively tasteful effect. msg += “and only a portion is displayed at once.length) + “.80). } This script first defines the msg variable.nodeValue = newtext..substring(pos. However. msg += “Notice that the actual message is larger “.206 Hour 15 This example creates an <h1> heading with the ID head1 to be faded. DHTML removes this limitation.. Here is the script: msg = “This is an example of a scrolling message. Workshop: Creating a Scrolling Message While not as dramatic (or annoying.firstChild. msg. The onLoad event handler in the <body> tag fades the heading in when the page is loaded.substring(0.getElementById(“scroll”).. newtext=newtext. Text that continues to fade in and out can be distracting. Creating the Script The scrolling message will use a JavaScript function to handle each step of the scrolling. scrolling messages have been a fixture on the Web since the advent of JavaScript.length) pos = 0.150). pos++.. especially when it fades in and stops as in this example. window.” + msg. function ScrollMessage() { newtext = msg. You also can use the two links that call the Fade function directly to fade the text in or out. depending on your opinion) as blinking text. if (pos > msg.

it uses the window. This consists of the message from the pos position to the end. “. Finally.4 shows the complete scrolling message example.0 or later. it requires Internet Explorer 5. LISTING 15. This makes the scrolling appear smoother. Keep in mind that timeouts under 150 tend to create messages that move too fast to read. The text is then limited to its first 80 characters to prevent the scrolling message from wrapping on the screen. Listing 15. There is no easy way to achieve this effect in the 4. 15 Since this example modifies text within the Web page. The function then finds the object for the paragraph with the ID attribute “scroll” and assigns the value of its text node to the new text. or Netscape 6 or later. Putting It All Together To test the scrolling message script.setTimeout method to a different value. it starts pos over at zero. As with the other examples in this hour. and the message from the beginning to the pos position.setTimeout method to repeat the ScrollMessage function every 150 milliseconds. The if statement checks whether the end of the message has been reached. Next. a spacer. . since it displays the text in a monospace font.4 The Complete Scrolling Message Example <html> <head> <title>Scrolling Messages in DHTML</title> <script language=”javascript”> msg = “This is an example of a scrolling message. This example will use a <pre> tag.Creating DHTML Text Effects 207 This function first assigns the newtext variable to the latest text for the scrolling area. you can add it to an HTML document and create a text object to scroll.0 browsers. you can speed up or slow down the scrolling message by changing the 150 in the window. the ScrollMessage function increments the pos variable. and if so.

} </script> </head> <body onLoad=”ScrollMessage().nodeValue = newtext. msg += “and only a portion is displayed at once. obj.. function ScrollMessage() { newtext = msg.”> <h1>A DHTML Scrolling Message</h1> <p>The text below is scrolled across the screen using DHTML.</pre> </body> </html> ScrollMessage The onLoad event handler in the <body> tag starts the scrolling message by calling the function. obj = document. Notice the text in the <pre> tag. window. but will be replaced. The <pre> tag has been assigned an ID attribute of “scroll” and will contain the scrolling message. .2 shows the scrolling message in action in Netscape 6. the browser won’t create a text node to hold the scrolling message. load it into a browser.length) pos = 0. if (pos > msg.</p> <hr> <pre ID=”scroll”>This text is required.4 continued msg += “Notice that the actual message is larger “.substring(pos.. “. which will be instantly replaced by the scrolling message.. pos).length) + “. Figure 15.substring(0. .80). pos = 0. msg. To test this example.firstChild. This allows text to be scrolled directly in the body of the page rather than within a form or the status line.substring(0.getElementById(“scroll”).setTimeout(“ScrollMessage()”.. newtext=newtext. This is necessary because if you leave the <pre> tag empty. pos++.100).208 Hour 15 LISTING 15.” + msg.

Q. moving text. Why does the fading text example use timeouts instead of a simple for loop to fade the text? A. fading text. it would look like the color instantly changed rather than faded. change the initial value of the direction variable to a number greater than one.Creating DHTML Text Effects 209 FIGURE 15. and refrain from using them all on the same page. For an even faster display. it would happen very quickly—on a fast computer. you’ve explored some simple examples of using DHTML to add emphasis to text: blinking text.2 The scrolling message example in action. While you could use a for loop to cycle the color through all of the shades of gray. In the next hour. Using timeouts allows you to slow down the effect. 15 Summary In this hour. and a scrolling message. Q&A Q. please use these techniques sparingly. . you’ll further explore how DHTML can be used for animation with a more complex example of animated graphics. To keep your visitors sane.setTimeout statement. the text will move faster. How can I speed up the moving text example? A. If you reduce the delay in the window.

Internet Explorer 5 3.50). Since these fonts have different widths for different letters. Which of the following browsers supports the <blink> tag? a.1000). window.”. the message appears to move at different rates depending on the letters in the message. See Hour 24.setTimeout(“ScrollMessage()”. .setTimeout(Fade().200). Q.setTimeout(“ScrollMessage()”. Netscape 6 b. for example “i” and “W”.500).500).setTimeout(“Fade(). Why doesn’t the scrolling message look as good with proportional fonts? A.setTimeout(Fade(). Netscape 4 c. With a monospace font. window. c. Can I scroll a message vertically. window.5). “DHTML Tips and Tricks. window.setTimeout(“ScrollMessage()”. window. like the credits at the end of a film? A. or several.” for an example of vertical scrolling. Yes..210 Hour 15 Q. b. window. Which of the following is the correct command to set a timeout that calls the Fade function in half a second? a.. Which of the following timeouts in the scrolling message example would result in the fastest scrolling? a. This is a great way to scroll a longer message. 2. Quiz Test your knowledge of the material covered in this hour by answering the following questions.. Questions 1. the letter widths—and the movements—are equal. c. b. while keeping it readable.

b. instead of horizontally. b.Creating DHTML Text Effects 211 Answers 1. 15 Exercises If you’d like to experiment further with this hour’s examples before you move on. 2. • Change the fading text example to fade through several different colors. a delay of 50 milliseconds would scroll the message the fastest. Netscape 4 supports the <blink> tag. The correct statement uses quotation marks around the JavaScript statement to be executed. try the following exercises: • Change the moving text example to move the heading vertically. 3. . c. and the value of 500 milliseconds (half a second). Since shorter delays lead to faster scrolling. but Internet Explorer and Netscape 6 do not. instead of shades of gray. in fact. Too fast to read.

.

By repeatedly changing object positions. or add stylish animation to other dynamic tasks.HOUR 16 Using DHTML for Animation One of the most dramatic applications of DHTML is in the area of animation. This hour covers the following topics: • Choosing appropriate animation methods • Creating JavaScript functions for animation • Completing a simple animation example • Creating an animated navigation bar . you’ll explore the use of DHTML for animation by creating two examples: a simple animated graphic. In this hour. and a menu bar that can be shown or hidden using animation. you can create a moving object within a Web page.

Dynamic HTML You’ve already learned how to use the DOM’s positioning properties to move layers or other objects using DHTML. Animated GIF images consist of two or more images that are rotated over time. it isn’t always the best choice. This technique is handy for animating small drawings. creating a primitive movie. simply by replacing one image with another on the page.0 and later. At its simplest. GIF animations can be more complex—you can even display a series of photographs within the animated GIF. This can be done using the images array. and the GIF format doesn’t support full-color graphics. Animated GIF Images The GIF image standard supports animated images. While DHTML is ideal for some types of animation. technical illustrations that show a process. JavaScript Image Animation You can use JavaScript to create animations similar to animated GIF images. Hour 22. You also can combine DHTML positioning animation with JavaScript imageswapping to create more complicated animations. it would be useful to review the different ways Web pages can be animated. There are also many ways to create animation for the Web. to name a few.0 and later.214 Hour 16 Methods of Web Animation There are many reasons to use animation: novelties and games. and is supported by Netscape 2. a button can become animated when the mouse pointer moves across it. . Unlike GIF animations. However. JavaScript animations can interact with the user—for example. and this was the first type of animation supported by Web browsers. “Creating Complex Animations.” demonstrates an example of this technique. By repeatedly moving an object. or stylish transitions. you can create a simple animation. and Internet Explorer 3. The examples in this hour will demonstrate this. this effect creates most of the flashing advertising banners that distract you from your favorite sites. this creates a large graphic file. Before you create animations using DHTML. part of the Level 0 DOM.

Using vector-based graphics allows complicated animations to be performed with lowbandwidth files. You can place the graphic within a layer and repeatedly change the layer’s position. see Macromedia’s Web site. Web browsers support movies using Microsoft’s AVI format and Apple’s QuickTime format. http://www. However. but is rarely the easiest choice unless the animation needs to interact with the user or with data on the Web. the animation can simply be a set of instructions for drawing the parts of the animation. rather than using a layer. For more information about Flash. . macromedia. For more information about Java. 16 Java Sun’s Java language provides a sophisticated way of creating animations. Creating a Simple Animation As a simple example of animation using DHTML. http://java.sun. Flash has one important advantage over animated GIFs and JavaScript animations: it’s vector-based. effectively moving the graphic across the page. Hour 17. see Sun’s Web site. This means that rather than storing a series of bitmap images. You also can assign an ID attribute to the image itself and move it. you can create a graphic that moves across the screen. rather than a simple animation. and is supported by the latest browsers. If you need a full-scale movie.com/. For example. “Dealing with Browser Differences.” includes a version of this example that works on both 4. but not least. its most popular use is in advertising banners.0 browsers and newer browsers.Using DHTML for Animation 215 Flash Macromedia’s Flash plug-in is becoming ubiquitous on the Web. Movies Last. Like animated GIFs. using a layer makes it easy to adapt this example to work with older browsers. but Flash can create some much more impressive animations. these are much better choices. Java could be used to create an animated stock ticker.com/. It also allows the animation to easily be shown at different screen resolutions while maintaining a size.

10). LISTING 16.”. left:0.com/dhtml/. is available at this book’s Web site: If you’re a better artist than me—most people are—you can also substitute the graphic of your choice. Listing 16. Completing the HTML Document To complete the animation example.left property to the position value.setTimeout(“Move().gif” width=100 height=100 alt=”” border=”0”> </div> </body> </html> .getElementById(“mouse”). It then finds the object for the mouse graphic. top:100. window. } </script> </head> <body onLoad=”Move().1 The Complete HTML Document for the Simple Animation Example <html> <head> <title>Animation with Dynamic HTML</title> <script language=”javascript”> var position=0.gif. window.starlingtech. you simply need to include the Move function in an HTML document and initialize it.216 Hour 16 The graphic for this example. if (position > 650) position = 0. } This function increments the position variable by one.style. visibility:show”> <img src=”mouse. mouse. if (position > 650) position = 0. http://www. Finally. width:100. Creating the Animation Function You can animate the mouse graphic using a single function. Here is the Move function: function Move() { position += 1. document.left = position. and sets its style.setTimeout(“Move().left = position. height:100.10). document.”> <H1>Animation with Dynamic HTML</H1> <HR> <div ID=”mouse” STYLE=”position:absolute. and if it has passed 650.style. resets it to zero.getElementById(“mouse”). function Move() { position += 1.”.1 shows the complete HTML document. the Move function uses the setTimeout method to call itself again in 10 milliseconds.

you can move the menu tree to a navigation bar on the left side of the page. save it and load it into a browser. then declares the Move function. Figure 16. “Creating a Menu Tree. The onLoad event handler in the <body> tag starts the animation by calling the Move function. To try the example. such as a navigation bar. . As another example of animation.” you created a DHTML navigation tree with items that can be expanded or collapsed.Using DHTML for Animation 217 This HTML document includes a <script> section that first initializes the position variable. One feature that can be animated is the process of showing or hiding a section of the page. In Hour 14. The <div> section in the body of the page declares the layer that contains the graphic. 16 Workshop: Creating an Animated Navigation Bar Another use for animation is to add a touch of style to more useful DHTML features.1 shows Netscape’s display of this example as the mouse image moves across the screen.0 or later. This example requires Netscape 6 or later or Internet Explorer 5. and use animation to show or hide it. FIGURE 16.1 The simple animation example in action.

animenu. background-color:aqua.js.html”>Old Products</a><br> <a href=”specs2.”> <b><a ID=”icon” href=”javascript: ShowHide().218 Hour 16 This version of the menu tree also adds another feature: graphic icons instead of the [+] and [-] symbols.”> <a href=”prodlist. Creating the HTML Document The HTML document for this example is largely the same as the original in Hour 14.”>&gt. height:100%.&gt.gif” border=”0” align=”middle”> </a>Specifications<br> <div ID=”specs” style=”display:block. margin-left:2em.html”>Order Form</a><br> <a href=”javascript:Toggle(‘specs’). left:0.”> <img name=”xspecs” width=”20” height=”20” src=”minus.”> <img name=”xproducts” width=”20” height=”20” src=”minus.js”> </script> </head> <body> <div id=”_tree” style=”position: absolute.</a></b><br> <div id=”_indented” style=”margin-left:31px”> <b><a ID=”xproducts” href=”javascript:Toggle(‘products’).html”>Product List</a><br> <a href=”order.gif” border=”0” align=”middle”> </a>Products</b><br> <div ID=”products” style=”display:block. The main differences are that the navigation bar and the body text have been enclosed within <div> tags to allow them to be positioned.&gt. and images are used instead of [+] and [-] icons. Listing 16.} </style> <script language=”javascript” src=”list16-3. LISTING 16.html”>Price List</a><br> .html”>New Products</a><br> </div> <a href=”pricelist. margin-left:2em”> <a href=”specs1.2 The HTML Document for the Animated Navigation Bar <html> <head> <title>Animated Navigation Tree</title> <style> A {text-decoration: none. The script functions will be contained in a separate JavaScript file.2 shows the complete HTML document.

&gt.Using DHTML for Animation 219 LISTING 16.”> <h1>Animated Navigation Tree Example</h1> <p>The navigation tree to the left allows you to expand and collapse items.html”>Service Department</a><br> <a href=”contact3.html”>Marketing Department</a><br> </div> <p> </p> <a href=”javascript:Expand(). save it as an HTML file. Notice that when you first load the document.”> <a href=”contact1.html”>Technical Support</a><br> <a href=”sforum. margin-left:2em. background-color:white.gif” border=”0” align=”middle”> </a>Contact Us</b> <div ID=”contact” style=”display:block. revealing or hiding the navigation bar. margin-left:2em.”>[Expand All]</a><br> <a href=”javascript:Collapse(). height:100%.”>[Collapse All]</a> </div> </div> <div ID=”_text” style=”position:absolute. Figure 16.”> <img name=”xcontact” width=”20” height=”20” src=”minus.</p> </div> </body> </html> 16 To use this example.2 shows Internet Explorer’s initial display of the HTML document.html”>Contact Support</a><br> </div> <b><a href=”javascript:Toggle(‘contact’). icons.2 continued </div> <b><a href=”javascript:Toggle(‘support’). You can hide or show the menu iteself using the &lt.&gt.gif” border=”0” align=”middle”> </a>Support</b><br> <div ID=”support” style=”display:block. but the dynamic functions won’t work until you add the JavaScript in the following sections. You can test it in a browser. The animation you add later will move the body text layer to the right or left.html”>Support Forum</a><br> <a href=”sforum.”> <img name=”xsupport” width=”20” height=”20” src=”minus. left:30px.”> <a href=”tech. the body text layer is positioned to cover most of the navigation bar. .&lt. or &gt. with the menu hidden.html”>Sales Department</a><br> <a href=”contact2.&lt.

• The _indented layer contains all of the menu items and their menus. and contact layers each contain a menu that can be shown or hidden. The text layer has been assigned a white background using the backgroundcolor style property. Additionally. This layer will be hidden under the body text layer and revealed using animation.3 is a diagram showing how these layers are nested. Setting a color is necessary because otherwise the layer would be transparent. specs. here’s a breakdown of the different <div> sections used: • The _tree layer contains the entire navigation tree.2. and would be shown merged with the navigation bar layer underneath.2 The animated navigation bar example with the menu hidden. This layer will be animated to hide and reveal the navigation tree. the products layer has a submenu. . Figure 16. Since this structure can be confusing. Planning Layers If you examine the HTML document in Listing 16. This layer is indented so that no part of the menu is visible until the user chooses to show it.220 Hour 16 FIGURE 16. • The products. • The _text layer contains the body text. you’ll notice that it uses several nested <div> elements to create layers that can be hidden or positioned. support.

either plus. visible=(obj. } } This function first checks whether the item is currently visible. part of the Level 0 DOM.src=”plus. This time. The images for the [+] and [-] icons are available at this book’s Web site. the images array.display!=”none”) key=”x” + item.getElementById(item).images[key]. http://www.com/dhtml/.style. and assigns the visible variable accordingly.3 The menu tree uses several nested layers. _tree <<< or >>> icon Main menu terms Products menu _text _indented products specs Specifications sub-menu Body Text support Support menu 16 contact Contact Us menu Expanding or Collapsing Items The Toggle function is called when the [+] or [-] icons are clicked. is used to change the src attribute of the image for the [+] or [-] icon.gif”.images[key].src=”minus.gif”. document. } else { obj.Using DHTML for Animation 221 FIGURE 16.style.display=”none”.style. Depending on this value.gif or minus. .starlingtech. This function is only slightly different from Hour 14’s example: function Toggle(item) { obj=document. if (visible) { obj. document.gif is assigned as the image source.display=”block”. it either shows or hides the item using its display property. Depending on the status of the menu. and resets the icon.

id. these functions simply used a loop to work on every <div> element in the entire document. If it is there. the loop continues with the next item.images[key]. document. Since you are now using some <div> elements for other purposes.src=”plus.indexOf(“_”) >-1) continue.style.length. This statement checks whether the underscore (_) character appears in the ID attribute for each division. It returns an index if it is found.images[key].gif”. In the HTML document you created earlier.id.getElementsByTagName(“DIV”).id.id.222 Hour 16 Expand and Collapse All The Expand and Collapse functions expand or collapse the entire menu tree at once. document. The indexOf string method searches for a character within a string.style.display=”none”.i++) { if (divs[i].indexOf(“_”) >-1) continue.getElementsByTagName(“DIV”). divs[i]. Here are the Expand and Collapse functions with the added if statements. and –1 if it is not found. for (i=0. } } The ShowHide Function The ShowHide function will be called when the <<< or >>> icon is clicked.i<divs.i++) { if (divs[i].gif”.display=”block”. the <div> elements that are not part of the menu tree have been assigned names beginning with the underscore character.indexOf(“_”) >-1) continue.i<divs. In Hour 14’s example.src=”minus.id. divs[i]. for (i=0.length. and the changes needed to work with the graphic [+] and [-] icons: function Expand() { divs=document. } } function Collapse() { divs=document. to show or hide the entire menu using animation. Here is the JavaScript code for this function: . you need to add a statement to differentiate the two: if (divs[i]. key=”x” + divs[i]. key=”x” + divs[i].

if (thetext. if (position < thetree.innerHTML=”&gt. the MoveRight function is called to slide it to the right.”.getElementById(“_text”). } } 16 This function first finds objects for three elements: the body text layer (_text). theicon.left=position.&gt.offsetWidth + 10 The MoveRight function moves the body text to the right step-by-step.”.offsetWidth + 10) { window. theicon. thetree=document. You can use the offsetWidth property to determine the right edge of the menu tree. thetree=document.setTimeout(“MoveRight().getElementById(“_tree”). If the body text is currently covering the menu. the menu tree layer (_tree) and the <<< or >>> icon (icon).&lt.getElementById(“_text”). The final destination of the animation will be 10 pixels to the right of the menu tree’s right edge: thetree. If the menu is already showing. gradually revealing the menu tree.getElementById(“_tree”). } } . thetext=document.offsetLeft<40) { MoveRight().&gt. and the icon is changed to <<<.style. and the icon is changed to >>>. } else { MoveLeft().”.3).&lt. position +=10. Here is the MoveRight function: function MoveRight() { thetext=document.innerHTML=”&lt. theicon=document. The MoveRight Function When the body text layer moves to the right. thetext. it should start at its current position and move until it is on the right side of the menu tree.Using DHTML for Animation 223 function ShowHide() { if (!document. It then uses an if statement to determine the body text’s current location. the MoveLeft function is called to slide the text back over the menu.getElementById) return.getElementById(“icon”).

224 Hour 16 This function first finds objects for the body text and the menu tree. you simply need to create a JavaScript file with the functions you have created.display!=”none”) key=”x” + item. If the body text layer has not yet reached its final destination of 30 pixels from the edge. The MoveLeft Function The MoveLeft function moves the body text layer to the left step-by-step. The MoveRight function then sets the text layer’s style. hiding the menu tree.left attribute to the position value. LISTING 16. thetext. This global variable will keep track of the body text layer’s current position. It increments the position variable by 10 pixels. Listing 16.setTimeout(“MoveLeft(). Use a larger increment or a smaller timeout to speed things up. position -=10.3 shows the complete JavaScript file.style. visible=(obj. function Toggle(item) { obj=document. The speed of the animation is controlled by two values: the increment in the position += 10 statement. The if statement checks whether the layer has reached its final destination. If not.”. it uses the setTimeout method to call itself again after a 3-millisecond delay. and the timeout value in the setTimeout statement.getElementById(item).left=position. if (position > 30) { window. This function is the opposite of the MoveRight function: function MoveLeft() { thetext=document. } } This function subtracts 10 from the position variable each time it runs. Putting It All Together To complete the animated navigation bar example.3).getElementById(“_tree”). .3 The JavaScript File for the Animated Navigation Bar var position=30. thetree=document.style. MoveLeft is called again using a timeout.getElementById(“_text”).

getElementById(“_text”). position +=10. divs[i].display=”block”.getElementById(“_tree”). theicon.i++) { if (divs[i].Using DHTML for Animation 225 LISTING 16.style.images[key]. document. thetext=document. for (i=0.id. theicon=document.id.src=”plus.i<divs.getElementById(“_text”). } } function ShowHide() { if (!document.”.&lt.setTimeout(“MoveRight().innerHTML=”&lt.getElementsByTagName(“DIV”).3 continued if (visible) { obj.offsetLeft<40) { MoveRight().images[key].src=”plus. document.display=”none”.images[key].src=”minus.gif”. for (i=0.left=position.style. thetext.images[key]. thetree=document. if (position < thetree.gif”.”.length. } } function MoveRight() { thetext=document. document.”.&gt.length.offsetWidth + 10) { window.3). theicon.id. key=”x” + divs[i].style. thetree=document. } } function Collapse() { divs=document.style.i++) { if (divs[i].getElementById(“_tree”). } else { MoveLeft(). divs[i].gif”. document.getElementsByTagName(“DIV”).display=”block”. if (thetext.id.src=”minus.innerHTML=”&gt.i<divs.gif”. } } function Expand() { divs=document.&lt.indexOf(“_”) >-1) continue.style. key=”x” + divs[i]. } else { obj.indexOf(“_”) >-1) continue.display=”none”. } 16 .getElementById(“icon”).getElementById) return.&gt.

4 shows the result in Netscape 6 after the move to the right has completed.js in the same directory as the HTML document you created earlier. with the navigation bar completely revealed. } } This JavaScript file simply consists of the functions you have created.getElementById(“_tree”). To use this file.setTimeout(“MoveLeft(). save it as animenu.style.”. position -=10. and load the HTML document into a browser.3 continued } function MoveLeft() { thetext=document. Figure 16.left=position. FIGURE 16.226 Hour 16 LISTING 16. with the addition of a var statement on the first line to set the initial value for the position global variable.4 The example after the navigation bar has been revealed. thetree=document. if (position > 30) { window. . thetext.3).getElementById(“_text”).

3 use &gt. and troubleshooting. Q. Q. You’ve created a simple example. such as <body>. b.0 browsers. You also can move an object vertically. Since the < and > (greater-than and less-than) symbols are used in the formatting of HTML tags. Hour 17 includes a modified version of this hour’s simple animation example that works in the 4. Why does the example in Listings 16.setTimeout window.animate . window. 16 Q&A Q. by using a separate variable for the vertical position. instead of the > and < symbols? A.” you’ll learn some advanced DHTML techniques. Congratulations—you’ve reached the end of Part IV! In Part V.2 and 16. HTML requires that you use coded versions when you want to display the actual symbols. Yes.0 browsers? A. as well as horizontally. and &lt. Simply create separate position variables for each object and update them all in the Move function. “Learning Advanced Techniques. Can I animate more than one object at once? A. using downloadable fonts. Quiz Test your knowledge of the material covered in this hour by answering the following questions.repeat window. Questions 1. Yes. Which JavaScript method is typically used to repeat an animation function? a. c. although you’ll need separate animation functions for Netscape and Internet Explorer. you’ve learned how DHTML’s positioning features can be used to create animation. Can objects be animated in the version 4. and a more complex example that hides and shows a navigation bar.Using DHTML for Animation 227 Summary In this hour. creating dynamic forms. including dealing with older browsers.

3. try the following exercises: • Modify Listing 16. c. 3.1 to place two mice on the screen on different rows.setTimeout method is typically used to repeat animation functions. • Create a simplified version of Listing 16.3 that shows or hides the navigation bar without animation.style. layer.left=100. c. Which of the following is the correct command to set the horizontal position of a layer to the 100th pixel from the left? a. It is defined last. each with a different speed. layer. . Since the example doesn’t explicitly set the z-index properties of the layers. Answers 1. It has a lighter background color.x=100. b. a. The z-index properties are set explicitly. layer. b. b. the layer defined second (the body text layer) appears on top. The style. 2.left property determines a layer or other object’s horizontal position.228 Hour 16 2. What causes the body text layer to obscure the navigation layer in Listing 16.2? a. b. The window.left=100. Exercises If you’d like more practice with DHTML before you move on to Part V.

PART V Learning Advanced Techniques Hour 17 Dealing with Browser Differences 18 Using DHTML with Forms 19 Using Dynamic Fonts 20 Troubleshooting DHTML .

.

0 browsers.HOUR 17 Dealing with Browser Differences The W3C DOM has revolutionized DHTML by making a single standard that both Netscape and Microsoft have committed to support. You’ll also learn how to adapt DHTML applications to work on the version 4. Nevertheless. you will need to account for all of these possibilities. In this hour. Welcome to Part V! In the next four hours. you’ll learn how to understand the basic differences between the DHTML browsers. If your page relies on DHTML. This hour covers the following topics: • Differences between DHTML browsers • Detecting the current browser • Detecting feature support • Writing cross-browser DHTML scripts . neither supports it perfectly yet. and many users use older browsers. you’ll learn some advanced aspects of DHTML. and how to write scripts that detect the current browser.

which is supposed to contain a concise list of information about the user’s browser. You can do this in one of two ways: • Detecting the exact browser in use (browser sensing) • Detecting whether a feature is supported (feature sensing) Browser Sensing The most obvious way to detect which browser is in use is to use the navigator object. neither browser supports 100% of the W3C DOM standard. if you write an application for one of these browsers the chances are good it will work on the other. Since both Internet Explorer 5 and later. At the very least. Things are different now with the W3C DOM. Using this technique. the chance increases that you’ll run into a difference between the browsers. test your script in as many different browsers as possible.0 browsers were the latest thing. there was no chance at all it would work on Netscape 4.1 shows a simple script that displays the values of several navigator properties. and deal with differences by writing code for different browsers. you can use JavaScript to detect the user’s current browser or the features it supports. you should have the latest versions of Netscape and Internet Explorer available. Listing 17. However. .0.0. As you use more specific properties and attributes. as well as the latest. If you wrote an application using DHTML for Internet Explorer 4. Second. There are two key things you can do to make sure the latest DHTML browsers support your scripts: First. there were major differences between their support for DHTML. and Netscape 6 and later are based on this standard. Detecting Browsers If you plan to support more than one browser—or even if you’re restricting your page to certain browsers—you’ll need a way to detect which browser is in use. you can support older browsers.232 Hour 17 • Supporting older browsers • Creating cross-browser animation DHTML Browser Differences Back when the version 4.

starlingtech. you might think that the code name.platform). </p> <ul> <script LANGUAGE=”JavaScript”> document.com/dhtml/.appName). version. app name. document. Unfortunately. or download the listings for this hour. Today’s browsers have strange ways of supporting the navigator properties: • Internet Explorer 4 and later list their code name as Mozilla.appVersion). document. at this book’s Web site: http://www. and other properties would differ with each browser you tried. </script> </ul> <hr> </body> </html> 17 To test this example.1 shows this example as displayed by Internet Explorer 5. . document. Figure 17.write(“<li><b>App Name:</b> “ + navigator. If you haven’t used the navigator object before. and their user agent as Mozilla/4. Netscape’s codename. You can try this example online.write(“<li><b>User Agent:</b> “ + navigator.5. save it and load it into a browser. followed by the correct application and version information.Dealing with Browser Differences 233 LISTING 17.write(“<li><b>Platform:</b> “ + navigator. document. you have only to look at Internet Explorer’s display of the example to realize that something’s amiss.0 (compatible).language).write(“<li><b>Code Name:</b> “ + navigator.userAgent).1 Displaying Information About the Browser <html> <head> <title>Browser Information</title> </head> <body> <h1>Browser Information</h1> <hr> <p> The <b>navigator</b> object contains the following information about the browser you are using.write(“<li><b>App Version:</b> “ + navigator. Try at least two different browsers and notice the differences in the display.appCodeName). document.write(“<li><b>Language:</b> “ + navigator.

many Web designers made their pages check specifically for Netscape. it’s sometimes necessary to use this technique when dealing with cutting-edge DHTML.1 Internet Explorer displays the browser information script. Internet Explorer has released version 7.) FIGURE 17. Now suppose that Netscape has released version 7. you can see that browser sensing isn’t the easiest way to support different DHTML browsers. is the open-source project that Netscape 6 is based upon. With the advent of frames. Although you can write a script to deal with these quirks.0. (Netscape 5. also known as Mozilla. • Netscape 6 lists its version number as 5. and other features. Feature Sensing Suppose you’ve used browser sensing to check for Internet Explorer 5 or Netscape 6.234 Hour 17 • Internet Explorer 5 and later list their app version and user agent as version 4.5. it made Internet Explorer’s user agent similar to Netscape’s to allow these pages to work without modification. Chances are. one or more of these new browsers wouldn’t work with your script. Nonetheless. The reasons for Internet Explorer’s strange navigator values are rooted in the browser wars.0. When Microsoft supported these features. . DHTML. although the correct version number appears in parentheses. and Opera has released a version that supports DHTML better than either one.

2 shows the feature sensing example. By detecting the specific DHTML features you plan to use. Using Feature Sensing Using feature sensing. 17 While actually using the document.2 Using Feature Sensing <html> <head> <title>Browser Feature Sensing</title> </head> <body> <h1>Browser Features</h1> <hr> <p>The information below was obtained using feature sensing: </p> <ul> . LISTING 17.getElementById method. Listing 17. as you’ll see later in this hour. You can also use this technique to create a version of the script for older browsers.getElementById method exists. or any other method or object your script will use. you can determine whether the current browser supports them—without necessarily knowing which browser it is.getElementById method on an older browser will cause an error. You’ve already seen an example of browser sensing in several of the examples in this book: if (!document. If it doesn’t exist. If you include a statement like this before you actually use the document. you can use feature sensing rather than browser sensing. it returns from a function.getElementsByTagName.Dealing with Browser Differences 235 To account for situations like these.getElementById) return. you can create a simple script that checks whether the current browser supports the W3C DOM or one of the older DHTML standards. checking for it in this manner will not. You can use the same technique with document. Be sure you don’t include any parentheses or parameters to avoid calling the function. This statement checks whether the document. you can avoid error messages in older browsers.

if (document. FIGURE 17.all) { document.</li>”). </script> </ul> <hr> </body> </html> This example checks for three features: the document. Figure 17.all array”). and appears to support the W3C DOM.</li>”).write(“<li>The W3C DOM is not supported.</li>”). and the document.write(“<li>document.236 Hour 17 LISTING 17.2 shows Netscape 6’s display of this example.all array supported by Internet Explorer 4. and is most likely Internet Explorer. and is most likely Netscape 4. document.write(“. if (document. .write(“<li>This browser supports the layers array”).write(“.getElementById method for DOM-compliant browsers. the document.getElementById) { document.2 continued <script LANGUAGE=”JavaScript”> if (document.</li>”). document.layers) { document. } else document.write(“<li>This browser supports getElementById”).layers array supported by Netscape 4.write(“.”). document.write(“<li>The layers array is not supported.2 The feature sensing example as displayed by Netscape 6.all is not supported. } else document.”).write(“<li>This browser supports the document. } else document.

As a bare minimum. there are still differences between these browsers. While the W3C DOM standard allows you to create DHTML scripts that will work on both Internet Explorer 5 and Netscape 6 and later. Both Netscape 4. and Internet Explorer 5 on the same computer. to allow you to test your pages in these browsers. Netscape 6. you can add support for these browsers to your scripts. In fact. you should make sure your DHTML scripts account for the 4. At the very least. you can run into trouble with one browser or another.0 browsers.0 include limited DHTML features. Testing in Multiple Browsers A big part of writing cross-browser DHTML is testing your scripts in multiple browsers. If you wish. 17 Accommodating Older Browsers While the latest DOM-compliant browsers are popular and dominate the market.0 and Internet Explorer 4. . and make your script inactive if it is not supported. prevents error messages. you can go one step further. This is simple to do. and be sure your pages work with limited functionality in older versions. you should support the latest Internet Explorer and Netscape versions. and allows users with older browsers to use your page without its dynamic features. Unfortunately.Dealing with Browser Differences 237 Writing Cross-Browser DHTML Before you embark on a DHTML project. there are differences between browsers of the same version on different platforms. and it’s hard to test Macintosh. you should consider which browsers to support. Windows. and Unix versions of browsers. One easy way around this is to publish a beta version of your Web site and allow users on different browsers and platforms to test it and give you feedback before you release the final version. and with a small amount of extra programming. you can use feature sensing to determine whether the DOM is supported. To avoid crashing browsers. there are still a number of users out there using Netscape 4 or Internet Explorer 4. It’s easy to set up Netscape 4. Even if you follow the W3C standards. it’s difficult to set up multiple versions of Internet Explorer on the same computer. such as Windows and Macintosh.

rather than obj.all array includes elements for every object on the page. While this includes <div> and <span> elements like Netscape 4. but fortunately it also supports the CSS positioning standard—using <div> or <span> elements with positioning attributes to define layers.all array.getElementById(“page2”). Internet Explorer 4 includes the document.visibility. suppose you have defined a layer in a <div> tag with the ID attribute “page2”. Internet Explorer 4 DHTML Internet Explorer 4 was the first version to include DHTML features. it also includes other objects on the page and is not limited to layers.style.” introduces layers and the methods of defining them and working with their properties. it centered on the use of layers. . For example. The following statement would find the object for the layer in DOM-compliant browsers: obj=document.visibility. The document. the visibility property of the layer referenced above would be obj. “Creating Positionable Elements (Layers). Hour 6. The Netscape 4 equivalent is to look up the element with the name “page2” in the layers array: obj=document. For example. Netscape 4 doesn’t support the W3C DOM or the getElementById method. it stores information about each defined layer in the document.layers array. If you use a <div> or <span> tag to define a layer. Instead.layers[“page2”]. Netscape 4 includes a <layer> tag to define layers. The other key difference is that Netscape does not use the style object under the layer object. and Microsoft chose to create their own standard. Rather than using Netscape’s layers array.238 Hour 17 Netscape 4 DHTML When DHTML was first introduced in Netscape. However. Netscape 4 will recognize it as well as newer browsers.

it won’t attempt to use document. to find the object for a layer or other element with the ID attribute “page2” in Internet Explorer 4. But if you can use layers for your application.getElementById) return document. you can simulate the document. return false. If you’ve previously created a DHTML script for Internet Explorer 4.all[“page2”].. You could control the visibility of the object in this example using the obj. else if (document. else if (document. You can create an alternative function that works the same way.all array: obj=document. Internet Explorer 4 supports the style object. Here is the code for the GetObject function: function GetObject(id) { if (document. Creating Cross-Browser Functions There are some things that the 4. } } Internet Explorer 5.style.layers[id].Dealing with Browser Differences 239 For example.getElementById(id).0 browsers simply can’t do: for example. else { alert(“DHTML support not found.0 browsers.all array for backward compatibility.5 support the document. the getElemementById function is often used to find objects. Since this function checks for the getElementById method first.all[id].all on these newer browsers. 17 Finding Layer Objects In DHTML scripts for W3C DOM browsers.all array in the DOM-compliant browsers by using document. you can look up the ID attribute in the document.all) return document. Unlike Netscape 4.getElementsByTagName(“*”). adding or deleting nodes from the DOM. it’s easy to adapt the script to support both older and newer browsers. but also supports the 4. .visibility property.layers) return document.”).0 and 5.

layers array.style. For DHTML scripts that use the getElementsByTagName method.all array.left obj.left (Internet Explorer 4 or later. the function displays an error message and returns a false value.getElementById(id). often you need to deal with style properties. since only layers are stored in the layers array. if you need to change the horizontal position of the object obj.all) return document. • For Internet Explorer 4. • For Netscape 4. If none of these features are detected. Otherwise. the correct properties are: • • obj.style.style.all array provides the same functionality for Internet Explorer 4.”). it returns an object that can be used just like the getElementById result. For example. it returns the appropriate object from the document.layers) return document. An easy alternative is to create a GetStyleObject function that returns the appropriate object for the style properties: function GetStyleObject(id) { if (document.layers[id]. } } . and uses a series of if statements and feature sensing to return one of three values: • For DOM-compliant browsers.getElementById) return document.240 Hour 17 This function accepts the ID attribute of a layer as its parameter. you can’t simply add style to the result of the GetObject function. it returns the appropriate object from the document. the document. return false. else if (document. There is no way to obtain a list of HTML elements in Netscape 4.all[id]. it returns the result of the getElementById method. Finding Style Objects While the GetObject function above will work in some cases. else { alert(“DHTML support not found. else if (document. Netscape 6 or later) (Netscape 4) Since the style object isn’t used by Netscape 4.

Dealing with Browser Differences

241

This function is similar to the GetObject function, but returns the style object for DOM browsers or Internet Explorer 4, and returns the layer object directly for Netscape 4. Thus, if you include this function in a document, you can change the horizontal position of the layer1 layer with two simple statements:
obj=GetStyleObject(“layer1”); obj.left=300;

By including the GetObject or GetStyleObject functions, or both if needed, you can easily work with layers for both 4.0 browsers and newer DOM-compliant browsers.

Workshop: Supporting Old and New Browsers
As a demonstration of the GetStyleObject function, you can use it to make a version of the simple animation example from Hour 16, “Using DHTML for Animation,” that works on both 4.0 browsers and newer browsers. The example already uses a layer to enclose the mouse.gif graphic. This makes it easy to support the 4.0 browsers: simply add the GetStyleObject function to the <script> section in the header, and use this function instead of the getElementById method. Listing 17.3 shows the cross-browser version of the animation example. LISTING 17.3 The Complete Cross-Browser Animation Example

17

<html> <head> <title>Animation with Dynamic HTML</title> <script language=”javascript”> var position=0; function GetStyleObject(id) { if (document.getElementById) return document.getElementById(id).style; else if (document.layers) return document.layers[id]; else if (document.all) return document.all[id].style; else { alert(“DHTML support not found.”); return false; } } function Move() { position += 1; if (position > 650) position = 0;

242

Hour 17

LISTING 17.3

continued

obj = GetStyleObject(“mouse”); obj.left = position; window.setTimeout(“Move();”,10); } </script> </head> <body onLoad=”Move();”> <H1>Animation with Dynamic HTML</H1> <HR> <div ID=”mouse” STYLE=”position:absolute; left:0; top:100; width:100; height:100; visibility:show”> <img src=”mouse.gif” width=100 height=100 alt=”” border=”0”> </div> </body> </html>

In this listing, the GetStyleObject function is defined at the beginning of the <script> section. The Move function uses GetStyleObject to get the appropriate object for the current browser, and sets the animation to its next position. This modified example should work in a nearly identical fashion on Netscape 4.0, Internet Explorer 4.0, and the new DOM-compliant browsers. Figure 17.3 shows Netscape 4’s display of the animation.
FIGURE 17.3 Netscape 4 shows the cross-browser animation example in action.

Dealing with Browser Differences

243

Summary
In this hour, you’ve learned how to deal with differences between browsers, including the latest DHTML browsers, as well as older browsers with limited DHTML support. You’ve also adapted an animation example to work on older browsers, as well as the latest ones. In the next hour, you’ll learn how DHTML can be used with forms. This will allow you to change a form dynamically based on information the user enters, a useful technique for online order forms.

Q&A
Q. Aren’t there any other browsers that support DHTML? A. Yes. Opera, http://www.opera.com/, has limited DHTML support. If you use feature sensing rather than browser sensing, you can support this browser in your DHTML scripts. Q. I know exactly which browsers support the feature I’m using. What’s wrong with using browser sensing? A. The main problem is that the list of browsers that support a feature can change with every browser release, and you would have to modify your script each time. Q. Does anyone really still use the version 4.0 browsers? A. According to Internet.com’s statistics at this writing, nearly 20% of Web users are still using Netscape 4 or Internet Explorer 4. Statistics vary for different sites, but chances are enough of your users use older browsers that you shouldn’t ignore them.

17

Quiz
Test your knowledge of the material covered in this hour by answering the following questions.

Questions
1. Which of the following is the best all-around technique for determining which type of DHTML to use in a script? a. Browser sensing b. Feature sensing c. Assume everyone uses Internet Explorer

244

Hour 17

2. Which browser supports the layers array? a. Internet Explorer 4 b. Netscape 4 c. Netscape 6 3. What would be the navigator.appCodeName value for Internet Explorer 5.5 under Windows? a. Mozilla b. IE5 c. IE4

Answers
1. b. Feature sensing is the best way to quickly determine which type of DHTML to use. 2. b. Only Netscape 4 supports the layers array. 3. a. Internet Explorer 4.0 and later report the code name Mozilla to indicate compatibility with Netscape.

Exercises
If you’d like to practice cross-browser scripting before you move on to the next hour, try the following exercise: • There is an example of using JavaScript to position layers in the Workshop section of Hour 6. Use the functions you created in this chapter to modify that example to work with version 4.0 browsers.

HOUR

18

Using DHTML with Forms
In the previous hours of this book, you’ve learned how DHTML can make dramatic changes to Web pages in real time. Forms, some of the most common Web page elements, also can make use of DHTML. In this hour, you’ll learn some ideas for making forms dynamic using DHTML, and create several examples of forms that can be modified automatically depending on the user’s choices. This hour covers the following topics: • Using dynamic forms • Modifying form elements • Adding elements to a form • Creating a dynamic order form

246

Hour 18

Dynamic Forms
While forms are hardly the most exciting thing the Web can do, they’re one of the most practical. Order forms, feedback forms, and registration forms abound on the Web. Forms are also considered one of the uglier parts of the Web by designers. A page filled with white blanks isn’t the best example of effective design, and many aspects of form appearance can’t be controlled using style sheets. You can alleviate some of the boredom of forms using DHTML. Your forms can show only the fields that are needed based on a choice the user makes, and can expand and shrink as needed.

When using DHTML with forms, you can easily create a form that relies on DHTML, and won’t work in older browsers. If you do, be sure to provide an alternative for browsers that don’t support DHTML.

Modifying Form Elements
One problem that traditional Web forms share with printed paper forms is that they can’t change to ask only for the required information. For example, suppose a response form asks the user whether they wish to be contacted by mail, by e-mail, or by phone. The form would need separate fields for the mailing address, e-mail address, and phone number, even though all of them won’t be used. Using DHTML, you can create a form that prompts for this information and displays only the needed fields.

Creating the JavaScript Function
To create a dynamic form, you will use three separate <div> elements, one for each of the contact options. The changes to the form will be made by the Display function. This function accepts the name of one of the <div> elements, shows it, and hides the others.
function Display(which) { ma=document.getElementById(“mail”); em=document.getElementById(“email”); ph=document.getElementById(“phone”); if (which==”mail”) ma.style.display=”block”; else ma.style.display=”none”; if (which==”email”) em.style.display=”block”; else em.style.display=”none”; if (which==”phone”) ph.style.display=”block”; else ph.style.display=”none”; }

Using DHTML with Forms

247

This function accepts a parameter, which, and tests it. The if statements set the display property for the selected element to block, and the display properties for the other elements to none.

Creating the HTML Document
To complete the example, you need an HTML document with the three <div> elements and a way for the user to choose which one to display. Listing 18.1 shows the complete HTML document.

As usual, you can download the HTML documents for the examples in this hour from this book’s Web site: http://www.starlingtech.com/dhtml/.

LISTING 18.1

The HTML Document for the Dynamic Form

<html> <head> <title>Modifying Forms with DHTML</title> <script language=”javascript”> function Display(which) { ma=document.getElementById(“mail”); em=document.getElementById(“email”); ph=document.getElementById(“phone”); if (which==”mail”) ma.style.display=”block”; else ma.style.display=”none”; if (which==”email”) em.style.display=”block”; else em.style.display=”none”; if (which==”phone”) ph.style.display=”block”; else ph.style.display=”none”; } </script> </head> <body> <h1>Modifying Forms with DHTML</h1> <p>The form below changes depending on the radio button selected.</p> <hr> <form name=”form1”> <p>How would you like us to contact you?</p> <input type=”radio” name=”type” value=”mail” checked onClick=”Display(‘mail’);”> By mail <input type=”radio” name=”type” value=”email” onClick=”Display(‘email’);”> By email

18

248

Hour 18

LISTING 18.1

continued

<input type=”radio” name=”type” value=”phone” onClick=”Display(‘phone’);”> By phone <br> <div ID=”mail” style=”display:block;”> <b>Address 1:</b> <input type=”text” name=”address1” size=”25”> <br> <b>Address 2:</b> <input type=”text” name=”address2” size=”25”> <br> <b>City:</b> <input type=”text” name=”city” size=”14”> <b>State:</b> <input type=”text” name=”state” size=”5”> <b>Zip:</b> <input type=”text” name=”zip” size=”9”> </div> <div ID=”email” style=”display:none”> <b>Email address:</b> <input type=”text” name=”email” size=”25”> </div> <div ID=”phone” style=”display:none”> <b>Phone:</b> <input type=”text” name=”phone” size=”15”> </div> </form> </body> </html>

This document includes a set of radio buttons with onClick event handlers that call the Display function. It also includes the three <div> elements—mail, email, and phone. To test this document, load it into a Web browser. This example requires Netscape 6 or later, or Internet Explorer 5 or later, although it could be adapted to work with older browsers.

If you use a form like this, keep in mind that some of the form fields won’t be available to users on non-DHTML browsers. Make sure you provide an alternative form for these browsers.

Figure 18.1 shows Netscape’s display of the document while the By Mail option is selected. As you select other options, the bottom portion of the form changes accordingly.

button=document.1 The dynamic form example in action. items++. newnode.innerHTML=newitem.createElement(“span”). The following JavaScript code declares a variable. 18 Creating the JavaScript Function The form will initially be displayed with one text field. A button will allow the user to add one or more similar text fields. div. and defines the AddItem function to add items: var items=1. newnode=document. items. As an example. labeled Item 1. to keep track of the number of items.getElementById(“add”). function AddItem() { div=document.Using DHTML with Forms 249 FIGURE 18.getElementById(“items”). you can create a simple form that allows fields to be added at the click of a button. newitem=”<b>Item “ + items + “: </b>”.insertBefore(newnode. newitem+=”<input type=\”text\” name=\”item” + items. Adding Form Elements Using DHTML. } .button). newitem+=”\” size=\”45\”><br>”. you also can create forms that expand to fit the quantity of information the user wishes to enter.

newitem+=”<input type=\”text\” name=\”item” + items. which will be inside the <div> element. newitem=”<b>Item “ + items + “: </b>”. Next. } </script> </head> <body> <h1>Adding Form Elements</h1> <p>The form below allows you to add elements dynamically.” for more information about this method. items++.button).2 shows the complete HTML document. newnode=document. Listing 18. function AddItem() { div=document.createElement(“span”). newitem+=”\” size=\”45\”><br>”.</p> . “Working with DOM Properties and Methods. newnode. and the existing child node it should be inserted before. div.getElementById(“items”). the newitem string is created with the HTML for the new item. you need to create an HTML document that defines the form.innerHTML=newitem. and the button that allows the user to add items. button=document. It next increments the items variable.insertBefore(newnode.2 The Complete Example of Adding Form Elements <html> <head> <title>Adding elements to a form</title> <script language=”javascript”> var items=1.250 Hour 18 The AddItem function first finds the object for the <div> element with the ID attribute “items”. and the insertBefore method inserts the new node into the <div> element. including the <div> element to add items to. The createElement method is used to create a new <span> element containing the HTML in newitem. See Hour 7. LISTING 18. It also finds the object for the add items button. The insertBefore method has two parameters: the new child node to insert.getElementById(“add”). including a label and the <input> tag. Completing the HTML Document To complete this example.

This button’s onClick event handler calls the AddItem function. FIGURE 18. The <form> section includes the <div> with the ID attribute “items”.2 shows Internet Explorer’s display of this example after several items have been added to the form. Figure 18.Using DHTML with Forms 251 LISTING 18.2 continued <hr> <form name=”form1”> <div ID=”items”> <b>Item 1:</b> <input type=”text” name=”item1” size=”45”> <br> <input type=”button” value=”Add an Item” onClick=”AddItem(). 18 .2 The form with added items. containing the first item field and the Add an Item button.” ID=”add”> </div> </form> </body> </html> The <script> section in this document initializes the items variable and defines the AddItem function.

PHP. CGI programs can be written in any language supported by the server. created with the <input type=”submit”> tag. If you’d like to learn more about Perl. • A Submit button. Popular CGI languages include the open-source Perl and PHP languages. Some can be downloaded and used on your server. and other server-side languages.” If you’d rather not learn a whole new language just to accept data from your forms. you need certain components in your HTML document: • An action attribute in the <form> tag that specifies the URL of the CGI program. Since JavaScript and DHTML work on the client. When this button is clicked. To use a CGI script. you’ll find a list of useful Web sites in Appendix A. you would use a CGI (common gateway interface) script or program to accept the data. and Sun’s JSP (JavaServer Pages).com/ If you’d like to learn more about CGI.resourceindex. Which one you use depends on the needs of the CGI script. the CGI script will execute on the server and receive the data from the form. by Rafe Colburn. • A method attribute in the <form> tag that specifies one of the two methods for communicating with CGI scripts.252 Hour 18 Accepting Data from Forms While you can use DHTML and JavaScript to add interactive features to forms as in this hour’s examples. “Other JavaScript and DHTML Resources. while others are set up as services that you can use on their servers. One good one to get started with is Sams Teach Yourself CGI in 24 Hours. there are thousands of free CGI scripts available. GET or POST. Microsoft’s ASP (Active Server Pages). There’s even a server-side version of JavaScript that can be used for this purpose. you also need a way to accept the data from the form. Typically. . CGI isn’t a language. but rather a standard for executing scripts on Web servers. You can find an excellent collection of links to these resources at the CGI Resource Index: http://cgi. a number of books are available. they don’t provide a way to accept data from forms.

if (a) obj.style.innerHTML=newitem. Showing the Ship-to Address Hiding or showing the ship-to address is simple. items++. but this time the newitem variable includes HTML to define a quantity field as well as an item field for each new item: var items=1. button=document.Using DHTML with Forms 253 Workshop: Creating a Dynamic Order Form As a final demonstration of the power of DHTML in working with forms. newitem+=”<b>Item: </b>”. newitem+=”\” size=\”45\”><br>”.getElementById(“shipto”).display=”none”. depending on the value of the parameter (a).button).2. as in the previous example. } 18 As before.style.createElement(“span”). This form will have two dynamic components: the ability to add items. newitem+=”<input type=\”text\” name=\”qty” + items.display=”block”.getElementById(“add”). Adding Items to the Form The AddItems function is similar to the one in Listing 18. the createElement method is used to create a new <span> element containing the HTML. newitem=”<b>Qty: </b>”. function AddItem() { div=document. and a ship-to address form that displays only when it is needed. The Show function accepts a parameter indicating whether to show or hide the ship-to fields: function Show(a) { obj=document. else obj. div. newnode. } The <div> element with the ID attribute “shipto” will contain the address fields. newitem+=”\” size=\”3\”> “. newitem+=”<input type=\”text\” name=\”item” + items. you can create a dynamic order form.getElementById(“items”). . newnode=document. The insertBefore method then is used to add the item immediately before the button.insertBefore(newnode. The if statements change the display property for the <div> element to block or none.

if (a) obj. newnode=document. } </script> </head> <body> <h1>Order Form</h1> <hr> <form name=”form1”> <b>Bill to:</b><br> <b>Name:</b> <input type=”text” name=”customer” size=”20”><br> <b>Address 1:</b> <input type=”text” name=”addr1” size=”20”><br> <b>Address 2:</b> <input type=”text” name=”addr2” size=”20”><br> <b>City:</b> <input type=”text” name=”city” size=”15”> <b>State:</b> <input type=”text” name=”state” size=”4”> <b>Zip:</b> <input type=”text” name=”zip” size=”9”> <hr> <b>Ship to:</b><br> .3 shows the complete HTML document. Listing 18. newitem+=” ‘ size=’3’> “. button=document.display=”none”. function AddItem() { div=document.getElementById(“shipto”). LISTING 18. newitem=”<b>Qty: </b>”.getElementById(“add”). } function Show(a) { obj=document. newitem+=”<input type=\”text\” name=\”item” + items. div.getElementById(“items”). else obj.innerHTML=newitem. newitem+=”\” size=\”45\”><br>”.254 Hour 18 Completing the HTML Document To complete this example.3 The Complete Dynamic Order Form <html> <head> <title>Dynamic Order Form</title> <script language=”JavaScript”> var items=1. newitem+=”<input type=’text’ name=’qty” + items.createElement(“span”).style.style. all you need to do is add the JavaScript functions you created to an HTML document. items++. newitem+=”<b>Item: </b>”. newnode.display=”block”.insertBefore(newnode. and add the form elements.button).

. hidden by default.3 shows the dynamic order form in action. The ship-to fields are enclosed in a <div> element with the style attribute display:none. This example requires Netscape 6 or later.Using DHTML with Forms 255 LISTING 18.”> <br> <b>Name:</b> <input type=”text” name=”shipname” size=”20”><br> <b>Address 1:</b> <input type=”text” name=”shipaddr1” size=”20”><br> <b>Address 2:</b> <input type=”text” name=”shipaddr2” size=”20”><br> <b>City:</b> <input type=”text” name=”shipcity” size=”15”> <b>State:</b> <input type=”text” name=”shipstate” size=”4”> <b>Zip:</b> <input type=”text” name=”shipzip” size=”9”> </div> <hr> <div ID=”items”> <b>Qty:</b> <input type=”text” name=”qty1” size=”3”> <b>Item:</b> <input type=”text” name=”item1” size=”45”> <br> <input type=”button” value=”Add an Item” onClick=”AddItem().”> <b>Same Address</b> <input type=”radio” name=”shipopt” value=”other” onClick=”Show(1). to use this example on a live site. To test this script. <form> The first item field and the Add an Item button are enclosed in the <div> element with the ID attribute “items”.0 or later.. load it into a browser. or Internet Explorer 5.”> <b>Other Address</b> <div ID=”shipto” style=”display:none. The button’s onClick event handler calls the AddItem function to add another item. you’ll need a CGI script to handle the form submission when the Continue button is clicked. The section defines two radio buttons that call the Show function.” ID=”add”> </div> <hr> <input type=”submit” value=”Continue. .”> </form> </body> </html> 18 The <script> section of this document defines the AddItem and Show functions.3 continued <input type=”radio” name=”shipopt” value=”same” checked onClick=”Show(0). Figure 18. While you can test the interactive DHTML features.

. Can I create a script that adds items to a form that works in the version 4. you’ll learn how to use dynamic fonts. Since this example manipulates the DOM. This isn’t something JavaScript or DHTML can do. How do I store the results of a form in a file or database? A.256 Hour 18 FIGURE 18. Summary In this hour. a feature of the CSS standard that allows you to customize fonts and allow them to be downloaded with your HTML documents. you’ve learned some ways DHTML can be used to add functionality to Web forms.0 browsers? A. No. You’ve created simple examples including a dynamic order form. You’ll need a CGI script or other server-side application to accept the results of a form. it will only work in DOM-compliant browsers. In the next hour.3 The dynamic order form in action. Q. Q&A Q.

immediately before the button object? a. div.Using DHTML with Forms 257 Q. Which event handler is called when a radio button is selected? onClick onSelect onRadio Answers 1. Questions 1.insertBefore(newnode. a. a. Which of the following is the correct command to insert the newnode object in the div object.button). c. b. b. and none to hide it. b. 2. b. This is JavaScript’s way of escaping the quotation character. It is used to include quotation marks within a string.insertBefore(newnode). The insertBefore method is used on the container to insert the new object into it. meaning JavaScript doesn’t interpret it as a quotation mark. Quiz Test your knowledge of the material covered in this hour by answering the following questions. 3. b. The display property accepts the value block to display an object in the default way. div. Why is the combination \” used in the examples? A. a. and its parameters are the new node and the object to insert it before. 2. c.insertBefore(newnode). button. c. Which two values are used in an object’s display property to display it or hide it? display block 1 and none 18 and none and 0 3. . The onClick event handler is called when a radio button is selected.

1. • Add a Payment section to the form in Listing 18. Include radio buttons to choose credit card or check payment.258 Hour 18 Exercises If you’d like further practice creating dynamic forms before you move on. .3. and make the form dynamically display either a credit card number field or a check number field according to the selected option. and create a section of the form to be displayed when that choice is selected. try the following exercises: • Add a fourth choice to the radio buttons in Listing 18.

These give you total control over fonts. margins. although the current state of browsers makes the use of this feature a bit risky. you learned how CSS style sheets can give you powerful.HOUR 19 Using Dynamic Fonts In Part III of this book. and other aspects of your Web pages’ appearance. which can be downloaded with a Web page. standardized control over the fonts. This hour covers the following topics: • The basics of dynamic fonts • The two dynamic font standards • Defining dynamic fonts • Using Microsoft’s WEFT program • Using dynamic fonts in Web pages . sizes. spacing. In this hour. you’ll learn how to go one step further by using dynamic fonts.

You’ll also learn which browsers support dynamic fonts. Netscape and Microsoft developed completely different standards for dynamic fonts. Internet Explorer for Macintosh doesn’t support downloadable fonts. it makes a nice luxury for those browsers that do support it when used carefully. . They can then be used by name in CSS styles. Dynamic Fonts and Browsers Unlike the DOM. you’re still relying on every user having the fonts you use available.260 Hour 19 How Dynamic Fonts Work While CSS allows you a great deal of versatility in selecting fonts for your Web pages.72 support Truedoc fonts. similar to the way you link an external style sheet. and some versions of both of their browsers don’t support them at all. progress will have to be made before you can rely on dynamic fonts. Unfortunately. each standard doesn’t correspond to a line of browsers as you might expect—and some major browsers don’t support dynamic fonts at all. • Internet Explorer: Versions 4. and Microsoft’s Web Embedding Fonts Tool (WEFT). Both Netscape and Microsoft have developed ways to escape this limitation. while this sounds like a grand idea. Part of the original buzz in Netscape’s debut of dynamic HTML was the dynamic fonts feature.0 and later for Windows support WEFT fonts. two standards have emerged: Truedoc. Nonetheless. from Netscape and Bitstream. These Windows versions can also support Truedoc fonts with a downloadable player from Bitstream. As you can see. Dynamic fonts.1 don’t support downloadable fonts at all. Here’s a summary of what’s supported for the current browsers: • Netscape: Versions 4. are fonts that can be linked within a Web page. neither of the major browsers supports a cross-browser standard for dynamic fonts. Unfortunately. which has been standardized by the W3C. In this hour. in the same way as built-in fonts. Instead. Netscape 6 and 6. you’ll learn how to embed fonts using both of the standards. and some of the problems you might encounter when using them. The following sections describe the two major standards for dynamic fonts. also known as downloadable or embedded fonts.03 through 4.

0 and later can also use these fonts with the font displayer installed. they include only the characters used by a document or set of documents you analyze. This program creates dynamic fonts from TrueType or Postscript fonts. 19 Internet Explorer Dynamic Fonts Microsoft’s system of dynamic fonts is a bit easier to use. Bitstream has a number of fonts available for public use at the http://www. Netscape (Truedoc) Fonts The Truedoc standard was developed by Netscape and Bitstream. To create custom fonts. This version works for up to 10 days and creates up to 10 dynamic fonts. While including only certain characters makes embedded fonts smaller to download. these fonts are supported strictly by Internet Explorer.com/typography for the latest details.truedoc. the disadvantage is that you might need to re-create the font object when you add a page or edit an existing page. This format requires that the Bitstream Font Displayer be installed. files with the . Microsoft’s WEFT program creates font objects.com/ Web site.com/ and Microsoft’s font site at http://www. Internet Explorer 4.com/.truedoc. This displayer is built in to Netscape 4.com/. However. http://www. A demo version of Web Font Wizard is available at Bitstream’s Web site.truedoc.truedoc.Using Dynamic Fonts 261 The dynamic font situation might have changed since this writing.72 for Windows and MacOS.eot extension. and only on Windows platforms. you have to purchase Bitstream’s Web Font Wizard.microsoft. Earlier versions of Netscape can support Truedoc fonts by downloading the font displayer from http://www. since the software for creating them (WEFT) is available as a free download. Be sure to check the Truedoc site at http://www. . These objects don’t include an entire font—rather.

0 and later by adding another bit of code to the header of your page: <script LANGUAGE=”JavaScript” src=”http://www.pfr file using a <link> tag in the header of your page: <link REL=”FONTDEF” SRC=”http://www.pfr files.com site.pfr”> This tag is similar to the one you use to link an external style sheet. since you can freely use the font definitions on Bitstream’s Web site. their names are specified there.truedoc. This tag is recognized by Netscape 4. The name is actually the original name of the font. The first step in embedding a Truedoc font is to specify the location of the . You can also support Truedoc fonts in Internet Explorer 4. you can refer to it in the same way as other fonts. and is included to prevent bugs in some browser versions.com/pfrs/EngraversGothic. in the deprecated <font> tag or in a style sheet. The first time an Internet Explorer user views your page. The extra <link> tag is part of Bitstream’s recommended code for including . The following is a brief style sheet that uses the font embedded above for paragraphs within a page: <style type=”text/css”> P {font-family: “EngraversGothic BT”} </style> Notice that the font name for the font-family attribute isn’t the same as the name of the . In this case.truedoc. and also take a look at Bitstream’s Web Font Wizard and Microsoft’s WEFT tool for creating font objects. they might be prompted as to whether to run the font displayer application.pfr file. the file is stored on Bitstream’s server. you’ll learn how to use both standards. Using Truedoc Fonts The Truedoc standard is easy to experiment with.js”> </script> <link> This is a <script> tag that references an external JavaScript file.262 Hour 19 Defining Dynamic Fonts Defining fonts for use in your Web page is similar for the two downloadable font standards. If you use the fonts at the truedoc. .com/activex/tdserver. In the sections below. which includes the Bitstream Font Displayer. Once you’ve embedded the font.

a complete set of all characters in the font. The font will work only when stored at a URL matching this list. 4. Choose a filename for the new . it presents a series of dialogs to create a Web font: 1. 5. an HTML file will be created with an example of the font and instructions for using it on your site. Select the font family and style (Regular. Click Next to continue. . Bold. Choose one or more URL paths where the dynamic font will be used. 2. Click Next to continue.pfr file. 19 Many fonts are copyrighted.Using Dynamic Fonts 263 Using the Web Font Wizard You can create . Be sure to check the copyright status of any font you use as a dynamic font. This program is available for Windows or Macintosh platforms. Along with the .1 The Web Font Wizard displays the font selection dialog.pfr files using Bitstream’s Web Font Wizard. The wizard displays an introductory message. and you might be violating the copyright by using them on your site. Click Next to continue. Partial URLs are allowed. Click Next to continue. 3.1. Click Finish to create the file. When you run the Web Font Wizard. FIGURE 19. This dialog is shown in Figure 19. or Italic) for the Web font. Select a set of characters to include in the font file: a standard alphanumeric set. or a custom set of the characters you specify.pfr file. You can choose any font that is installed on the local computer.

you use Microsoft’s WEFT (Web Embedding Fonts Tool) to analyze your Web documents and add the desired fonts to them. You are prompted for the URL or file location for one or more Web pages to analyze. This can be a local file or a path to a Web server directory. 5. When you run WEFT. font-style: normal. .2. This screen is shown in Figure 19. 4.eot). 2. You can also do this manually. } </STYLE> Microsoft’s WEFT application. WEFT is available for Windows platforms only.com/dhtml/examples/ARIAL0. you are asked to list the fonts to embed.microsoft. 3.starlingtech. can create the required style sheet code for your embedded font objects automatically. as explained above.264 Hour 19 Using Microsoft Fonts You use Microsoft’s WEFT fonts by adding an @font-face selector within a style sheet. you can run it from the Start menu. described in the next section. try saving a local file.com/typography/. The default list includes a list of fonts that were used in the Web pages you specified for analysis. This specifies the URL of the embedded font object and the font family it corresponds with. You are prompted for your name and e-mail address to identify the font object. Here is an example: <STYLE TYPE=”text/css”> @font-face { font-family: Arial. Finally. If you have trouble saving to a Web server. You must also specify the URL where the objects will be used. Using Microsoft’s WEFT Tool To create a font object. You are prompted for a location to store the new font objects. After WEFT analyzes your pages. a wizard guides you through the process of setting up an embedded font: 1. This tool is available for download from Microsoft’s site at http://www. Once you’ve downloaded and installed it. font-weight: normal. src: url(http://www. the wizard offers to insert links to the new font objects in your Web documents.

They can’t be used from another URL unless you re-create them. WEFT embedded fonts are locked to the URLs you specify when creating font objects. 19 Using a WEFT Font First. you can try using Microsoft’s WEFT standard for embedded fonts. The following examples demonstrate how to use both types of downloadable fonts in Web pages.1 Using an Embedded Microsoft Font <html> <head> <title>Dynamic fonts: Microsoft WEFT</title> <STYLE TYPE=”text/css”> @font-face { font-family: “Freestyle Script”. you can still take advantage of them in your pages. Listing 19. LISTING 19. font-weight: normal. .2 WEFT prompts you for Web page URLs.1 shows a simple example that uses an embedded WEFT font. font-style: normal.Using Dynamic Fonts 265 FIGURE 19. Workshop: Using Dynamic Fonts Although you should be cautious as dynamic fonts are not yet standardized between browsers.

The text in this paragraph is displayed in large letters in a script font that was embedded into the document’s style sheet.} </STYLE> </head> <body> <h1>Embedded Fonts Example</h1> <p>This is a simple example of dynamic fonts using Microsoft’s WEFT application. you don’t need a copy of the .266 Hour 19 LISTING 19.com/dhtml/examples/FREESTY0. you can try using an embedded Truedoc font.com/dhtml/.eot file from this book’s Web site.1 continued src: url(http://www. . you can’t copy the . Since the file is locked to a specific URL.2 shows the Truedoc example.starlingtech.eot file from this book’s Web site to use on your own machine. Listing 19.</p> </body> </html> To use this example. font-size: 34pt. you’ll need to use the WEFT utility to create an . To use this example on your own server. http://www. You can try this example online or download the listings for this hour from this book’s Web site.eot). Figure 19.eot file for the FreeStyle Script font.starlingtech. If you test this example on your local computer. } P {font-family: “Freestyle Script”.0 or later for Windows. This example will only work in Internet Explorer 4. or the font of your choice.0 or later. it will work with the . Since Bitstream allows you to use the fonts from their site. Using a Truedoc Font Next.pfr files.3 shows Internet Explorer’s display of the example. save it as an HTML document and load it into Internet Explorer 4.

3 The embedded WEFT font example in action.truedoc. For reasons only Bitstream can explain. LISTING 19.pfr”> <SCRIPT LANGUAGE=”JavaScript” SRC=”http://www. font-size: 34pt. If you don’t have a Web server handy.</p> </body> </html> 19 To use this example.truedoc. try the online version on this book’s Web site. Truedoc fonts won’t work in Netscape if your HTML document is stored on your local hard disk. The text in this paragraph is displayed in large letters in the Engraver’s Gothic font.com/activex/tdserver.Using Dynamic Fonts 267 FIGURE 19. downloaded from Bitstream’s site.2 Using an Embedded Truedoc Font <html> <head> <title>Dynamic fonts: Truedoc</title> <LINK REL=”fontdef” SRC=”http://www. .js”> </SCRIPT> <link> <style type=”text/css”> P {font-family: “EngraversGothic BT”. save it as an HTML document and upload it to a server.} </style> </head> <body> <h1>Embedded Truedoc Fonts</h1> <p>This is a simple example of dynamic fonts using Bitstream’s Truedoc standard.com/pfrs/EngraversGothic.

and Truedoc will become a true cross-browser method of using dynamic fonts.03 and later. you’ve learned about the two conflicting standards for downloadable. you’ll take a look at some useful troubleshooting techniques for your DHTML scripts. Although Bitstream’s Web site says that Truedoc fonts work in Netscape 4. . Figure 19. and learned not to rely on them since there is not yet a consistent cross-browser standard. You’ve learned how to use both of these. dynamic fonts.4 shows Netscape 4’s display of the example in action. With any luck. you’re bound to run into errors. In the next hour.0 or later. FIGURE 19.268 Hour 19 This example will work in Netscape 4 (but not Netscape 6) or Internet Explorer 4. Internet Explorer will prompt you to download the Bitstream Font Displayer. and you should know how to deal with them.4 The Truedoc font example in action. As you create more advanced DHTML applications. Summary In this hour. Bitstream will release a font displayer for Netscape 6. Netscape 6 does not currently support these fonts.

Microsoft’s WEFT standard is ideal. Which of the following is the extension used for font files created by Microsoft’s WEFT program? a. there isn’t currently an ideal choice. so a common font format would be needed for cross-browser downloadable fonts.Using Dynamic Fonts 269 Q&A Q. This allows you to use downloadable fonts to provide a last-resort alternative when you specify a font that not everyone has available. Browsers use the existing font rather than downloading a font whenever possible. Postscript .pfr 2. the W3C doesn’t define a standard data format for fonts. Which of the dynamic font standards is the best choice for my pages? A. WEFT c. For intranet sites where Internet Explorer is the only browser used. There will still be less popular browsers without support for these fonts. For public Web sites. Truedoc b. Has the W3C considered a standard for dynamic fonts? A. It depends on your audience. . Which of the following font formats is supported by Netscape 4? a.weft . However. Q. What happens if I specify a downloadable font and the user already has an installed font of the same name? A. b. however. 19 Questions 1. as a matter of fact the @font-face method used for Internet Explorer’s embedded fonts is a CSS2 standard. Quiz Test your knowledge of the material covered in this hour by answering the following questions. c.eot . Q. although the Truedoc standard will be when it’s supported by Netscape 6. Yes.

. Netscape 4 supports the Truedoc system for dynamic fonts. • Look at the list of fonts at http://www. b. a.truedoc.270 Hour 19 3.com/ and try creating a . b.pfr file.eot extension. b.1. Which CSS attribute do you use to assign text to a downloadable font you have embedded? a.com/ and try adding another dynamic font to the example in Listing 19.truedoc. 2. c. • Download the trial version of the Web Font Wizard from http://www.2. The font-family attribute is used to assign a font you’ve embedded to a section of text within the page. font-face font-family font-file Answers 1. Exercises If you’d like to experiment further with dynamic fonts before moving on. try the following exercises: • Use Microsoft’s WEFT program to create a font file to go with Listing 19. 3. Microsoft’s WEFT program creates font object files with the . linked to your server or local computer’s URL.

This hour covers the following topics: • Following good DHTML practices • Avoiding common mistakes • Displaying and analyzing error messages • Testing dynamic documents • Testing in multiple browsers • Debugging an example document . and learn how to find and eliminate errors when they do occur. When you’re dealing with this much HTML and JavaScript code.HOUR 20 Troubleshooting DHTML Throughout this book. you’ve learned how to use DHTML to create increasingly complex applications. In this hour. you’re bound to run into errors here and there. you’ll learn how to avoid some of the most common pitfalls when creating DHTML applications. and in the remaining hours you’ll create some larger-scale examples.

and DHTML. • Use JavaScript comments (begin a line with // or enclose comments between /* and */ characters) and HTML comments (begin with <!-. you’ll remember how it works. • When developing with an application. you might also run into mistakes that are common and easy to make. Sometimes your document will also use CSS styles. • Use meaningful variable and function names. • Check your browser for error messages—these aren’t always displayed unless you ask for them. and divide large functions into smaller functions. Here are a few guidelines for creating error-free scripts: • Format your scripts neatly for readability. The following are some of the most common errors in HTML. This way when you look at your script later. Avoiding Common Mistakes While it’s not hard to come up with an original mistake. and separate each statement onto its own line. You’ll learn how to display these errors later this hour. The following are some common HTML errors: .and end with -->) to document your scripts. CSS. While every programmer runs into bugs on a regular basis. JavaScript. • Divide complex scripts into functions. and a small mistake in any of them can render your DHTML useless. Although this is optional. testing regularly to make sure everything works so far. you can avoid some errors by making sure you follow consistent practices when creating DHTML scripts. it makes the script easier to read and makes it easier for the browser to display meaningful error messages.272 Hour 20 Tips for Error-free DHTML When you create DHTML applications. your HTML syntax becomes even more crucial. start with a simple version and add features. you’re actually dealing with three separate languages: HTML. This makes it easy to take a divide-and-conquer approach to debugging. Common HTML Mistakes The HTML language is pretty forgiving. • End all JavaScript statements with semicolons. which have their own language. Each of these languages has rules and restrictions. JavaScript. but when you add DHTML. and the syntax of DOM objects. Use indenting to separate sections.

it’s global. • Confusing local and global variables. 20 . While this won’t crash browsers. For example. it can cause trouble with DHTML. while name is used for form elements that will be read using a CGI program or manipulated using the Level 0 DOM. • Confusing the ID and name attributes. • Confusing the ID and class attributes. For example. ID should be used with any tag that will be manipulated using DHTML. Common CSS Mistakes CSS style sheets aren’t always crucial to the functioning of your application.Troubleshooting DHTML 273 • Forgetting to end sections. These files can contain only JavaScript statements. • Confusing assignment (=) and equality (==) operators. function is lowercase. color=blue> should • Including the <style> tag or other HTML tags in an external style sheet file. • Nesting tags improperly: for example. and worse. while a class can be assigned to several elements. potentially causing other errors. if it’s created inside a function. • Using HTML tags. such as <script>. If a variable is created outside a function. <p be <p style=”color:blue”>. Except for special cases such as <hr> and <br>.links) refers to a class attribute. The following are some of them you might run into: • Getting case-sensitive keywords wrong. it’s local. but it too has some common mistakes. HTML tags require an ending tag. <p><b>Hello</p></b>. These files should contain only CSS directives. the statement if (a=5) will always return true. avoid using the same name for two variables at all. For example. but CSS errors might give your document an incorrect appearance and can cause trouble with DHTML. and properties such as style. one beginning with a pound sign (#table) refers to an element’s ID attribute. Use the var keyword inside functions to ensure that you create a local variable if you use the same name as an existing global variable—or better yet. A selector without punctuation (Body) refers to an HTML element. An ID can be used for only one element. Here are some common CSS mistakes: • Using style attributes as regular attributes.backgroundColor have extra capital letters. in external JavaScript files. Common JavaScript Mistakes The JavaScript language is pretty simple. • Using incorrect selector syntax. The correct statement is if (a==5). one beginning with a period (. will set the variable a’s value to five.

To troubleshoot your DHTML applications. you should make sure your browser is configured to display errors. common mistakes abound with the DOM objects used in DHTML.all collection.0 browsers. • Attempting to use older DHTML syntax. you can simply look at the JavaScript console.1. When you’ve assigned an ID attribute. The console window. • Attempting to access an object without first finding the object. or even cause the browser to crash. . errors are not displayed by default. you can’t use it directly—use the result of getElementById instead. Displaying Errors in Netscape Some earlier versions of Netscape display JavaScript errors automatically by default. displays a list of the most recent errors. You can keep the window open and clear it when you’re about to test a new function. any time something went wrong in your DHTML script. These should only be used if you’re creating a compatible version for 4. cause the wrong result. both major browsers will at least let you know when syntax errors occur in your scripts.getElementById rather than simply getElementById. properties. The getElementById method is the most common source of confusion—remember that the initial g and the final d are lowercase. Unfortunately. Here are a few mistakes you might run into: • Getting case-sensitive objects and methods wrong. or methods that don’t exist. such as the <layer> tag or the document. • Using objects incorrectly. Remember to use document.274 Hour 20 Common DHTML Mistakes Last but not least. type javascript: into the browser’s location bar. Fortunately. In Netscape 6 and some versions of Netscape 4. To display the errors. the browser would display an error message. this is often not the case—an error can cause nothing to happen at all. To access this window. or when you refer to objects. Analyzing Errors In an ideal world. shown in Figure 20.

JavaScript Console from the menu.1 Netscape’s JavaScript console displays a list of recent errors. . you’ll want to make sure errors are displayed. FIGURE 20. To display JavaScript errors in Internet Explorer 4. while other versions suppress the error by default. then uncheck the Disable Script Debugging option and check the Display a notification about every script error option.Troubleshooting DHTML 275 Some versions of Netscape 6 don’t accept the javascript: command.0 and later. select Tools. Tools. Internet Explorer will display an error icon on the status line. 20 When the display of errors is disabled. but when you’re creating your own scripts. An alternate way of displaying the JavaScript console in Netscape 6 is to select Tasks. You can double-click this icon to display the error message. Select the Advanced tab. Internet Options from the menu. Displaying Errors in Internet Explorer Some versions of Internet Explorer display an alert box for each JavaScript error by default. This is nice when you’re browsing the Web and don’t want to know about every JavaScript error you encounter.

you’ll need to test in each of those too. or making the script not work at all—others are harder to notice. you should test it thoroughly. incompatibilities. you’ll usually know which area of your script to look at.com/). If it interacts with the user. Sometimes you need to use a separate computer. Once an error occurs. To avoid surprises like this. You’ll probably still be amazed at the mistakes users come up with.org/). To make sure your script is bug-free. you should keep at least a couple of different browsers (the latest Netscape and the latest Internet Explorer) handy. Play piano on the keyboard and enter totally random information. . Often you’ll develop an application that works perfectly. Don’t forget alternative browsers. and so on.browser. If you are designing scripts to work with older browsers. and quirks.opera. to keep two different versions of Internet Explorer installed on a Windows system.276 Hour 20 Testing Dynamic Documents An important part of the troubleshooting process is testing. a browser that supports many operating systems and languages. until you try it in a different browser. or boot to a different operating system. and Lynx (http://lynx. click the wrong links. to test in Internet Explorer 4. a text-based browser still in wide use. While many errors are obvious—making an error message appear immediately when the page loads. It’s difficult. if not impossible. Testing Browser Compatibility On top of the many places a bug might appear in your DHTML script. continue testing to make sure there are no others. After you’ve fixed the error. Two good ones to test are Opera (http://www. browsers have bugs too—not to mention inconsistencies. based on what you were doing at the time. act like the worst possible user to see if you can find any errors. Don’t just test your scripts by making what you believe to be typical user mistakes. Enter the wrong information.

starlingtech. However.com/software/jsdebug. Here are a few tools you might wish to use as you develop and debug larger DHTML applications: • HTML validators can check your HTML documents to see if they meet the HTML standard. but a version is in development: http://www.asp.Troubleshooting DHTML 277 Using Debugging Tools While you can do most debugging using only a text editor and browser.1 shows a document with HTML. . in working and non-working versions. and perform other debugging tasks.” includes links to HTML validators. and CSS. after all. Appendix A.mozilla. editors. It is available from this url: http://msdn.microsoft.com/library/en-us/sdbug/Html/ sdbug_1.html. The validation process can also help you find errors in your HTML. Workshop: Debugging a Document As an example of the process you’ll go through when debugging a DHTML application. • While text and HTML editors are good basic editing tools. The debugger does not yet support Netscape 6.com/dhtml/.org/projects/venkman/. but works with Internet Explorer. and other debugging tools. that uses DHTML to display a clock on the screen. from this book’s Web site: http://www. “Other JavaScript and DHTML Resources. Listing 24. The W3C has a validator online at http://validator. display variable values. JavaScript. • Netscape’s JavaScript debugger allows you to set breakpoints.w3. 20 You can download this hour’s example.org/.netscape. sometimes software tools can save you time. You can download the debugger at this URL: http://developer. • Microsoft Script Debugger is similar. they can also help with debugging by displaying line numbers and using color codes to indicate valid commands. this version of the document doesn’t work—this hour’s topic is troubleshooting.

position: absolute. window.</p> <div ID=”clock”> 00:00:00 </div> </body> </html> To test this document. similar clocks can be created using layers to work with the 4. hours=now. left: 5px. secs=now. font-family: monospace.”.setTimeout(“Clock(). try to find the errors and get it working before you move on.getElementById) return. theclock=document. and if you feel ambitious. } </style> </head> <body onLoad=”clock(). theclock.getSeconds().getHours().getMinutes(). The clock updates continously to show the current time. When it’s working.250). .innerHTML = hours + “:” + mins + “:” + secs. } </script> <style type=”text/css”> #clock { backgroundColor: yellow.1 The Clock Application. font-weight: bold.”> <h1 align=”center>DHTML Clock Example</h1> <p>This example uses DHTML to display a clock in the upper-left corner of the browser window. with Errors <html> <head> <title>DHTML Clock</title> <script language=”JavaScript”> function Clock() { if (!document.278 Hour 20 LISTING 20. the clock example will require Netscape 6 or later or Internet Explorer 5. mins=now. save it as an HTML file and load it into a browser. now = new Date().0 or later. top: 5px.getElementById(“clock”). font-size: 20pt. However.0 browsers. Notice what happens.

Character 1. with the exception of the clock. . and the clock actually acts like a clock. since the function keyword defines it as Clock. and Internet Explorer’s reads Object expected. and the <div> never gets defined. and Internet Explorer says ‘theclock’ is null or not an object. • All of the HTML text fails to display. So the next step is to look for an HTML error near the <div> tag with the ID attribute “clock”. This also explains why most of the HTML content wasn’t displayed! 20 Fixing Minor Errors After adding the missing quotation mark. While neither of these is a perfect clue. the clock still doesn’t work. • The clock doesn’t display leading zeros: for example. you’ll immediately notice two major problems: • A JavaScript error occurs when the page is first loaded. you’ll find that the heading is actually the problem: <h1 align=”center>DHTML Clock Example</h1> In this line. The result is that the quoted string encloses the rest of the document. Netscape’s display of this error reads Error: clock is not defined. Line 28. the JavaScript error on loading. you can begin to fix them.getElementById(“clock”). things are much better—the entire HTML content displays. Start with the most severe error. This time. and the clock display remains at 00:00:00.Troubleshooting DHTML 279 Fixing Major Errors When you first load the clock example into a browser. 11:01:03 is displayed as 11:1:3. If you look through the HTML document. Both of these are referring to this statement: theclock=document. This statement looks fine—getElementById is even spelled correctly. the Clock function isn’t capitalized as it should be. Now that you’ve found the errors. they should both lead you to this HTML tag: <body onLoad=”clock(). Netscape displays the error message theclock has no properties.”> In this tag. try loading the document again. After you’ve fixed this error. Now only two minor problems remain: • The clock doesn’t have the yellow background color that was specified in the style sheet. the closing quotation mark is missing from align=”center”.

look at the crucial part of the style sheet for the background color: backgroundColor: yellow. theclock=document. hours=now. you’ll have to manually add the zeros.2 shows the debugged clock example. if (mins < 10) mins= “0” + mins. Finally.250).getElementById) return. such as Hour 9.” in this book. window.setTimeout(“Clock(). mins=now.getHours(). The Debugged Document Now that you’ve found the HTML errors.getMinutes(). the clock needs to display two-digit numbers. don’t expect the browser to give you any error messages. . LISTING 20.innerHTML = hours + “:” + mins + “:” + secs. and CSS errors and fixed them. you’ll have to look through the document. Adding two if statements before the line that displays the clock takes care of this: if (secs < 10) secs= “0” + secs.getSeconds().2 The Working Version of the Clock Application <html> <head> <title>DHTML Clock</title> <script language=”JavaScript”> function Clock() { if (!document. take a quick look at a DHTML reference. First. JavaScript errors. theclock. Listing 24. You’ll discover that the correct property is background-color.getElementById(“clock”).”. position: absolute. Fix this error. if (secs < 10) secs= “0” + secs. } </script> <style type=”text/css”> #clock { background-color: yellow. not backgroundColor. now = new Date(). if (mins < 10) mins= “0” + mins.280 Hour 20 Since these are minor functional problems. While this might look correct at first glance. Since JavaScript displays numbers lower than ten as single digits. Instead. secs=now. left: 5px. and the background will display correctly. “Introducing Style Sheets. you should have a working document.

2 shows Internet Explorer’s display of the working example. font-family: monospace.2 continued top: 5px.</p> <div ID=”clock”> 00:00:00 </div> </body> </html> To test this document. The clock updates continously to show the current time.Troubleshooting DHTML 281 LISTING 20. FIGURE 20.2 The working version of the clock example. font-size: 20pt.”> <h1 align=”center”>DHTML Clock Example</h1> <p>This example uses DHTML to display a clock in the upper-left corner of the browser window. } </style> </head> <body onLoad=”Clock(). 20 . You should find that the clock is now fully functional. Figure 20. save it as an HTML file and try it again in the browser. font-weight: bold.

it runs four times per second and quickly updates the clock when the seconds have changed. Yes. Which time zone does the clock display the time in? A. and the error message is displayed then. ranging from a company Web page with multiple dynamic functions to a complete game application. and how to find and fix any errors that appear in your DHTML applications. In the final four hours of this book. you’ve learned how to avoid common mistakes in DHTML. you’ll explore more examples of what can be done with DHTML. Q. rather than once per second? A. this will let you know any areas where you’ve deviated from the W3C’s HTML standard. Along with finding errors. This makes the clock a bit more accurate. Q. CSS. Different users will see different times depending on their time zone and their computer’s clock setting. . See Appendix A for a list of applications you can use to validate. or the current browser’s internal clock. Is there an easier way to find HTML errors? A.282 Hour 20 You’ve now completed the process of debugging a DHTML application. Do browsers always display JavaScript error messages when the page is first loaded? A. The clock is in local time. No. and you won’t usually have this much trouble with a simple example—but as you move on to more complex applications. this was a worst-case scenario. your HTML documents. or test the syntax of. Since the timeout won’t run the function each time the seconds value of the time changes. Q&A Q. HTML. Fortunately. and JavaScript. you’ll quickly gain more troubleshooting experience. Q. Why does the SetTimeout method in the clock example repeat the function every 250 milliseconds. Sometimes an error doesn’t happen until a particular part of your script executes. Summary Congratulations—you’ve reached the end of Part V! In this hour.

This statement is correct. 2. Which of the following is the correct command to enter into Netscape’s location bar to display the JavaScript console? a. c. 2. c. the if statement is improperly capitalized. b. In answer C. 20 . the equality operator (==) is used where the assignment operator (=) belongs. b. a. 3. console: http://www. Which of these statements does not contain an error? a = document.getElementById(“layer”).Troubleshooting DHTML 283 Quiz Test your knowledge of the material covered in this hour by answering the following questions. a. if (score=10) alert(“You win!”). The correct command is javascript:. the getElementById method is capitalized incorrectly.getElementById(“layer”). c. In answer B’s statement. c. This statement is correct.getElementByID(“layer”). if (score==10) alert(“You win!”). 3.com/javascript javascript: Answers 1. b. a = document.netscape. Questions 1. In answer A. If (score==10) alert(“You win!”). the assignment operator (=) is used instead of the equality operator (==). c. a == document. Which of the following JavaScript statements does not contain an error? a. In answer B.

2. and see how the browser responds. . to create various errors. try the following exercises: • Modify the working clock example. Listing 20.284 Hour 20 Exercises If you’d like more practice troubleshooting before you move on to more complex applications. Find and fix any errors you run into. • Modify the clock example to flash the time on and off each second as it counts.

PART VI Putting It All Together Hour 21 Creating a Dynamic Site 22 Creating Complex Animations 23 Creating a DHTML Game 24 DHTML Tips and Tricks .

.

In this hour. you’ll take a look at some more complex DHTML examples. This hour covers the following topics: • Guidelines for complex DHTML sites • Creating the basic HTML document • Creating the JavaScript file for menus • Adding a scrolling message . and learn some useful tips for use with large-scale DHTML applications.HOUR 21 Creating a Dynamic Site Welcome to Part VI! In the final part of this book. you’ll see how easily you can combine two or more dynamic features on a single page. You’ll create an example company Web site with menus and a scrolling message.

” However. you created a Web site menu system. The first step is to define a table to lay out the body of the page and the menu column. you will create a new version of the Figby Industries home page in this hour. this is as easy as including the appropriate HTML and JavaScript for each feature. “Creating DHTML Text Effects. you will frequently want to combine several dynamic features within the same site. Creating the HTML Document As an example of combining DHTML features. follow these tips when combining features: • Carefully consider whether each feature is necessary. To avoid creating a huge and cumbersome HTML document. “Creating Drop-Down Menus. • Avoid using global variables in the DHTML functions except when absolutely necessary. The two <td> sections will contain the menu column and the body of the page. and test each one to make sure it works correctly before adding additional features. Fortunately. This page will include two dynamic features: • A menu system. .” The first step in this process is to create the HTML document. • Use separate JavaScript files whenever possible. Laying Out the Page In Hour 13. You can create an alternate version of this menu that works from a column at the left side of the page instead of the top. Here is the basic layout of the table. using the same function you used in Hour 15. • A scrolling message. Most of the dynamic features will be included in separate JavaScript files. this menu will be set up to work vertically instead of horizontally. or whether it will make the page unnecessarily complex. Be sure that the same variable name is not used for two different global variables. • Implement one feature at a time. similar to the one you created in Hour 13.288 Hour 21 Creating Complex DHTML Sites While the examples in this book generally show a single DHTML feature in use at a time.

Menu bar goes here --> </td> <td> <!-.”> <a href=”equip.html”>Supplies</a></td></tr> </table> </div> 21 .” onMouseOut=”Timeout(‘sales’). with each menu item appearing on its own row of the table.’p2’).” onMouseOut=”UnHighlight(‘products’.menu table --> <tr> <td ID=”menu-products” width=”100” bgcolor=”Silver” onMouseOver=”Menu(‘products’). Each item has onMouseOver and onMouseOut tags to call the Menu and Timeout JavaScript functions.”> <a href=”supplies. each of which contains one of the menus that will be displayed when the mouse moves over a menu term.’p2’). The following is the structure of one of the layers: <div ID=”products” STYLE=”position:absolute. The following is a simplified menu with only two items: <table border=”0” cellpadding=”4”> <!-. Defining Layers The final part of the HTML document for the menu system is a series of layers.html”><b>Sales</b></a> </td> </tr> </table> <!-.end of menu table --> The final menu will include five items.Creating a Dynamic Site 289 <table cellspacing=”0” cellpadding=”0” align=”left”> <tr><td valign=”top”> <!-. which will handle the opening and closing of menus. visibility: hidden”> <table width=”100%” border=”0” cellpadding=”4” cellspacing=”0”> <tr> <td width=”100%” ID=”p1” onMouseOver=”Highlight(‘products’.html”>Equipment</a></td></tr> <tr> <td width=”100%” ID=”p2” onMouseOver=”Highlight(‘products’.” onMouseOut=”UnHighlight(‘products’.’p1’).html”><b>Products</b></a> </td> </tr> <tr> <td ID=”menu-sales” width=”100” bgcolor=”Silver” onMouseOver=”Menu(‘sales’).’p1’).” onMouseOut=”Timeout(‘products’).”> <a href=”products.”> <a href=”sales.Body of page goes here --> </td></tr> </table> Defining the Menu The menu itself is defined in another table.

LISTING 21. This function will change the background color of the item the mouse is over. This menu includes two items.” > <table cellspacing=”0” cellpadding=”0” align=”left”> <!-. You can add another menu by adding a row to the menu table with the appropriate links. and combine them with the layout table and the body of the page. and ensure that the menu continues to display.menu table --> <tr> <td ID=”menu-products” width=”100” bgcolor=”Silver” onMouseOver=”Menu(‘products’).layout table --> <tr><td valign=”top”> <!-.js”> </script> </head> <body style=”margin-left:0.1 The Complete HTML Document <html> <head> <title>Figby Industries. Listing 21. Equipment and Supplies. Conversely.”> <a href=”products.290 Hour 21 This layer will be made visible when the mouse is over the Products menu. and adding a corresponding <div> section with the menu itself. Completing the HTML Document To complete the HTML document.</title> <script language=”JavaScript” src=”menu2. The final HTML document will include five such layers. margin-top:0. This function will return the background color to normal and allow the display of the menu to time out.” onMouseOut=”Timeout(‘products’). Each item in the menu includes an onMouseOver event handler that calls the Highlight function. one for each menu term.menu on left side --> <table border=”0” cellpadding=”4”> <!-. the onMouseOut event handler will call the UnHighlight function.1 shows the complete HTML document.html”><b>Products</b></a> </td> </tr> <tr> . with a menu item in each row. Inc. you need to complete the menu table and the layers for each menu. It consists of a table to lay out the items.

” onMouseOut=”UnHighlight(‘products’.’s2’). visibility: hidden”> <table width=”100%” border=”0” cellpadding=”4” cellspacing=”0”> <tr> <td width=”100%” ID=”p1” onMouseOver=”Highlight(‘products’.’s2’).’s3’).Creating a Dynamic Site 291 LISTING 21.html”><b>Staff</b></a> </td> </tr> <tr> <td ID=”menu-jobs” width=”100” bgcolor=”Silver” onMouseOver=”Menu(‘jobs’).’s1’).”> <a href=”service.” onMouseOut=”UnHighlight(‘sales’.”> <a href=”staff.” onMouseOut=”Timeout(‘staff’).html”>Order Form</a></td></tr> <tr> <td width=”100%” ID=”s3” onMouseOver=”Highlight(‘sales’.1 continued <td ID=”menu-sales” width=”100” bgcolor=”Silver” onMouseOver=”Menu(‘sales’).’p1’).”> <a href=”equip.”> <a href=”order.” onMouseOut=”UnHighlight(‘sales’.’s3’).end of menu table --> <div ID=”products” STYLE=”position:absolute.” onMouseOut=”Timeout(‘service’).html”>Price List</a></td></tr> <tr> <td width=”100%” ID=”s2” onMouseOver=”Highlight(‘sales’.html”><b>Service</b></a> </td> </tr> <tr> <td ID=”menu-staff” width=”100” bgcolor=”Silver” onMouseOver=”Menu(‘staff’).’p2’).” onMouseOut=”Timeout(‘sales’).’s1’).” onMouseOut=”UnHighlight(‘sales’.”> <a href=”prices.html”>Equipment</a></td></tr> <tr> <td width=”100%” ID=”p2” onMouseOver=”Highlight(‘products’.’p2’). visibility: hidden”> <table width=”100%” border=”0” cellpadding=”4” cellspacing=”0”> <tr> <td width=”100%” ID=”s1” onMouseOver=”Highlight(‘sales’.’p1’).html”><b>Employment</b></a> </td> </tr> </table> <!-.”> <a href=”supplies.html”>Supplies</a></td></tr> </table> </div> <div ID=”sales” STYLE=”position:absolute.”> <a href=”jobs.” onMouseOut=”Timeout(‘jobs’).”> 21 .” onMouseOut=”UnHighlight(‘products’.”> <a href=”sales.html”><b>Sales</b></a> </td> </tr> <tr> <td ID=”menu-service” width=”100” bgcolor=”Silver” onMouseOver=”Menu(‘service’).

visibility: hidden”> <table width=”100%” border=”0” cellpadding=”4” cellspacing=”0”> <tr> <td width=”100%” ID=”t1” onMouseOver=”Highlight(‘staff’.”> <a href=”jobs.html”><b>Sales</b></a></li> <li><a href=”service.’t1’).html”>Job Listings</a></td></tr> </table> </div> </td> <td> <!-.’r2’).html”><b>Products</b></a></li> <li><a href=”sales.’t1’).html”>Contact Us</a></td></tr> </table> </div> <div ID=”staff” STYLE=”position:absolute.html”><b>Service</b></a></li> <li><a href=”staff.html”><b>Employment</b></a></li> </ul> <pre>(c) 2002 Figby Industries</pre> .html”>Meet the Staff</a></td></tr> </table> </div> <div ID=”jobs” STYLE=”position:absolute.” onMouseOut=”UnHighlight(‘jobs’.” onMouseOut=”UnHighlight(‘service’.’r1’).”> <a href=”support.’r2’). </p> <ul> <li><a href=”products. your source for all sorts of imaginary products.’r1’). Follow the links below or use the menu on the left to learn more about our company and our products.” onMouseOut=”UnHighlight(‘service’. visibility: hidden”> <table width=”100%” border=”0” cellpadding=”4” cellspacing=”0”> <tr> <td width=”100%” ID=”j1” onMouseOver=”Highlight(‘jobs’.”> <a href=”cservice.body of page on right side --> <img align=”center” src=”logo.html”>Specials</a></td></tr> </table> </div> <div ID=”service” STYLE=”position:absolute.292 Hour 21 LISTING 21.html”><b>Staff</b></a></li> <li><a href=”jobs. visibility: hidden”> <table width=”100%” border=”0” cellpadding=”4” cellspacing=”0”> <tr> <td width=”100%” ID=”r1” onMouseOver=”Highlight(‘service’.1 continued <a href=”specials.gif” width=”486” height=”180” border=”0”><br> <h1>Welcome to Figby Industries!</h1> <p>Welcome! This is the home page of Figby Industries.’j1’).’j1’).html”>Support</a></td></tr> <tr> <td width=”100%” ID=”r2” onMouseOver=”Highlight(‘service’.”> <a href=”staff.” onMouseOut=”UnHighlight(‘staff’.

In an example like this with several nested tables. it’s best to keep the JavaScript functions in a separate file. comments can help you keep track of the different tags and avoid creating HTML errors. This example requires a graphic. Creating the JavaScript File The next step in creating the page is to add the JavaScript functions that will manage the menu. The following is the Menu function: function Menu(current) { if (!document.Creating a Dynamic Site 293 LISTING 21.starlingtech. inmenu=true. 21 . and will open the menu requested by its parameter. These define comments that make it clear where the different sections of the layout table begin. current.js: <script language=”JavaScript” src=”menu2.js”> </script> The JavaScript functions for the menu will be similar to those you used for the horizontally-oriented menu in Hour 13.1 continued </td></tr> </table> <!-.getElementById) return. but the dynamic functions won’t work until you add the JavaScript functions in the next section. You can view it in a browser.com/dhtml/. <!-.end of layout table --> </body> </html> To use this example. logo. oldmenu=lastmenu. Notice the HTML comment tags in this example. You can download it.gif. along with the HTML and JavaScript files for this hour. Modifying the Menu Function The Menu function will be called by the onMouseOver event handlers for menu terms. save it as an HTML document. from this book’s Web site: http://www. The HTML document already includes a <script> tag that references the file menu2.and -->. lastmenu=current. Since this is a complex document already.

Listing 21.visibility=”visible”.style.2 shows the complete JavaScript file for this example. m=document.top= m. box.style. box. m. var lastmenu=0. Completing the JavaScript File The complete JavaScript file includes the modified Menu function as well as the Erase.style. Timeout.style. It erases the previously displayed menu.style. and the style. LISTING 21. These four functions are unchanged from those in Hour 13.left= m. The difference between this function and the version for the horizontal menu is in the positioning of the menu. box. box=document. } This function first uses an if statement to verify that the browser has the necessary DOM support.style.offsetLeft + m. if (oldmenu) Erase(oldmenu).offsetTop.getElementById(current). by calling the Erase function. box. function Menu(current) { if (!document.visibility=”visible”. m.294 Hour 21 if (oldmenu) Erase(oldmenu). lastmenu=current. Highlight. box.offsetWidth + 2. box=document. if any.backgroundColor=”Aqua”. It then sets the global inmenu and lastmenu variables to keep track of the current menu.getElementById(“menu-” + current).left= m.backgroundColor=”Silver”.backgroundColor=”Aqua”. box. and UnHighlight functions. oldmenu=lastmenu.getElementById(“menu-” + current).offsetWidth + 2.top position is set to the top position of the menu term.offsetLeft + m.offsetTop. .getElementById(current).style.top= m. box.width=”100px”.style. The style.2 The Complete JavaScript File var inmenu=false. m=document.left position is set to the menu term’s position plus its width and a 2-pixel offset. box.style. inmenu=true.getElementById) return.style.

save it as menu2.getElementById(item).setTimeout(“Erase(‘“ + current + “‘). or the name you used in the <script src> tag in the HTML file.getElementById(current).0 browsers.visibility=”hidden”. } function Timeout(current) { inmenu=false. Once both files have been placed in the same directory.getElementById(item). This example uses the W3C DOM.getElementById) return.style. m. box=document.backgroundColor=”Silver”. } function Highlight(menu. See Hour 17.style. } function Erase(current) { if (!document.getElementById) return.getElementById) return.style.”. window.item) { if (!document. } To use this file. obj=document.item) { if (!document. inmenu=true.style.500).Creating a Dynamic Site 295 LISTING 21. and thus requires Netscape 6 or later or Internet Explorer 5 or later. However. box.backgroundColor=”Silver”.getElementById(“menu-” + current).backgroundColor=”Aqua”. Timeout(menu). } function UnHighlight(menu.2 continued box. m=document.style.1 shows Netscape 6’s display of the menu in action. box. obj=document. since it uses layers. you can test the menu by loading the HTML document into a browser.” for information about this process. It should be saved in the same directory as the HTML document.style.js. “Dealing with Browser Differences. lastmenu=menu. Figure 21.backgroundColor=”Silver”. if (inmenu && lastmenu==current) return. obj. it could be adapted to work in the 4. with the Sales menu currently selected.width=”100px”. obj. 21 .

as shown by Netscape. msg += “and our daily specials. you can add a scrolling message.getElementById(“scroll”). msg += “Be sure to check out our snazzy DHTML menu “. “. pos). function ScrollMessage() { newtext = msg. obj = document.substring(0.substring(pos..3 shows the complete JavaScript file. newtext=newtext. similar to the one you created in Hour 15.296 Hour 21 FIGURE 21. LISTING 21.. Workshop: Adding a Scrolling Message As an example of how DHTML functions can be combined.” + msg. . ..3 The JavaScript File for the Scrolling Message msg = “Welcome to our site! “. Listing 21. To do this. to the Web page.substring(0.. except that the scrolling message itself has been changed and it will be stored in a separate JavaScript file.80). pos = 0.length) + “. you can simply create a JavaScript file to handle the scrolling functions and modify the HTML document to include this file. Creating the JavaScript File The JavaScript code for the scrolling message is identical to that used in Hour 13. msg.1 The menu in action.

Figure 21.js”> </script> You can add this <script> tag in the <head> section of the document. you need to modify the HTML document to include the new JavaScript file. } To use this JavaScript file. if (pos > msg. save it as scroll2. Assign it the ID attribute “scroll” to place the scrolling message there: <pre ID=”scroll”>(c) 2002 Figby Industries</pre> Last but not least.length) pos = 0. the message should begin to scroll.js in the same directory as the existing HTML and JavaScript files. You could also combine these JavaScript functions into the JavaScript file you created earlier and include them with a single <script> tag.Creating a Dynamic Site 297 LISTING 21. Here’s the modified <body> tag: <body style=”margin-left:0. Next. you need to start the scrolling message.firstChild.100). pos++. and the menu will continue to work as before.3 continued obj.” onLoad=”ScrollMessage(). you’ll need to create a place for the message to scroll. There is already a <pre> section at the end of the document containing a copyright notice. 21 .”> Testing the Modified Example Now that these changes are in place. First.nodeValue = newtext.setTimeout(“ScrollMessage()”. window. Once you load it. Modifying the HTML Document Next.2 shows Internet Explorer’s display of the example in action with the menu closed and the message scrolling. margin-top:0. However. after the closing </script> tag for the menu script. you can load the HTML document into a browser. it’s useful to keep related functions in their own files for a modular approach. Add an onLoad event handler to the <body> tag to start the ScrollMessage function. you’ll need to add a <script> tag that references the file: <script language=”JavaScript” src=”scroll2.

In the next hour. you’ll create a more complex DHTML animation that uses dynamic graphics combined with DHTML positioning. you’ve seen how you can combine multiple JavaScript files to create a page that supports multiple dynamic features using DHTML. You can use this same technique to combine whichever features you need onto a single page.298 Hour 21 FIGURE 21. Q&A Q.2 Internet Explorer shows the scrolling message in action. However. Can I position the menu somewhere other than the upper-left corner? A. you’ll explore another larger DHTML example—this time. you’ll need to change the positioning based on the current browser. Netscape measures these properties from the edge of the browser window. To deal with a menu anywhere other than the top of the page. Summary In this hour. there is a difference in the way current browsers interpret the offsetTop and offsetLeft properties. Yes. . while Internet Explorer measures them from the edge of the table cell. or onto all of the pages within a site.

Is there a limit to the number of <script> tags I can use that reference external files? A. b. When starting an animation or scrolling message. Which of the following is the property you use to set the left-hand position of a layer with the object box? a. which is a way to call the function whenever the browser displays the page? a.style. an onLoad event handler in the <body> tag b.0 browsers. How can I modify the menu to work in the version 4. Which of the following is the typical extension used for external JavaScript files? a. Questions 1. as discussed in Hour 17. b. The key difference is to use a browser-independent version of the getElementById method. No. box.0 browsers? A.left 21 . but adding additional files increases the browser’s delay when loading the HTML document. Q. c.style.offsetLeft box.offsetLeft box. You will also need to change the way menu items are positioned.script . To avoid this delay. c. since the offset properties don’t work in the 4. an onLoad event handler anywhere c. combine functions into a single JavaScript file. Quiz Test your knowledge of the material covered in this hour by answering the following questions. .jsc 2. a <script> tag in the header of the page 3. or avoid using unneeded DHTML functions.js .Creating a Dynamic Site 299 Q.

or an example site of your choosing. try the following exercises: • Modify Listing 21. An onLoad event handler in the <body> tag will start a function as soon as the page loads. You can use the box. JavaScript files typically end with the . a.style. then change the ScrollMessage function to check that variable before it continues the scrolling. .1 to personalize the menu system for your own site. b. 2. Exercises If you’d like to work further with this example before moving on. 3. • Try adding a link or button within the page that can disable the scrolling message. c.left property to assign the left-hand position of a layer or other object. You should set a global variable as a flag.300 Hour 21 Answers 1.js extension.

This hour covers the following topics: • Following the mouse pointer’s position • Creating an animation that tracks the mouse • Animating with multiple images • Creating JavaScript functions • Completing the animation example . you’ll create some more complex examples of DHTML animation.HOUR 22 Creating Complex Animations As you’ve explored in the earlier hours of this book. You will also learn how to combine DHTML animation with JavaScript image source changes to create better animations. DHTML provides a simple way to position and animate objects. such as animated navigation features. This can be used for entertaining animations as well as practical purposes. In this hour.

In this hour.indexOf(“Netscape”) != -1). you’ll need an HTML document. you’ll create a more sophisticated version that uses multiple images. To make it easier to address these differences.”> <h1>Animation in DHTML</h1> <div ID=”mouse” style=”position:absolute. You will use this later this hour to make the image change dynamically. Netscape. Creating the HTML Document To begin creating this example.appName. top:150. you can include this line at the beginning of the script: var Netscape=(navigator. You will add JavaScript functions to this HTML document to animate the mouse. Notice that the <img> tag also has an ID attribute defined. This statement sets a variable. which will be true if the browser is a version of Netscape.”> <img ID=”mouseimg” src=”mouse.” you created a simple animation that moved a picture of a mouse across the Web page. left:150. The following is the basic HTML document: <html> <head> <title>Follow that Mouse!</title> </head> <body onLoad=”Setup(). Later. . you’ll improve upon this example by making the graphic mouse follow the mouse pointer across the screen. you’ll create a simpler version of the animation that follows the mouse pointer directly. the methods for detecting and following mouse movement are different in Netscape and Internet explorer. First.gif” width=”100” height=”100” border=”0”> </div> </body> </html> This document defines a layer with the ID attribute “mouse” using a <div> tag. “Using DHTML for Animation.302 Hour 22 Following the Mouse Pointer In Hour 16. and false if it is not. Detecting the Browser Type Although this example will use cross-browser DHTML.

getElementById) return.” Creating the Move Function Now that event capturing is set up. ypointer=event. Finally. For details on how event capturing works in Internet Explorer and Netscape.getElementById) return. } 22 This function first verifies that the getElementById method is supported by the browser.captureEvents(Event. “Responding to Events. This is necessary because the onMouseMove event is generated frequently and is not detected by default. and will set up event capturing so that the onMouseMove event can be detected. function Move(e) { if (!document. Because the event handler is assigned using JavaScript. if (Netscape) event=e. } . if (event.pageX) { // Netscape. This function will update the position of the layer to track the mouse pointer. see Hour 8.Creating Complex Animations 303 Capturing Events The Setup function will be called by the <body> tag’s onLoad event handler. the Move function will be called each time the mouse moves over the Web page..pageY. since it will be used in other functions. xpointer=event.onmousemove=Move. the Netscape variable is tested and the document.pageX. if (Netscape) document.getElementById(“mouse”). obj=document.. Next.captureEvents property is set for Netscape browsers. the function assigns the onMouseMove event handler for the document to the Move function. an onMouseMove attribute is unnecessary within the body of the HTML document. document. Here is the Setup function: function Setup() { if (!document.MOUSEMOVE). This property tells Netscape which events can be captured.

1 shows the complete example. } obj.top=ypointer .appName. xpointer=event.y.style.pageX.x) { // Internet Explorer. if (Netscape) event=e. } This function first finds the object for the layer and stores it in the obj variable.pageY.left=xpointer . the function finds the current mouse pointer position and stores it in the xpointer and ypointer variables. 50 pixels are subtracted from the position to center the graphic at the mouse pointer position. Next.x. Depending on the browser. function Move(e) { if (!document. } else if (event. the Move function sets the position of the layer to the same position as the mouse pointer.style.indexOf(“Netscape”) != -1).304 Hour 22 else if (event. obj=document. since Netscape does not set the event variable automatically. LISTING 22. it assigns it to the Move function’s argument. obj.. xpointer=event.pageX and event. ypointer=event.1 Following the Mouse Pointer <html> <head> <title>Follow that Mouse!</title> <script language=”JavaScript”> var Netscape=(navigator.x and event.50. Next. ypointer=event. or the event.pageX) { // Netscape..pageY properties. you simply need to combine the script functions you have created with a simple HTML document. if (event.y properties.. ..getElementById) return.50. Putting It All Together To complete this example. Listing 22. the position is found either in the event.x) { // Internet Explorer.x. since the graphic is 100 pixels square.getElementById(“mouse”). xpointer=event.. Finally..

top:150.y.”> <h1>Animation in DHTML</h1> <div ID=”mouse” style=”position:absolute. the onLoad event handler of the <body> tag calls the Setup function to begin the animation.left=xpointer .top=ypointer . To test this example.starlingtech. } obj.50. if (Netscape) document. load it into a browser.0 or later.gif” width=”100” height=”100” alt=”” border=”0”> </div> </body> </html> 22 In this listing. } function Setup() { if (!document. } </script> </head> <body onLoad=”Setup().”> <img src=”mouse.onmousemove=Move. obj. Figure 22. However. which you can download from this book’s Web site at http://www. Since this example uses the W3C DOM for positioning. See Hour 17.getElementById) return. This function sets up the event handler for mouse movement.style. This example requires a graphic. left:150.gif. and the Move function is called when the mouse moves.style. it requires Netscape 6 or later or Internet Explorer 5.50. document.captureEvents(Event. as if it’s stuck to the pointer. “Dealing with Browser Differences. The mouse graphic should move continuously as the mouse pointer moves.” for techniques you can use. mouse.Creating Complex Animations 305 LISTING 22.1 shows Netscape’s display of the example in action.com/dhtml/.0 browsers. . it could be adapted to work with the 4.MOUSEMOVE).1 continued ypointer=event.

306

Hour 22

FIGURE 22.1 The animation following the mouse pointer.

Animation with Multiple Images
While the example you’ve created is more sophisticated than previous examples, it is still simplistic: the graphic doesn’t change, and it acts like an extension of the mouse pointer. In this section, you’ll improve the example in two ways: first, you will use four different graphics to make the mouse change direction as it moves. Second, the mouse will move at a constant speed and won’t immediately catch the mouse pointer.

Creating the Graphics
The new example will use four different graphics, one for each of four directions the mouse’s nose can point. Figure 22.2 shows all four of the graphics you will use in this example.

These graphics, along with the graphic for the previous example and the listings for this hour, are available on this book’s Web site: http://www.starlingtech.com/dhtml/.

Creating Complex Animations

307

FIGURE 22.2 The four graphics for the improved animation.

22

Setting Up Positioning Variables
This script will use several global variables to keep track of the animation’s status. The following are the declarations for these variables:
var var var var x=150,y=150; dx=0,dy=1; xpointer=0,ypointer=0; counter=0;

The x and y variables will store the current position of the animated mouse graphic. The dx and dy variables will store the current direction of motion: dx values of –1 or 1 will move left and right, and dy values of –1 or 1 will move up and down. The xpointer and ypointer variables will store the current position of the mouse pointer. The counter variable will count animation cycles and allow changes of direction.

Setting Up Events
As before, your script will use a Setup function to set up the event handler for mouse movement. The following is the new Setup function:
function Setup() { if (!document.getElementById) return; if (Netscape) document.captureEvents(Event.MOUSEMOVE); document.onmousemove=SetPointer; a1 = new Image(); a1.src=”mouseR.gif”; a2 = new Image(); a2.src=”mouseL.gif”; a3 = new Image();

308

Hour 22

a3.src=”mouseU.gif”; a4 = new Image(); a4.src=”mouseD.gif”; Move(); }

This function is different in two ways: first, it assigns the SetPointer function as the event handler rather than the Move function. Second, the statements using the a1 through a4 variables are used to preload the four images used in the animation.

The statement a1 = new Image(); creates an Image object, and assigning the src property of the object loads the image into the browser’s cache. The preloaded images are not displayed until their names are assigned to an image’s src property.

The final line of the Setup function calls the Move function to begin the animation. This function will repeat itself to move the graphic repeatedly on a timer.

Tracking the Mouse Pointer
The SetPointer function will be called by the onMouseMove event each time the mouse moves. This function assigns the xpointer and ypointer variables, as the Move function did previously:
function SetPointer(e) { if (Netscape) event=e; if (event.pageX) { // Netscape... xpointer=event.pageX; ypointer=event.pageY; } else if (event.x) { // Internet Explorer... xpointer=event.x; ypointer=event.y; } }

This version of the script will declare xpointer and ypointer as global variables. They are set by the SetPointer function, and will be read by the Move function.

Creating the Move Function
Rather than executing each time the mouse pointer moves, the Move function will now execute on a timer. Here is the new Move function:

Creating Complex Animations

309

function Move() { if (!document.getElementById) return; obj=document.getElementById(“mouse”); xdist=Math.abs(xpointer-x); ydist=Math.abs(ypointer-y); ChangeDirection(xdist,ydist); if (xdist>2) x += dx*2; if (ydist>2) y += dy*2; obj.style.left=x - 50; obj.style.top=y - 50; window.setTimeout(“Move();”,1); }

22

This function first checks that the getElementById method is supported, and uses this method to find the object for the layer. Next, it calculates the distance from the mouse graphic to the mouse pointer, and stores it in the xdist and ydist variables.

The Math.abs function returns the absolute value of its argument. This is essentially the value with its negative sign removed: Math.abs(1) is 1, and Math.abs(-1) is also 1.

Next, the Move function passes xdist and ydist to the ChangeDirection function. This function will change the animation’s direction if needed. Next, the dx and dy variables are used to change the x and y position, and the layer is moved to this position. Finally, the setTimeout method calls the Move function again in one millisecond.

Changing Direction
The ChangeDirection function checks the current distance between the graphic and the mouse pointer, and potentially changes the animation’s direction to head closer to it. The following is the JavaScript code for this function:
function ChangeDirection(xdist,ydist) { counter++; if (counter<30 || (xdist<2 && ydist<2)) return; counter=0; if (xdist > ydist) { dx = (xpointer-x<0) ? -1 : 1; dy = 0; } else if (ydist > xdist) { dy = (ypointer-y<0) ? -1 : 1; dx = 0; } if (dx>0) fn=”mouseR.gif”; if (dx<0) fn=”mouseL.gif”;

310

Hour 22

if (dy>0) fn=”mouseD.gif”; if (dy<0) fn=”mouseU.gif”; document.images[“mouseimg”].src=fn; }

counter

This function first increments the counter variable. The if statement exits the function if has not yet reached 30. It also exits if the xdist and ydist variables are less than two, meaning the animated mouse has “caught” the mouse pointer.

The counter variable is used to make sure the graphic (and its direction) doesn’t change too rapidly, which would create a flickering effect.

If counter has reached 30, it is reset to zero. Next, dx and dy are set depending on which distance is greater. These values are set to –1 or 1 depending on the direction the graphic needs to move. The final four if statements set the fn variable depending on the current direction: mouseR.gif for right, mouseL.gif for left, mouseD.gif for down, or mouseU.gif for up. The src property for the image is set to change the image.

Workshop: Completing and Testing the Animation
To complete this example, you need to combine the JavaScript functions you’ve created into the HTML document. Listing 22.2 shows the complete HTML document. LISTING 22.2 The Complete Animation Example

<html> <head> <title>Follow that Mouse!</title> <script language=”JavaScript”> var x=150,y=150; var dx=0,dy=1; var xpointer=0,ypointer=0; var counter=0; var Netscape=(navigator.appName.indexOf(“Netscape”) != -1); function SetPointer(e) { if (Netscape) event=e; if (event.pageX) { // Netscape... xpointer=event.pageX;

Creating Complex Animations

311

LISTING 22.2

continued

ypointer=event.pageY; } else if (event.x) { // Internet Explorer... xpointer=event.x; ypointer=event.y; } } function Move() { if (!document.getElementById) return; obj=document.getElementById(“mouse”); xdist=Math.abs(xpointer-x); ydist=Math.abs(ypointer-y); ChangeDirection(xdist,ydist); if (xdist>2) x += dx*2; if (ydist>2) y += dy*2; obj.style.left=x - 50; obj.style.top=y - 50; window.setTimeout(“Move();”,1); } function ChangeDirection(xdist,ydist) { counter++; if (counter<30 || (xdist<2 && ydist<2)) return; counter=0; if (xdist > ydist) { dx = (xpointer-x<0) ? -1 : 1; dy = 0; } else if (ydist > xdist) { dy = (ypointer-y<0) ? -1 : 1; dx = 0; } if (dx>0) fn=”mouseR.gif”; if (dx<0) fn=”mouseL.gif”; if (dy>0) fn=”mouseD.gif”; if (dy<0) fn=”mouseU.gif”; document.images[“mouseimg”].src=fn; } function Setup() { if (!document.getElementById) return; if (Netscape) document.captureEvents(Event.MOUSEMOVE); document.onmousemove=SetPointer; a1 = new Image(); a1.src=”mouseR.gif”; a2 = new Image(); a2.src=”mouseL.gif”; a3 = new Image(); a3.src=”mouseU.gif”; a4 = new Image();

22

312

Hour 22

LISTING 22.2

continued

a4.src=”mouseD.gif”; Move(); } </script> </head> <body onLoad=”Setup();”> <h1>Animation in DHTML</h1> <div ID=”mouse” style=”position:absolute; left:150; top:150;”> <img ID=”mouseimg” src=”mouseR.gif” width=”100” height=”100” border=”0”> </div> </body> </html>

To test this document, save it and load it into a browser. Now, rather than being stuck to the mouse pointer, the animated mouse will chase the pointer, not stopping until it catches it. Figure 22.3 shows Internet Explorer’s display of the animation in action.
FIGURE 22.3 The new animation example in action.

Summary
In this hour, you’ve created two animation examples, including one that combines dynamic images with DHTML animation to create a complete effect.

Creating Complex Animations

313

In the next hour, you’ll create another advanced DHTML application: a complete game that uses JavaScript and DHTML to interact with the user.

22

Q&A
Q. Can I hide the mouse pointer and use a graphic as a custom pointer? A. Yes, depending on the browser. See Hour 10, “Using Style Sheet Properties,” for information. Q. Why don’t these animation examples use a separate JavaScript file for the functions? A. While separating HTML and JavaScript can often make life easier, these examples use much JavaScript and very little HTML, so there isn’t much need for a separate document. Nonetheless, you can use a separate script file if you prefer. Q. Can I use more than four graphics for different directions of the animation? A. Yes. If you changed the example to allow diagonal movement, you could add four additional graphics to create a more realistic animation.

Quiz
Test your knowledge of the material covered in this hour by answering the following questions.

Questions
1. Which of the following properties must be set for event capturing in Netscape? a. b. c.
document.mousemove document.captureEvents document.onmousemove

2. Which of the following is the correct command to set the onMouseMove event handler for the document? a. b. c.
document.onmousemove=SetPointer; document.onMouseMove=SetPointer; document.mousemove=SetPointer;

src Answers 1.2 to speed up the mouse graphic’s movement.314 Hour 22 3.onmousemove=SetPointer.mouseimg. try the following exercises: • Try changing Listing 22. . c.src document. 2.images.captureEvents property is required for event capturing in Netscape. c.images[“mouseimg”]. 3. Which property should you change to change the image file displayed by an <img> tag with the ID attribute “mouseimg”? a. document. a. The correct statement is document. b.2 to restrict the animated mouse’s movements to a box within the Web page.images[“mouseimg”].src[“mouseimg”] document. The correct property is document. Exercises If you’d like to experiment further with this hour’s examples before moving on.src. • Add if statements to Listing 22. b. The document.

At this point. This hour covers the following topics: • Creating the HTML document • Planning the dynamic features • Creating graphics for the game • Adding JavaScript functions • Creating the word list • Adding the style sheet • Completing and testing the game . you should feel comfortable working with DHTML and ready to move on to more complicated tasks.HOUR 23 Creating a DHTML Game You’re nearing the end of your 24-hour tour of DHTML. attractive user interface for the game. Using dynamic features will allow you to create a friendly. you’ll create a version of the word-guessing game Hangman using DHTML. In this hour.

js”> </script> <script language=”JavaScript” src=”hangman.1 shows the complete HTML document. Click on a blue letter to guess that letter. You’re allowed a total of seven incorrect guesses. Listing 23. If your guess is correct. the letter turns green and you’re closer to winning . LISTING 23. Notice that the <span> tag with the ID attribute “alphabet” is empty—this will contain a clickable alphabet used .316 Hour 23 Creating the HTML Document The game will use a simple HTML document as its basis. along with a link to a style sheet to format the text.”> <h1>Hangman Game</h1> <p>This is a simple Hangman game that uses DHTML and JavaScript.</b> </td> </tr> <tr> <td valign=”top”> <span ID=”alphabet”></span> </td> </tr> <tr> <td align=”center” id=”theword”> </td> </tr> </table> </body> </html> The table in the body of the page will provide the game display. This document will include links to JavaScript files for the DHTML features.1 The HTML Document for the Hangman Game <html> <head> <title>DHTML Hangman Game</title> <script language=”JavaScript” src=”wordlist.</p> <table> <tr> <td rowspan=”3”> <img ID=”hangman” src=”hangman0.css”> </head> <body onLoad=”Setup().but if your guess is wrong.gif” width=”80” height=”105”> </td> <td> <b ID=”status”>Guess a Letter Below. the letter turns red and you’re closer to hanging.js”> </script> <link rel=”stylesheet” href=”hangman.

and will no longer be clickable links after being guessed once. the <td> tag with the attribute “theword” will display the current word as letters are guessed. keep in mind that the alphabet and word displays will be generated by JavaScript functions.1 The display at the beginning of a game.Creating a DHTML Game 317 ID for guessing letters. and the fonts will be defined by a style sheet. In the meantime. graphics are required. However.com/dhtml/. . and additionally.1 shows how the initial game display will look. this one will take full advantage of the W3C DOM’s dynamic features: • The letters of the alphabet that you click to guess letters will change color to indicate whether the guess was correct. save the HTML document. http://www. 23 This example’s listings are long. Planning Dynamic Features While you could create a Hangman game without using DHTML. which will be added using a script. All of these can be downloaded from this book’s Web site. Similarly. FIGURE 23.starlingtech. Figure 23. You’ll need to create these before the game will work.

0 or later. • The large word display will update with letters and blanks as you guess correct letters. Figure 23. Creating the JavaScript Functions This example will use more JavaScript functions than previous examples in this book. FIGURE 23. Here is a summary of the functions this game will use: . but they’re short and easy to understand.318 Hour 23 • The status line above the alphabet will update with the latest game status.starlingtech. You can download them from this book’s Web site. this feature uses the Level 0 DOM and does not require DHTML.2 The graphics for the Hangman game. the hangman graphic will change with each incorrect guess. Due to the dynamic features used. A link will appear there at the end of the game to allow the user to start a new game. this example will require Netscape 6 or later or Internet Explorer 5. Additionally. http://www. This graphic will be changed to one of eight images depending on the number of incorrect guesses.2 shows all eight of the graphics that will be used in this game. Creating Graphics The HTML document includes a single <img> tag to display the hanging man graphic.com/dhtml/. However.

chosen randomly at the beginning of the game. The gamestatus variable will keep track of the number of incorrect guesses. This will be defined in a separate JavaScript file. . The currentword variable will store the current word as letters are guessed. The following is the definition for the Setup function: function Setup() { if (!document. which you’ll create later this hour. and will handle the game play. The answer variable will store the correct word. 23 Setting Up Variables The game will use three global variables to keep track of the status of the game. The following lines of JavaScript define the global variables: var answer=””. • The Hang function will handle incorrect guesses.getElementById) return. and will display correct letters as they are guessed.currentword=””. DrawAlphabet(). • The Guess function will be called when the user clicks on the alphabet links. and will create the clickable letters for guessing. or when the maximum number of incorrect guesses is reached. The following sections describe each of the functions for the Hangman game. beginning as a series of blanks. • The GameOver function will end the game when the word is guessed completely. • The DrawAlphabet function will be called by Setup. and will choose a random word for each game. The Setup Function The Setup function will execute when you first load the page. var gamestatus=0. and will set up the variables for the game and call other setup-related functions. The game will require one more global variable—an array with a large list of words that can be guessed. • The AddLetter function will be called by Guess.Creating a DHTML Game 319 • The Setup function will start the game when the page loads. • The ChooseWord function will be called by Setup.

createElement(“A”). dispword=document. node.innerHTML=currentword. The String.getElementById(“alphabet”). which you’ll create next.i++) { currentword += “_”.”). it displays the current word by assigning it to dispword’s innerHTML property. node=document.className=”letter”.innerHTML=letter.getElementById(“theword”). node. The for loop executes the remaining statements once for each letter from A-Z. the Setup function finds the object for the word display and stores it in the dispword variable.i<answer. node. alpha.id=letter. DrawAlphabet and ChooseWord. . which contains a string of underscore (_) characters the same length as the answer variable.appendChild(node).320 Hour 23 ChooseWord(). Drawing the Alphabet The DrawAlphabet function is called by the Setup function when the game begins. so the game won’t start unless the browser supports the required DOM features. } dispword. quoted=”\”” + letter + “\””. The for loop constructs the currentword variable.length. These are the character codes for the capital letters A through Z. for (i=65. function DrawAlphabet() { alpha=document. The loop actually sets the variable i to the numbers 65 to 90 in sequence.i++) { letter=String. Next. node. which has been assigned by the ChooseWord function. This function creates the alphabet of clickable letters that will be used for each guess.fromCharCode(i). Finally.fromCharCode method converts each code to the corresponding letter.setAttribute(“href”. it calls two other setup functions.i<91.”javascript:Guess(“+quoted+”). Next. } } This function first finds the object for the <span> element with the ID attribute “alphabet”. for (i=0. } This function first checks the getElementById method.

random function to choose a random number between zero and the length of the words array.getElementById(“status”). if (answer. and the new node is appended to the alphabet <span> element.color=”red”.getElementById(letter). This function will be called when one of the letters of the alphabet is clicked to make a guess.createElement(“span”). You’ll define this array later with a list of potential words. answer=words[num]. if (currentword==answer) GameOver(“You Win! “). letter. the letter G will be linked to this URL: javascript:Guess(“G”).displetter). node=document. node. the className of the <a> element is set to “letter”. and assigns the answer variable to the corresponding element of the words array. The following is the Guess function: function Guess(letter) { stat=document.replaceChild(node. alpha. displetter=document. is the letter currently being guessed.Creating a DHTML Game 321 In each iteration of the loop. function ChooseWord() { num=Math.getElementById(“alphabet”). The innerHTML property is set to display the letter. Its parameter.random()*words.indexOf(letter) != -1) { AddLetter(letter). Handling Guesses The Guess function will handle the actual game play. 23 Choosing a Word The ChooseWord function is called by the Setup function. For example.length). . This class will be used to format the alphabet with a style sheet.innerHTML=”Incorrect! Guess again!”.style. A new <a> node is created with the ID attribute of the current letter. the letter variable stores the current letter. Last but not least. node.innerHTML=”Correct! Guess another letter.style. node. This function chooses a random word to be guessed in each round of the game.floor(Math.”.color=”green”.id=letter. node.toUpperCase(). } else { stat. stat. The href attribute is set to link to the Guess function. alpha=document.innerHTML=letter. } This function uses JavaScript’s built-in Math.

it calls the AddLetter function.length.charAt(i). which adds the guessed letter to currentword and displays it. function AddLetter(letter) { dispword=document.i++) { if (answer. and uses the replaceChild method to replace the <a> node with the new <span> node. First.322 Hour 23 alpha. Hang(). Displaying Correct Letters The AddLetter function will be called by the Guess function. The innerHTML and id properties are set to the letter. the alphabet display. This function will update the game status and the hangman graphic. In the figure. Figure 23. it calls the GameOver function to end the game.replaceChild(node. This function updates the currentword variable with the guessed letter.color property to green. It then displays a congratulatory message in the status area. the else clause takes over. } .i<answer. If the guessed letter was not found in the answer. } } This function first finds objects for three parts of the Web page: stat. the Guess function creates a new <span> node.getElementById(“theword”). else newword += currentword. using the indexOf method.3 shows how the game will appear in progress.innerHTML=currentword. the if statement determines whether the letter appears in the answer. the status line within the table. If the guess was correct. This node will replace the <a> node for the letter. a correct letter has just been guessed. sets node’s style. alpha. so it can’t be guessed again. } currentword=newword. dispword. and displetter. If currentword is now equal to the answer variable. It replaces the <a> node with the <span> node. Next.charAt(i)==letter) newword += letter. newword=””. This first displays a message in the status area and sets node’s color to red. and calls the Hang function.displetter). the <a> element for the letter that is being guessed. and displays it in the game area. for (i=0.

which stores the number of incorrect guesses. newsrc=”hangman” + gamestatus + “. The following is the GameOver function: . Ending the Game The GameOver function is called by the Guess function if the game ends with a successful guess. The for loop creates with the letters and blanks of the current word. It changes the hangman graphic to the corresponding image.3 The Hangman game in progress.Creating a DHTML Game 323 FIGURE 23. } This function increments the gamestatus variable. combined with the new letter that was guessed. Updating the Hangman Graphic The Hang function is called each time a letter is guessed incorrectly: function Hang() { gamestatus++.images[“hangman”]. The currentword variable is replaced with the value of newword. and by the Hang function if the maximum number of incorrect guesses is reached.gif”. document. if (gamestatus==7) GameOver(“Sorry! “). Finally it calls the GameOver function to end the game if gamestatus has reached seven incorrect guesses. and it is displayed in the word display area. after a correct guess.src=newsrc. 23 newword This function first finds the object for the word display area.

getElementById(“theword”).replaceChild(node. newlink+=” to start a new game. dispword.i<91.getElementById(letter). it displays the answer in the word display area. which will start a new game. LISTING 23. Next.getElementById(“status”).i++) { .i<answer. This way.getElementById(“theword”). node. stat. } // end if } // end for } This function first creates a link to the location. for (i=65.innerHTML=”<b ID=’gameover’>GAME OVER</b> .“ + text + newlink.oldnode). For each letter that is still a link.className=”letter”. the for loop finds each of the elements within the <span> area for the alphabet. if you lose the game.i++) { letter=String.getElementById(“alphabet”). newlink=” <a href=’javascript:location.createElement(“span”).reload method.’>Click Here</a>”.innerHTML=answer. ChooseWord(). oldnode=document. you can combine them into a JavaScript file.fromCharCode(i). along with the words GAME OVER and the text sent by the Guess or Hang functions. DrawAlphabet(). in the newlink variable. Completing the JavaScript File Now that you have created the JavaScript functions to handle the game play.2 shows the complete JavaScript file. node.length. Listing 23. function Setup() { if (!document. alpha.324 Hour 23 function GameOver(text) { stat=document. This prevents any guessing after the game has ended.2 The Complete Hangman JavaScript File var answer=””. Finally. in the status area.currentword=””. it replaces it with a new <span> node. dispword=document. if (oldnode. alpha=document. var gamestatus=0.innerHTML=letter.reload(). for (i=0. It stores this link.nodeName==”A”) { node=document.”. you can see what the correct answer was. dispword=document.getElementById) return.

”.style. node.charAt(i)==letter) newword += letter.2 continued currentword += “_”. node. alpha=document.className=”letter”.getElementById(“status”). newword=””. Hang(). node. node=document. for (i=0. } } function ChooseWord() { num=Math. } function DrawAlphabet() { alpha=document.random()*words.innerHTML=currentword.length).createElement(“span”).displetter).”javascript:Guess(“+quoted+”).getElementById(“alphabet”).color=”red”.style.replaceChild(node. } } function AddLetter(letter) { dispword=document.i++) { letter=String.getElementById(letter).id=letter.fromCharCode(i).appendChild(node).id=letter. node. if (answer. } function Guess(letter) { stat=document. quoted=”\”” + letter + “\””. node.innerHTML=”Incorrect! Guess again!”. 23 . displetter=document.innerHTML=letter.i<91. alpha. alpha.”).innerHTML=letter. node. answer=words[num].getElementById(“theword”). } else { stat.displetter).Creating a DHTML Game 325 LISTING 23. for (i=65.innerHTML=”Correct! Guess another letter.toUpperCase().length. } dispword. node. if (currentword==answer) GameOver(“You Win! “).replaceChild(node.getElementById(“alphabet”).indexOf(letter) != -1) { AddLetter(letter).createElement(“A”).floor(Math. node=document.i<answer.color=”green”. stat. node.i++) { if (answer.setAttribute(“href”. alpha.

alpha=document.getElementById(“alphabet”). Listing 23.images[“hangman”].js in the same directory as the HTML file.innerHTML=currentword.getElementById(“theword”).gif”. newlink=” <a href=’javascript:location.createElement(“span”).i++) { letter=String.oldnode). dispword. } // end if } // end for } To use the JavaScript file. } function Hang() { gamestatus++.fromCharCode(i). Creating the Word List The word list for the game will be stored in a separate JavaScript file.nodeName==”A”) { node=document.326 Hour 23 LISTING 23. newsrc=”hangman” + gamestatus + “. node. alpha. if (oldnode.innerHTML=”<b ID=’gameover’>GAME OVER</b> .charAt(i). stat. save it as hangman. node.getElementById(“status”).innerHTML=letter. dispword=document.src=newsrc.className=”letter”.innerHTML=answer. since you still need to create the word list and the style sheet. . if (gamestatus==7) GameOver(“Sorry! “).reload(). newlink+=” to start a new game. You can’t test the game yet. dispword.“ + text + newlink. for (i=65.i<91. } currentword=newword. } function GameOver(text) { stat=document. document. though.”.2 continued else newword += currentword.replaceChild(node.getElementById(letter). oldnode=document.3 shows this JavaScript file.’>Click Here</a>”.

3 The Word List JavaScript File var words = new Array( “accept”.”freedom”. ”whether”.”select”.”expect”.”volume”. “nearly”.”demand”. “toward”.”realize”.”former”.”marriage”.”southern”.”picture”.”moment”.”service”.”charge”.”problem”. “source”.”forget”. but also perform some important functions: in particular. You’ll find a longer word list on this book’s Web site.”choice”.com/dhtml/.”series”.”various”.”square”.”finish”.”rather”.”effect”.”remember”. “prevent”.”hospital”.”animal”.”research”. http://www.”physical”.”another”. This word list is short for the sake of simplicity.”actually”.”office”.”answer”.”manner”.”within”. “happen”.”except”. which declares the words array and fills it with about 150 words.”direct”. Listing 23.”supply”.”larger”.”product”.”follow”.”morning”.”trouble”. they create large letters with space between them in the current word display.”interact”. Workshop: Adding the Style Sheet The final step in creating the game is to create the style sheet.”normal”.”behind”.”across”. “audience”. “instance”.”addition”.”minute”. “suddenly”.”suffer”.”concern”.4 shows the complete style sheet.”control”. “maintain”.”fiscal”. “evidence”.”matter”.”modern”.”believe”.”market”.”interest”.”private”.”reaction”.”window”.”congress”.”number”. “analysis”.”military”.”worker”. “finger”.”account”.”weapon”.”language”.”during”.”reason”.”spring”.”object”.”instead”. save it as wordlist.”explain”.”support”.”produce”.”remain”.”certain”.”chance”.”station”. “section”.”really”. “period”.”probably”.”extend”.”herself”. “division”.”example”.”suppose”.”before”.”remove”.”several”.”settle”.”nothing”.”involve”. “question”.”material”.”permit”. 23 This file is essentially a single JavaScript statement.”better”.”receive”.”summer”.”design”.”manager”.”detail”.”specific”.”higher”.”century”.”process”.”continue”.”wonder”.”special”.”anything”. To add the word list to the game.”dollar”.”change”.”consider”.”describe”. “method”.”doctor”.”usually”.starlingtech.”anyone”.”serious”.”develop”.”without”. “complete”.”person”.js in the same folder as the other HTML and JavaScript files.”police”.”western”.”action”.”become”.”million”.”report”.”economic”.”writer”).”because”. The styles not only make the game look good.”require”.”obtain”. “central”.”effort”. “religion”.”history”. “defense”. .”either”.Creating a DHTML Game 327 LISTING 23.”contain”.”announce”.”foreign”.”personal”.”himself”.”suggest”.”however”.”express”.”officer”.”achieve”.

font-weight: bold.} .4 shows the game display after a game has been completed (and lost). the JavaScript file for the word list. letter-spacing: 5px. It also sets styles for the . After all of the files are assembled. To add the style sheet to the game. save it as hangman.letter class. the JavaScript file for the functions. the alphabet for guessing letters. text-decoration: none. letter-spacing: 12px. The text-decoration attribute removes the underlines from the linked letters.letter {color: silver. The eight hangman graphics also need to be in the same folder. #alphabet. } A. which will be assigned to each letter in the alphabet. . Figure 23.4 The Style Sheet for the Game #theword {font-size: 60px. To make the game work. and the style sheet in the same folder. you can load the HTML document into a browser and try the game. font-family: monospace. to blue for linked letters and silver for unlinked ones. color: blue.} #alphabet {font-size: 19px.} This style sheet sets styles for three explicit identifiers: #theword. the current word display.} #gameover {color: red. the words GAME OVER that will be displayed by the GameOver function. Testing the Complete Example You are now ready to test the Hangman game.328 Hour 23 LISTING 23.letter {text-decoration: none.css in the same folder as the HTML and JavaScript files. Their color is also set. and #gameover. you’ll need to store the HTML file. font-weight: bold.

You can expand the word list with words of any size. Q. . its entry in the alphabet is changed to no longer link to the Guess function. but the words in the included list range from 6-8 letters to make for a consistent game. JavaScript. Is there a limit on the length of words used in this game? A. Why doesn’t the game check whether a letter has already been guessed? A.Creating a DHTML Game 329 FIGURE 23. 23 Summary In this hour. This is just the beginning—you can actually create even more complex applications using DHTML. Q&A Q. so it’s actually impossible to guess the same letter twice. you’ve created a more complex example that uses DHTML.4 The game display after a game is lost. you’ll explore some tips to use DHTML more effectively. and learn what the future holds for DHTML and the Web. No. In the final hour of this book. When a letter is guessed. The letter simply won’t be clickable the second time. and CSS styles to create a complete game application. Words with fewer letters are harder to guess.

3. It effectively clears the contents of the alphabet and word displays. b. a. c. c.random function returns a random number. a. Which of the following is the correct JavaScript function to return a random number? a. Which of the following style sheet selectors refers to a CLASS attribute? #alphabet BODY .reload method used to start a new game? A. The character code 65 represents the capital letter A.rand() 2. Why is the location. 2. The .letter selector refers to a class. b. but would require more code. . Which of the following characters is represented by the character code 65? A Z a 3. This could also be done without reloading. Questions 1. allowing them to be re-created by the Setup function. This method has the same effect as the browser’s Reload button.letter Answers 1.330 Hour 23 Q. b. c. random() Math. a. The Math. Quiz Test your knowledge of the material covered in this hour by answering the following questions. c.random() Math. b.

23 . try the following exercises: • Add a feature to the Hangman game to display the number of incorrect guesses left in the status area after each incorrect guess. • Modify the example so that the words GAME OVER that appear at the end of the game are green in color if the game was won. and red if it was lost.Creating a DHTML Game 331 Exercises If you’d like to experiment further with this hour’s example before moving on.

.

In this hour. and learn where to go to continue your DHTML education. and created many working examples. examples.HOUR 24 DHTML Tips and Tricks Welcome to the final hour of your 24-hour tour of DHTML! You’ve now explored the many things that DHTML can do. This hour covers the following topics: • Creating DHTML tool tips • The future of DHTML • Learning more about DHTML • Creating a scrolling text window . You’ll also take a look at what the future holds for DHTML. you’ll create two more simple. but useful.

starlingtech. This is a common use for DHTML.org/”>The W3C</a></li> </ul> <div ID=”tip-thisbook” style=”position:absolute.” href=”http://www.” href=”http://www. LISTING 24. margin-top:0. visibility:hidden. or floating text descriptions of links.” href=”http://www. you can download this hour’s examples from this book’s Web site: http://www. One such example is displaying tool tips.1 The HTML Document for the Tool Tip Example <html> <head> <title>DHTML Tool Tips</title> <script language=”JavaScript” src=”tooltip.starlingtech.js”> </script> </head> <body style=”margin-left:0.</p> <ul> <li><a ID=”thisbook” onMouseOver=”ShowTip(‘thisbook’). there are still some useful things that can be done. each with event handlers that will display the tips. for each of the links in the bulleted list below.com/”>Microsoft</a></li> <li><a ID=”netscape” onMouseOver=”ShowTip(‘netscape’). As usual.” href=”http://www.1 shows the HTML document. often with a minimum of scripting.com/dhtml/”>This Book</a></li> <li><a ID=”microsoft” onMouseOver=”ShowTip(‘microsoft’). or pop-up hints. Creating the HTML Document This example begins with an HTML document. Listing 24.”> Check out this book’s Web site! </div> .netscape. This is a great way to describe links without taking up space. This will define a bulleted list of links.w3.com/”>Netscape</a></li> <li><a ID=”w3c” onMouseOver=”ShowTip(‘w3c’).”> <h1>DHTML Tool Tips</h1> <p>This example displays “tool tips”.334 Hour 24 Creating Tool Tips While you’ve explored much of what DHTML can do.” onMouseOut=”HideTip(‘microsoft’).microsoft.” onMouseOut=”HideTip(‘thisbook’).com/dhtml/.” onMouseOut=”HideTip(‘netscape’).” onMouseOut=”HideTip(‘w3c’).

getElementById) return. The following is the JavaScript code for this function: var t=0.setTimeout(“ShowIt(\””+item+”\”). 24 Looking for a challenge? Try creating the JavaScript file for the tips yourself.”> Visit Netscape’s Web site </div> <div ID=”tip-w3c” style=”position:absolute.offsetLeft + thelink.”. Showing Tips If you look at how tool tips work on other Web pages or in your operating system.DHTML Tips and Tricks 335 LISTING 24. Instead. thetip=document. visibility:hidden. } . The ShowTip function will be called when the mouse is over one of the links. thetip.”> Visit Microsoft’s Web site </div> <div ID=”tip-netscape” style=”position:absolute. To test this document. they display only when the mouse pointer hovers over an object for a certain time. thetip. you’ll notice that they don’t display immediately.1000).getElementById(item). this HTML document includes a <div> layer definition for each of the tool tips.offsetTop. The links should be displayed.offsetWidth + 10. thelink=document. You can create the same behavior in DHTML. visibility:hidden.1 continued <div ID=”tip-microsoft” style=”position:absolute.getElementById(“tip-” + item).”> Visit the World Wide Web Consortium </div> </body> </html> Along with the list of links with onMouseOver and onMouseOut event handlers. You should know enough about DHTML by now to do it easily. thetip.style.left=thelink. but the tips won’t work until you add the JavaScript functions.style. These have their visibility style property set to hidden by default.top=thelink. save it and load it into a browser.backgroundColor=”yellow”. visibility:hidden. function ShowTip(item) { if (!document.style. t=window.

See Hour 17. Finally. It sets the style. thetip=document.visibility=”hidden”.left and style. and will store an identifier for the timeout. it finds the object for the tip.e. Here’s the code for this function: function HideTip(item) { if (!document. The only other solution is to check for specific browsers. This was declared as a global variable. thetip. This example’s HTML document sets the left and top margins to zero to avoid this problem. thetip=document. Notice the variable t used with the setTimeout method. This function will make the tip become visible if the mouse remains over the link. tip-thebook). This will be used by the HideTip function to prevent the tip from displaying at the wrong time. “Dealing with Browser Differences. if (t) window.getElementById) return. Next.top properties for the tip based on the link’s offsetLeft and offsetTop properties. it sets the tip’s background color to yellow. to make it appear near the link. } This function first clears the t variable that was used for the timeout. The ShowIt function will make the tip visible. Hiding Tips The HideTip function is called by the onMouseOut event when the mouse moves away from a link. the function sets a timeout to call the ShowIt function in one second. thetip. Next. This function is simple: function ShowIt(item) { t=0.clearTimeout(t).336 Hour 24 Some versions of Netscape 6 report a slightly different offset than other browsers. and finds two objects: the link (i. } .style.getElementById(“tip-” + item).” for information about browser sensing. This function first checks for the needed DOM support.visibility=”visible”. thebook) and the corresponding tip (i.style.getElementById(“tip-” + item).e. and sets its visibility property to show it.

LISTING 24. the clearTimeout method clears the timeout.clearTimeout(t). You can then load the HTML document into a browser and verify that the tips work.getElementById(“tip-” + item). and then looks at the variable t. thetip=document.js. thetip. and sets its visibility property to hide the tip.getElementById) return. } function HideTip(item) { if (!document.getElementById) return. the mouse cursor is over the first link.style.style.top=thelink.1 refers to an external JavaScript file. Figure 24. . Completing the JavaScript File The HTML document in Listing 24. This stops the ShowIt function from making the tip visible if the mouse didn’t stay over the link for the full one second.1000).2 The Complete Tool Tip JavaScript File 24 var t=0. thetip=document.visibility=”visible”.left=thelink. function ShowTip(item) { if (!document.style.setTimeout(“ShowIt(\””+item+”\”).style. if (t) window.getElementById(item). the HideTip function finds the object for the tip. Finally. thelink=document.getElementById(“tip-” + item).getElementById(“tip-” + item). save it as tooltip.DHTML Tips and Tricks 337 This function checks for the required DOM support. } To use this file.visibility=”hidden”.style. tooltip.offsetTop. thetip.2 shows the complete JavaScript file.js in the same folder as the HTML document. thetip. thetip=document. If it is set.”. thetip.backgroundColor=”yellow”.offsetLeft + thelink. In the figure.offsetWidth + 10. } function ShowIt(item) { t=0. This file will contain the JavaScript functions you’ve created. t=window.1 shows the example in action in Netscape 6. Listing 24. thetip.

There is much more to learn. The Future of DHTML DHTML is a relatively new technology. and giving you control over color. you can use DHTML more freely without worrying about older browsers. you might be wondering where to go next.1 The tool tip example in action. and on top of that. and will hopefully support the DOM level 2 and 3 standards completely. Additionally. and it will be displayed as a tool tip. font size. and its potential is only beginning to be realized on the Web.0 and later support an easier way to create tool tips: set the title attribute of a link’s <a> tag to a description. DHTML and other Web technologies are constantly changing. . While the version 4. the new W3C DOM has revolutionized cross-browser DHTML. and you can expect DHTML to start popping up all over the Web. The DHTML alternative here has the advantage of working in other browsers. Internet Explorer 4. Where Do You Go from Here? Having nearly finished your 24-hour look at DHTML.0 browsers supported basic DHTML.338 Hour 24 FIGURE 24. and other aspects. browsers will continue to improve. As more users adopt browsers with W3C DOM support.

the international organization that maintains the standard for JavaScript.org/js/language/js20/index.DHTML Tips and Tricks 339 The Future of HTML and JavaScript HTML itself is changing with the emerging XHTML standard. but you can create one easily with DHTML using two layers. Listing 24. While scrolling messages. For more information. see Netscape’s Mozilla Web site: http://www. . 24 If you improve one of the examples in this book or create something new.0. which defines the layers and the content for the window. you might have seen a few more complex scrolling windows that scroll a few paragraphs of news or links. The W3C has published XHTML 1.1 as a recommendation. there is much more that could be done. a version of HTML that fits into the stricter confines of XML (extensible markup language). on a new version currently known as JavaScript 2. and it will soon make its way to browsers. Netscape is working with ECMA. The JavaScript language is also continuously changing. here’s one final example. “Creating DHTML Text Effects. such as the one you created in Hour 15. Creating the HTML Document The scrolling window example begins with the HTML document. and a smaller layer will show a “window” on the larger layer.3 shows the complete HTML document.” are common on the Web. Workshop: Creating a Scrolling Window Just to show you that you haven’t seen everything DHTML can do. See Appendix A for a list of resources to learn more about DHTML and JavaScript. you can submit it to this book’s Web site and share it with other readers.mozilla. One large layer will contain all of the text. Scrolling windows like this are traditionally created with the Java language. and you can move on to even more impressive DHTML examples.html Learning More While you’ve created a wide range of applications with DHTML in this book.

preventing any of the text from being obstructed.top property to move it relative to the window.top:100”> <p>This is the first paragraph of the scrolling message. The overflow property on the window layer prevents the rest of the content from showing.com/dhtml/”>Links</a>.width:170. you’ll only see part of it at a time. you could format items using a bulleted list. overflow:hidden. border-color:red”> <div id=”thetext” style=”position:absolute. This. contains the text to scroll. thewindow.</p> <div id=”thewindow” style=”position:relative. The message is created with ordinary HTML. will form the small window for text to display in.</p> <p>Entries within the scrolling area can use any HTML tags. They can contain <a href=”http://www.</p> <p><b>[<a href=”javascript:pos=100. creating a scrolling effect. You’ve reached the end. The window is actually a layer that shows a portion of a larger layer.js”> </script> </head> <body onLoad=”Scroll(). along with the left property.height:150.340 Hour 24 LISTING 24.</p> <p>There’s no limit on the number of paragraphs that you can include here. The other. thetext. Since the text doesn’t all fit in the small window. border-style:solid.</p> <ul><li>For example.starlingtech.left:5. . They don’t even need to be formatted as paragraphs.”> <h1>Scrolling Window Example</h1> <p>This example shows a scrolling window created in DHTML.</li></ul> <p>The scrolling ends when the last part of the scrolling text is on the screen. creates a small margin of white space on either side of the window.3 The HTML Document for the Scrolling Window <html> <head> <title>A DHTML Scrolling Window</title> <script language=”JavaScript” src=”window.Scroll(). The text layer is actually ten pixels narrower than the window layer.width:180. border-width:2px.”>Start Over</a>]</b></p> </div> </div> </body> </html> The <div> tags in this document create two nested layers: one. Your script will manipulate the text window’s style.

it uses the setTimeout method to repeat itself in 30 milliseconds. called by the onLoad event handler of the <body> tag. handles the actual scrolling. obj. pos -=1. The last line of the text includes a javascript: link that resets the pos variable and restarts the Scroll function. if (pos < 0-obj.30). . but it’s confined to a separate JavaScript file for clarity. The window should scroll at about the right speed for reading. obj=document. Creating the JavaScript Function This example’s JavaScript function is simple. To use this document.4 shows the complete JavaScript file. LISTING 24. The if statement checks whether the layer has moved to the point where the last part of the text is shown through the window. which will store the text layer’s current position.top property for the text layer to move it to the new position. It then subtracts one from the pos variable. although it should be able to wrap to the small window.style. Listing 24.getElementById(“thetext”). The Scroll function. The Scroll function next sets the style. You can vary the speed by changing the timeout value. save it as an HTML file. } 24 The first line declares the global variable pos. and stops the scrolling.DHTML Tips and Tricks 341 The actual text to scroll is placed within the inner <div> element. This function finds the object for the text layer.setTimeout(“Scroll(). Last of all. function Scroll() { if (!document.4 The JavaScript File for the Scrolling Window var pos=100. It won’t scroll until you add the JavaScript functions in the next section.offsetHeight+130) return.getElementById) return. window. You can use any HTML here. The scrolling stops at the end of the text.top=pos.”.

0 browsers? A. . See Hour 17. and where you can go to further your DHTML education. I hope you’ve enjoyed learning how JavaScript. as displayed by Internet Explorer. Yes. Figure 24. You can then load the HTML document into a browser. Be sure to look at the list of resources in Appendix A to find out how you can learn more. save it as window. you’ve completed your exploration of DHTML by creating two final examples.2 shows Internet Explorer’s display of this example after the scrolling text has reached its final position. Can the tool tip example be modified to work in the 4. CSS.342 Hour 24 To use this document. Time’s up! You’ve reached the end of your 24-hour DHTML course.2 The scrolling window example. Summary In this hour. FIGURE 24. HTML. Q&A Q. “Dealing with Browser Differences.” for a review of cross-browser layers. You’ve also taken a quick look at what the future holds for DHTML. since it uses layers.js in the same folder as the HTML document. and the DOM work together to make DHTML a powerful tool for the Web.

clearTimeout(t). Q. Suppose you have set a timeout using the statement t=window.DHTML Tips and Tricks 343 Q. Yes. HTML 4.setTimeout(0).0 c. window. Which of the following properties prevents the scrolling window text from showing below the window? a. c. why does a scroll bar appear on the right side of the page during the scrolling? A. window.stopTimeout(t). Which of the following is the correct way to prevent the timeout’s statements from executing? a. b. Doesn’t the scrolling window example set the layer’s position to negative numbers? Why doesn’t this create an error? A. This happens when the hidden text layer is longer than the current browser window would hold—even though the bottom part of it is invisible.1 . This simply positions the layer off the top of the screen. In Netscape.setTimeout (statements). This problem doesn’t occur in Internet Explorer. overflow: hidden border-style: solid position: relative 3. DHTML 4.1 b. b.. Which of the following is the latest version of HTML? a. 24 Questions 1. c. Quiz Test your knowledge of the material covered in this hour by answering the following questions. it does—but browsers allow this. 2. XHTML 1. window.

344 Hour 24 Answers 1. try the following exercises: • In Hour 22. hidden property prevents the scrolling text from showing out- 3.1 display at the mouse cursor’s location instead of at a fixed location. Exercises If you’d like to gain more experience with DHTML. . The overflow: side the window. DHTML (choice B) isn’t actually a version of HTML.” you created an animated mouse that follows the mouse cursor. 2.com/dhtml/. and look for more examples from the author and other readers. “Creating Complex Animations. b. XHTML 1.setTimeout method from executing. The window.clearTimeout method can stop the statements in the window.1 is the latest version of HTML.starlingtech. • Visit this book’s Web site at http://www. c. Check for updates to the book. a. Use the techniques you learned in that example to make the tooltips in Listing 24.

PART VII Appendixes Hour A Other JavaScript and DHTML Resources B Glossary C Browser Compatibility Chart D DOM Quick Reference .

.

and serve as references while you develop applications of your own. JavaScript Web Sites The following Web sites will help you learn more about JavaScript: • JavaScript Developer Central. The resources listed in this appendix will help you learn more about DHTML and JavaScript.html . includes links to a wide variety of JavaScript resources.netscape.com/tech/javascript/index. there’s more to learn if you’re willing.APPENDIX A Other JavaScript and DHTML Resources While you’ve learned quite a bit about DHTML in 24 hours. part of Netscape’s DevEdge site. http://developer.

com’s DHTML Lab has many DHTML tutorials and examples. http://www. http://www. and other Web technologies.irt. http://developer. maintained by the author of this book. http://www.com/ • The JavaScript FAQ. CSS. http://developer.irt.htmlcenter. includes sample scripts and answers to many JavaScript questions. both for the new DOM and for 4.webreference.org/xref/dom_objects. has many JavaScript links and examples.com/ • WebReference.348 Appendix A • Netscape’s JavaScript Reference is the definitive JavaScript reference.org/script/script.com/ Dynamic HTML Web Sites You’ll find the following resources useful for learning more about DHTML and CSS: • The Web Design Group has several useful references about HTML and CSS.com/ • Internet Related Technologies’ DOM cross-reference describes the objects of the W3C DOM and their support in current browsers. http://www.0 browsers.htm • The JavaScript Workshop. news.htmlhelp. from Internet Related Technologies.htm .org/ • HTMLcenter has reviews.com/dhtml/ Other Sites The following sites might also be of interest: • The W3C (World Wide Web Consortium) is the definitive source for information about the HTML and CSS standards.jsworkshop.htm • Website Abstraction has a number of sample scripts and JavaScript tutorials. This site also has a complete list of objects and properties for the Level 0 DOM. http://wsabstract. http://www. JavaScript. and tutorials about HTML. and some DHTML information too. http://www.com/docs/manuals/js/client/jsref/index.w3.netscape.

com/ • SlickEdit. ISBN 0-672-32077-0. is a full-featured HTML editor for Windows. • Sams Teach Yourself Web Publishing with HTML and XHTML in 21 Days. but includes features to automatically add HTML tags. TextPad is shareware. by Michael Moncur. Third Edition. and CSS. from Bare Bones Software. ISBN 0-672-32201-3. JavaScript. is a popular HTML and text editor for Macintosh systems. and other languages. Vincent and John Krutsch.com/ . by Laura Lemay. • JavaScript Developer’s Dictionary. from Helios Software Solutions. and a fully-working version can be downloaded from this site. http://www. It’s a fast. by Alexander J. from MicroEdge.slickedit. Development Tools The following tools might make your life easier as you develop DHTML Web pages: • HomeSite.com/ A • TextPad.allaire. and to easily create complicated HTML elements such as tables. Java.textpad. http://www. http://www.bbedit. Second Edition. is a sophisticated programmer’s editor for Windows and UNIX platforms. I use it to create and maintain all of my sites. is a Windows text editor intended as a replacement for the basic Notepad accessory. It is similar to a text editor.com/ • BBEdit. from Allaire and Macromedia. you might find these other books useful: • Sams Teach Yourself JavaScript in 24 Hours. useful editor. http://www. ISBN 0-672-32025-8.Other JavaScript and DHTML Resources 349 Other Books If you would like to learn more about JavaScript and HTML. Syntax coloring helps you create valid HTML. and also includes a number of features for working with HTML.

shtml CGI Resources Sometimes JavaScript and DHTML can’t do everything you need.w3. The following Web sites have information about CGI and server-side programming languages: • The CGI Resource Index has links to thousands of CGI scripts. It works with Netscape 4. display variable values. Find out more about this language at Perl.org/projects/venkman/ • Microsoft Script Debugger works with JavaScript and VBScript in Internet Explorer.com/2000/10_06/webauthors/10_06_00_1.html • Netscape’s Mozilla team is working on a debugger for Netscape 5 and 6.perl.webreview.x.org/ • Netscape’s JavaScript debugger allows you to set breakpoints.netscape.mozilla.350 Appendix A Debugging Tools and Resources You might find the following software tools and sites useful when debugging JavaScript and DHTML applications: • CSE HTML Validator. It can also be integrated with HomeSite. is an excellent stand-alone utility for Windows that checks HTML documents against your choice of HTML versions.ht1mlvalidator. http://cgi.com/library/en-us/sdbug/Html/sdbug_1.resourceindex. http://www. You can copy some of these to your own server.microsoft. http://msdn. http://www.asp • WebReview. and several other HTML and text editors.com/software/jsdebug. TextPad. from AI Internet Solutions. Find out more here: http://www. while others are remotely hosted services. Just enter your URL. and still among the most popular. http://developer. and it will be immediately checked for HTML compliance. http://validator. http://www.com has an excellent tutorial that covers the basics of JavaScript debugging.com/ • Perl is the original language for CGI programming.com/ • The W3C’s HTML Validation Service is a Web-based HTML validator.com/ .com. and perform other debugging tasks.

com/ In addition. you might find the following books useful: • Sams Teach Yourself CGI in 24 Hours. http://php.resourceindex. ISBN 0-672-31804-0 • Sams Teach Yourself Perl in 24 Hours. ISBN 0-672-31880-6 • Sams Teach Yourself PHP4 in 24 Hours. http://www. by Matt Zandstra.Other JavaScript and DHTML Resources 351 • PHP is a newer open-source language that works on Web servers. by Rafe Colburn. by Clinton Pierce.php. Full documentation is available at the official PHP site.net/ • The PHP Resource Index has links to many freely available PHP programs. ISBN 0-672-31773-7 A . and its simplicity makes it a perfect choice for those experienced with JavaScript.

.

alignment. Boolean false. Arguments are specified within parentheses in the function call. . margins. A type of variable that can store only two values: true and Browser sensing A scripting technique that detects the specific browser in use by clients to provide compatibility for multiple browsers. and other aspects of the element defined by the tag. Argument A parameter that is passed to a function when it is called. Attribute A property value that can be defined within an HTML tag. colors. Child node In the DOM.APPENDIX Glossary B Anchor In HTML. Arrays can also use alphanumeric keys. Cascading Style Sheets (CSS) The W3C’s standard for applying styles to HTML documents. CSS can control fonts. Anchors can also act as links. called an index. Array A set of variables that can be referred to with the same name and a number. specified using the <a> tag. a named location within a document. a node that is contained by the current node. and positioning. Attributes specify style. borders.

css extension. such as a DOM method. JavaScript. often the result of a user’s action.354 Appendix B Class An attribute that can be assigned to one or more HTML tags within a document. . A JavaScript statement or function that will be executed when an event Event capturing A browser feature that allows you to enable events that are not detected by default. External style sheet A style sheet that is stored in an external file. CSS. since style sheets can provide the same capability. CSS rules can be made to affect all elements within a class. and operators that can be evaluated to a single value. such as mouse movement. an element is a single node defined by an HTML tag. Dynamic HTML (DHTML) The combination of HTML. Event handler occurs. Document Object Model (DOM) The set of objects that JavaScript can use to refer to the browser window and portions of the HTML document. referred to with an index. usually using the if statement. The W3C (World-wide Web Consortium) DOM is a standardized version supported by the latest browsers. Concatenate The act of combining two strings into a single. and referenced in a <link> tag within an HTML document. For example. longer string. that can be acted upon by a script. DHTML is not a W3C standard or a version of HTML. is supported before using it to avoid browser incompatibilities. and the DOM. Expression A combination of variables. Dynamic fonts Fonts that are embedded with a Web page and downloaded for use. Dynamic fonts are part of the W3C’s CSS Level 2 recommendation. and allows access to every object within a Web page. constants. typically with the . and might not be supported in the future. Conditional A JavaScript statement that performs an action if a particular condition is true. Element A single member of an array. Feature sensing A scripting technique that detects whether a feature. In the DOM. the <font> tag is deprecated in HTML 4. Function A group of JavaScript statements that can be referred to using a function name and arguments. Deprecated A term the W3C applies to HTML tags or other items that are no longer recommended for use. which allows dynamic Web pages to be created.0. Event A condition.

Hypertext Markup Language (HTML) HTML is standardized by the W3C. the spacing between adjacent characters in a font. Inline style One or more styles defined using the style attribute of an HTML tag. A version of a font that has been designed with slanted characters.Glossary 355 Global variable A variable that is available to all JavaScript code in a Web page. called properties. an individual container or element within a Web document. in which letters have varying width. Leading text. rather than designing an italic font. JavaScript A scripting language for Web documents. also known as an argument. Method A specialized type of function that can be stored in an object. the node that contains the current node. It is declared (first used) within the function. JavaScript is now supported by the most popular browsers. B Parent node In the DOM. or until a certain condition is met. called methods. Monospace A type of font in which all characters have the same width. . Kerning In typography. In typography. loosely based on Java’s syntax. Object A type of variable that can store multiple values. the distance between corresponding points in adjacent lines of Local variable A variable that is available to only one function. Layer An area of a Web page that can be positioned and can overlap other sections in defined ways. and acts on the object’s properties. It is declared (first used) outside any function. This contrasts with proportional fonts. Operator Parameter A character used to manipulate variables or constants used in an expression. Layers are also known as positionable elements. Each HTML tag defines a node. Positionable element See layer. developed by Netscape. Loop A set of JavaScript statements that are executed a number of times. Italic The language used to create Web pages. Node In the DOM. and functions. A variable sent to a function when it is called. Oblique A slanted version of a font that has been created by computer processing of the original font.

Selector In a CSS rule. unvisited. CSS. Nodes that contain text. the first portion of the rule that specifies the HTML tag. Tag In HTML. Sibling node Statement In the DOM. XHTML (Extensible Hypertext Markup Language) A new version of HTML developed by the W3C. Pseudo-classes are available for links in visited. a node that has the same parent node as the current node. Rule In CSS. that can store a number. a string. a node that stores a text value rather than an HTML element. XML (Extensible Markup Language) A generic language developed by the W3C (World-wide Web Consortium) that allows the creation of standardized HTML-like languages. or hovering states. A container. Scope The part of a JavaScript program that a variable was declared in and is available to. an individual element of a style block that specifies the style for an HTML tag. but conforms to the XML specification. or identifier that the rule will affect. as in <body> and <p>. A single line of a script or program. String A group of text characters that can be stored in a variable. Serif In typography. HTML tags are contained within angle brackets. XHTML is similar to HTML. Selection lists are defined with the <select> tag. or an World Wide Web Consortium (W3C) An international organization that develops and maintains the standards for HTML. or identifier.356 Appendix B Property A variable that is stored as part of an object. Pseudo-class In CSS. a special selector that can set the appearance of certain elements in certain states. and other key Web technologies. Variable object. a perpendicular stroke at the end of lines within a character. such as paragraphs. Fonts are generally categorized into serif and sans-serif (without serifs) types. DOM objects and CSS styles have a wide variety of properties you can manipulate. active. have a text node as a child node. Text node In the DOM. referred to with a name. Selection list An HTML form element that usually displays as a drop-down list of choices. an individual element within a Web document. class. . using a DTD (Document Type Definition) to specify tags and attributes. Each object can have any number of properties. class.

and indicate whether they are supported by Netscape (6.0 or later) or Internet Explorer (5.0 or later). .APPENDIX C Browser Compatibility Chart The charts in this appendix list the W3C DOM properties and methods.

because browsers are continually changing.2 Name Object Properties and Methods Internet Explorer support Yes Macintosh only Yes Yes Yes Yes Yes Yes Yes Yes Macintosh only Yes Yes Macintosh only Yes No Yes Netscape support Yes Yes No No Yes Yes No Yes No Yes Yes Yes Yes Yes Yes Yes Yes appendChild appendData applyElement attributes childNodes ClassName clearAttributes CloneNode Contains Data deleteData firstChild getAttribute getAttributeNode getElementsByTagName hasAttributes hasChildNodes .1 Name Document Properties and Methods Internet Explorer support Windows version 6 only Yes Yes Yes Yes Yes Macintosh only Netscape support Yes Yes Yes Yes Yes Yes Yes createAttribute createElement createTextNode getElementById getElementsByTagName documentElement implementation TABLE C. TABLE C.358 Appendix C This information should only be used as a rough guideline.

Browser Compatibility Chart 359 TABLE C.2 Name Id continued Internet Explorer support Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Windows only Yes Yes Yes Netscape support Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes InnerHTML insertBefore LastChild Name nextSibling NodeName NodeType NodeValue parentNode previousSibling removeChild replaceChild replaceNode setAttribute Specified TagName C .

.

DOM Level 0 The Level 0 DOM includes objects that represent the browser window. including the basic Level 0 DOM and the W3C Level 1 DOM. The following is a basic summary of Level 0 DOM objects. and its contents. .APPENDIX D DOM Quick Reference This appendix presents a quick overview of the DOM objects available. the current document.

port specifies the communication port. This is the window containing the current JavaScript document. as does window.pathname name of the file. is the directory to find the document on the host.htm Window The window object represents the current browser window.362 Appendix D For detailed information about the properties and methods of each of the objects in the Level 0 DOM. is the protocol (or method) of the URL. consult Netscape’s JavaScript Reference: http://developer.protocol . and the location. location. location. These are given aliases to distinguish them: • • • self represents the current window. document • The history object contains a list of sites visited before or after the current site in the window. is the entire URL.href location. parent • The frames array contains the window object for each frame in a framed document. is the window that contains the current frame. is a combination of the host name and port.com/docs/manuals/js/client/jsref/index. specifies the host name.hash location. there might be more than one window object. if specified.hostname location. stores information about the current Web page. If multiple windows are open or frames are used. It has a set of properties to hold the different components of the URL: • • • • • • • location.netscape. top is the window currently on top (active) on the screen.host is the name of an anchor within the document. Location The location object contains information about the current URL being displayed by the window. The window object has three child objects: • • location stores the location (URL) of the document displayed in the window.

document.forward history. document. is the version number of the browser.forms document.images contains an element for each of the images in the current docuis a collection with references to each embedded Java applet in ment. goes forward to the next location.DOM Quick Reference 363 • • location.applets the document. which is sent to the host when requesting a Web page.) appVersion userAgent is the user-agent header. is a collection containing elements for each of the links in the is a collection with elements for each of the anchors in the doc- document.” is the browser’s full name.0(Win95. usually “Mozilla. It includes the following child objects: • • • • • document.target History The history object holds information about the URLs that have been visited before and after the current one in the window. document. It includes the entire version information. and includes methods to go to previous or next locations: • • • history.go goes to a specified offset in the history list. (Example: “4. such as “Mozilla/4.back goes back to the previous location. location. specifies the TARGET attribute of the link that was used to reach the current location.anchors ument. Document The document object represents the current document in the window.I).5(Win95.” D .I)”.query specifies a query string. history.links is a collection with an element for each form in the document. Navigator The navigator object includes information about the current browser version: • • • • appCodeName appName is the browser’s code name.

364 Appendix D • • plugIns is a collection which contains information about each currently-available plug-in. is an array of all of the child nodes under a node. id is the value of the ID attribute for the node. . You used this property in the previous hour to change the text within a node. childNodes previousSibling nextSibling parentNode is the object that contains the current node. and #text for text nodes. (Netscape only) mimeTypes DOM Level 1 The Level 1 DOM is the first cross-browser DOM standardized by the W3C. nodeType is a number describing the node’s type: 1 for HTML tags. nodeValue innerHTML is the text contained within a text node. and 9 for the document. #document for the document node. 3 for text nodes. The name is the tag name for HTML tag nodes. Basic Node Properties Each object has certain common properties: • • • • • • nodeName is the name of the node (not the ID). is the HTML contents of a container node. is the sibling before the current node is the sibling after the current node. (Netscape only) is a collection containing an element for each of the available MIME types. is the last child object for the current node. Its objects are stored under the document object of the Level 0 DOM. is the value of the class attribute for the node. classname Relationship Properties The following properties describe an object’s relationship with others in the hierarchy: • • • • • • firstChild lastChild is the first child node for the current node.

“Working with Style Sheets. D simply returns true if the node has attributes. is the width of the node object. See Part III. or false if it has none. replaceChild(node. value) removeAttribute(attribute_name) hasAttributes() removes the attribute you specify. removeChild(node) hasChildNodes() removes an existing child node. gets the value of the attribute you specify and sets the value of an attribute. and false if it has none. offsetTop offsetHeight offsetWidth is the height of the node object. returns a Boolean value of true if the node has one or more children. <style> tag. Node Methods The following methods are available for all DOM nodes: • • • • • • • • • • appendChild(node) adds a new child node to the node after all of its existing chilinserts a new node before the specified existing replaces the specified old child node with a new dren. returns a copy of the current node. .” for details on these properties.oldnode) node.oldnode) child node. is the distance from the top of the browser window or containing object to the top of the node object. both Netscape and Internet Explorer support the following properties that provide information about a node’s position: • • • • offsetLeft is the distance from the left-hand side of the browser window or containing object to the left edge of the node object. These are based on attributes of a style attribute. or external style sheet. setAttribute(attribute_name. insertBefore(node.DOM Quick Reference 365 Offset Properties While not part of the W3C DOM. cloneNode() getAttribute(attribute_name) stores it in a variable. Style Properties The style child object under each DOM object includes its style sheet properties.

documentElement . document. document.createElement(tag) • • • creates a new element with the specified tag creates a new text node containing the specified name. document. You can use the asterisk (*) as a wildcard to return an array containing all of the nodes in the document.createTextNode(text) text.getElementsByTagName(tag) document. returns an array of the elements with the specified tag name.getElementById(ID) returns the element with the specified ID attribute. is an object that represents the document itself. and can be used to find information about the document.366 Appendix D Document Object Methods and Properties The following are methods and properties of the document object: • • document.

18 // (double forward slashes). 188-193. 97 addresses (ship-to). 249-253 AddLetter function. 273 <!-. 120 . 293 >-. 322-323 AddNode function. 321-322 a1 = new Image(). 41 “ ” (double quotation marks). 227 . 119 + (plus sign) icon. 35.tag.tag. 149 . 35 <!-. 38 [ ] (brackets). 253 . 146.and --> comment tag.INDEX SYMBOLS < > (angle brackets). 188-193 ( ) (parentheses). 249 HTML documents. (comma). 252 adding elements to forms. 102. 39 = assignment operator. 118. 253 JavaScript files. 204 .(minus sign) icon. 223 >>> icon (MoveRight function). 96-98 items to dynamic order forms. 135. 222-223 A <a> tag. 296 scrolling messages. 222 = (equal sign) (assignment operator). 221-222 ‘ ’ (single quotation marks). 36. (period). 308 absolute value (position property). 75 action attribute. 189-190. 223-224 <<< or >>> icon (ShowHide function). 319. 159 / (forward slash). 146. 35 > (greater-than) symbol. 91 * (asterisk wildcard). 22. 35 <<< icon (MoveLeft function). 66 @font-face selector. 296 AddItems function. 39-41 % (percent sign) units. 102 _ (underscore). 39 == equality operator. 77 < (less than symbol). 273 == (double-equal sign) (equality operator). 218. 264 { } (braces).(hyphen). 227 # (hash symbol).

217 displaying. 306 mouse pointer. setting up. 222-223 support layer. 215 navigation bars Collapse function. setting up. 121-122 AlignMe function. expanding or collapsing. 217 on Netscape 6. 216-217 Java. 362 aligning text style. creating. creating. 309-310 code. 221 JavaScript code. 309 Move function. 222 HTML documents. 222 MoveLeft function. 307-308 graphics.js file. capturing.abs function. creating. 22 angle brackets (< >). 8. creating. 350 aliases. 363 appVersion (Web browser version information). 307-308 Web browser types. 303 HTML documents. 218-219 indented layer. 320-321 analyzing errors. 92 applications clock. 218.368 AI Internet Solutions (CSE HTML Validator) Web site AI Internet Solutions (CSE HTML Validator) Web site. 215 JavaScript images. 224-226 layers. 307 Move function. 220 Toggle function. 216 mouse pointers. 226 appCodeName (Web browser version information). 67 appendChild(node) method. detecting. 363 appendChild method. 302. 221 tree layer. 220 text layer. 302 mouse pointers with multiple images. 214 JavaScript images.0. 278-281 developing. 224 MoveRight function. 214 HTML documents. 216-217 movies. 214 animations. 224 animenu. 303-304 SetPointer function. 95 Allaire (HomeSite) Web site. 365 appending DOM nodes. 214 Flash. 220 menu trees. 220 speed control. 310-312 events. 226 Expand function. 308 Move function. 92 appendChild(newnode) method. 220 creating. 349 alphabets (drawing for Hangman game). 308 Setup function. 130 style properties. 272 appName (Web browser version information). 220 items. 302 Math. 223-224 products layer. 215-216. 305 code. tracking. 274 anchors <a> tag. planning. 308-309 variables. 220 ShowHide function. expanding or collapsing. 306 ChangeDirection function. 214 mouse Move function. 213-214 creating. 301 cross-browser animation example. 303. 363 . 241-242 displaying on Internet Explorer 5. 91 animating GIF (Graphics Interchange Format) images. 217 Dynamic HTML. creating. 215 GIF (Graphics Interchange Format) images. 304-305 events. 222 contact layer.

145 backgroundImage property. 77 Bare Bones Software (BBEdit) Web site. 273 method.getElementsBy TagName(*) method. 135-136 a:link pseudo-class. 125 bold fonts. downloading. 122.all.(hyphen). 122. 37 assignment operator (=. 156. equal sign). 252 position. 75.0 and 5.brackets [ ] 369 arguments (JavaScript functions). 164 HTML documents. 145 backgroundPosition property. 273 a:active pseudo-class. 106-109. 78. confusing. 23 books JavaScript. 261 Web Font Wizard demo version. 67 document. 162 DOM nodes. 135-137 style. 135 B backgroundAttachment property. 67. 238 Internet Explorer 5. 134 setting. 134 border property. 41 avoiding mistakes. 145 backgroundColor property. 66. 149 . 102. 122 backgroundRepeat property. 262 height. 22 href (<link> tag). 274 HTML. 145 background property. 273 ID and name. 38 brackets [ ]. 135 a:hover pseudo-class. 75. 20 braces ({ }). 77. 122. 134 borders consistent styles. 118 using correctly. 132-133 bold text <b> tag. 239 document. 41 arrays document. 22 auto value. 273 width. 200 blinking text. 134 border Width property. 158 properties. 64. 95 ID and class. 131. 78. 39. 189 styles. 200-201 <blink> tag. 94-96 font-family. 272-273 JavaScript. 78. 200 TYPE=“text/css” (<style> tag). 268 Blink function. 160 properties. 203 SRC (<script> tag). 157 images. 236-240 images. 273 asterisk (*). 18. 121. 272-275 CSS. 349 border Color property. 76 bottom property. 77 <body> tag. 123 bottom border Width property. 133 bottom. 78. 252 cursor. 66 attributes . 77.visibility. downloading. 122. 273 DHTML. 134 <br> tag. 349 Bitstream fonts. 240 GetObject function. 78 border Style property. confusing. 221 JavaScript variables. 349 HTML. 252 HTML tags. 240 Internet Explorer 4. 200-201 block value (display property). 236 getElementsByTagNa me method. 261 Web site Truedoc fonts. 19-20. 145 backgrounds colors. 136 Average function. 77 action.layers. 136 DISABLED (<link> tag). 122. 135 a:visited pseudo-class.5.

105-106 clip property. 205-206 GetObject function. 175-177 event logs. 278 clock application without errors. 92. <input type=“checkbox”> tag. 27 radio <input type=“radio”> tag. 28. 151 dynamic layers. 364 clear property. 327-328 HTML Products menu. mouse. 290-293 for Hangman game. 365 cloning DOM nodes. 92 code animations. 26 child objects. 134 clock applications with errors. 146-147 cross-browser animation example. 252 C calling color functions. 309-310 checkboxes. 41 capitalizing styled text. 321 class attributes. 64 ChooseWord function. HTML documents. 362-363 childNodes property. 254-255 for dynamic Web sites. 23. 135-136 a:link pseudo-class. 150 ChangeDirection function. 241-242 DHTML example. 252. expanding or collapsing. 97 <input> tag. 247-248 for dynamic order forms. 190-191 . 133 clearTimeout method. 319-321 choosing words. 239 GetStyleObject function. 149. 63 adding form elements. DOM (Document Object Model). 280-281 colors. 280-281 cloneNode method. 135 centering elements with CSS (Cascading Style Sheets). See Web browsers buttons Delete a Node. 118-119 classname property. 175 HTML documents. 50 creating. detecting. 250-251 before adding dynamic features. 131 capturing events for mouse pointer animations. 303 Cascading Style Sheets.370 browsers browsers. 240 Hangman game style sheets. 350-351 Change function. 82-83 for creating forms. 54-55 drop-down menu HTML documents. 273-274 categories main (menu trees).menu. 135 CGI (Common Gateway Interface). 273 classes a:active pseudo-class. 118 style sheets. 216-217 blinking text. 278 without errors. See CSS case-sensitivity. 337 clicks. 26 Submit. 163-164 creating with dynamic styles. 188 nested (menu trees). 108-109 external style sheets. 65. 135 . 188-189 <center> tag. 65. 146 JavaScript functions. 201 clock application with errors. Hangman game. 138 fading text. 316 for menu trees. 135 a:hover pseudo-class. 364 children. 135 a:visited pseudo-class.

147 properties of DOM (Document Object Model). 158 changing dynamically. 147 hyperlinks. 181-182 hiding. 296-297 scrolling windows. 139 for tool tips. 6 local and global variables. 350-351 comparing assignment (=) operator and equality (==) operator. 193 menu trees. 265-266 code listings. 204-206 text layer (navigation bars). 341 code for tool tips. downloading. 273 HTML (Hypertext Markup Language) and DHTML (Dynamic HTML). creating. 148 functions.tag. 337 for dynamic Web sites. 157-158 dynamic displaying in Internet Explorer. 146 HColor function. 339-340 for style sheet example. 157 PColor function. 221 collapsing main categories (menu trees). creating. 161-162 tool tips. 220 commas. key codes. 222 collapsing menu items (menu trees). 252. 273 . 207-208. 341 style sheets. 145 text consistent styles. 78-79 Menu function. 293-294 mouse pointer animations. 35 HTML. 304-305 mouse pointers with multiple images. calling. JavaScript code. 157 fading. 324-326 scrolling messages. 310-312 moving text. 146-147 consistent styles. 326-327 JavaScript functions for menu trees. 202-203 objects. 35 JavaScript files code for scrolling windows. 157 background images. 218-219 nodes. HTML documents. hiding and showing. 35 <!-. 41 comments > (greater-than) symbol. 34 HTML comments. 95 JavaScript >-. 35 navigation bars. 43-44 WEFT (Web Embedding Fonts Tool). 334-335 navigation bars. 296-297 word list for Hangman game. 145 styles. JavaScript example.tag. 193. 35 JavaScript. 97-98 structure. 107 Collapse function. 97 drop-down menus. 188 color properties. 272 Common Gateway Interface (CGI). 222 navigation bar items. 163-164 codes. 145 colors background. feature sensing. 337 Truedoc fonts. 266-268 Web browser sensing. arguments. 294-295 for Hangman game. 235-236 Web pages. 193-194 layered documents. adding or removing.comparing 371 for scrolling windows. 20 HTML tag attributes. 69 scrolling messages. changing. 194 code to create. 122. 224-226 <noscript> tag. defining. 124. 35 AddNode function. 232-233 Web browsers.

372

compatibility of Web browsers

compatibility of Web browsers, 276 complex DHTML sites, 288 components, DHTML (Dynamic HTML), 9 conditional operators (JavaScript), 39 consistent styles background colors, 157 background image colors, 158 borders, 160 colors, 157-158 creating, 155 CSS (Cascading Style Sheets), 160 fonts, 158-160 hyperlink colors, 157 margins, 160 style sheets, 161 code to create, 161-162 HTML documents, 163-166 Style function, 162-163 text colors, 157 usability, 156 Web browser support, 160-161 consoles, JavaScript errors, displaying in Netscape, 275 contact layer navigation bars, 220 content, style sheets versus presentation, 116 continuing education of DHTML, 339

control panels, 80-81 controlling speeds of animations, 224 coordinates, 75-76 copyrighted fonts, 263 correct letters, displaying for Hangman game, 322-323 createElement method, 250, 253 creating AddItem function, 249-250 animations, 215-217, 301 blinking text, 200-201 complex DHTML sites, 288 consistent styles, 155 background colors, 157 background image colors, 158 borders, 160 colors, 157-158 CSS (Cascading Style Sheets), 160 fonts, 158-160 hyperlink colors, 157 margins, 160 restraint, 156 style sheets, 161-166 text colors, 157 usability, 156 Web browser support, 160-161 control panels, 80-81 DHTML example, 49, 54-55 HTML documents, 50 objects, finding, 51-52

objects, Web browser support, 52 scripts, adding event handlers, 53 scripts, creating, 53-54 Display function, 246-247 drop-down menus, 171-172 displaying, 172 Erase function (JavaScript), 180 event handlers, 173 HTML documents, 173-1178 JavaScript functions, 178-182 layers, 173 Menu function (JavaScript), 178-180 menu items, highlighting, 180-181 menu terms, 172 objects, 172 onMouseOut event handler, 173 onMouseOver event handler, 173 Timeout function (JavaScript), 179 dynamic order forms, 253-255 dynamic styles, 149-151 dynamic Web sites, 287 elements, 91 Fade text function, 204-205 forms, 25-27

creating

373

functions for dynamic styles, 149 GetStyleObject function, 240 graphics Hangman game, 318 mouse pointer animations, 306 HTML documents, 139, 164-166, 288 code, 175-177 for drop-down menus, 173-178 for dynamic Web sites, code, 290-293 for forms, 247-248 for Hangman game, 316-317 for menu trees, 189-191 for mouse pointer animations, 302 for scrolling windows, 339-341 for tool tips, 334-335 layers, defining, 175, 289-290 menus, defining, 289 Web pages, laying out, 288-289 with dynamic styles, 149-151 JavaScript files for dynamic Web sites, 293-295 Menu function, modifying, 293-294 JavaScript functions Erase function, 180 for drop-down menus, 178-182

for Hangman game, 318-324 for menu trees, 191-193 for scrolling windows, 341-342 Menu function, 178-180 menu items, highlighting, 180-181 Timeout function, 179 variables, 319 layered documents, 78-79 Move function, 81, 202-203, 303-304 navigation bars, 217 Collapse function, 222 contact layer, 220 displaying, 226 Expand function, 222 HTML documents, 218-219 indented layer, 220 items, expanding or collapsing, 221 JavaScript code, 224-226 layers, planning, 220 menu trees, expanding or collapsing, 222 MoveLeft function, 224 MoveRight function, 223-224 products layer, 220 ShowHide function, 222-223 support layer, 220

text layer, 220 Toggle function, 221 tree layer, 220 scripts, 53 blinking text, 200 Describe function, creating, 53-54 event handlers, adding, 53 fading text, 204-205 moving text, 202 scrolling messages, 206-207 scrolling messages, 206 code, 207-208 scripts, 206-207 ScrollMessage function, 206-208 scrolling windows, 339 HTML document, 339-341 JavaScript file, code, 341 JavaScript function, creating, 341-342 style sheets, 118, 124, 137-138, 161-162 styled documents, 137-139 styled text, 130-131 text effects, 199 blinking text, 200-201 fading text, 204-206 moving text, 201-203 scrolling messages, 206-208 text nodes, 90 tool tips, 334 hiding, 336-337 HTML documents, code, 334-335

374

creating

HTML documents, creating, 334-335 HTML documents, testing, 335 in Internet Explorer, 338 JavaScript file, code, 337 showing, 335-336 Web pages with HTML (Hypertext Markup Language), 27-29 creating animations mouse pointers, 302, 305 code, 304-305 events, capturing, 303 HTML documents, creating, 302 Math.abs function, 309 Move function, creating, 303-304 SetPointer function, 308 Setup function, 303, 307-308 Web browser types, detecting, 302 mouse pointers with multiple images, 306 cross-browser animation example, 241-242 cross-browser DHTML, 237 cross-browser functions, 239-241 CSE HTML Validator Web site, 350

CSS (Cascading Style Sheets), 6, 9, 115, 135. See also style sheets a:active pseudo-class, 135 a:hover pseudo-class, 135-136 a:link pseudo-class, 135 a:visited pseudo-class, 135 borders, 133-134 centering elements, 135 clear property, 133 clip property, 134 cursor attribute values, 136 external style sheets, 138 float property, 133 fonts, 131-133 height property, 133 left-border-width property, 134 letter-spacing property, 130 line-height property, 130 link styles, 135 list styles, 136-137 margins, 133-134 mistakes, avoiding, 273 mouse cursor styles, 136 overflow property, 134 padding property, 134 style attributes, 135-137 style sheets, 116, 125 aligning text style properties, 121-122 background images properties, 122 cascading styles, 121 classes, 118-119

code to create, 124 color properties, 122 content versus presentation, 116 external, 120, 138 HTML documents, code, 139 IDs, 119 inline styles, 117 integrating with HTML (Hypertext Markup Language), 117-121 positioning objects properties, 123 properties, leading values, 130 rules, creating, 118 style properties, 121-123 <style> tag, 118 style, adding to substance, 117 traditional approach, 116-117 units, 119-120 styled documents creating, 137-139 displaying in Netscape, 140 HTML documents, creating, 139 style sheets, creating, 137-138 styled text, 130-131 text effects, 8-9 text properties, 130-131 top-border-width property, 134

displaying

375

vertical-align property, 130 white-space property, 130 width property, 133 word-spacing property, 130 CSS (Cascading Style Sheets), 6, 9. See also style sheets .css file extension, 120 cursors, 136

D
data, on forms, 252 debugging documents, 277-282 debugging tools, 277, 350 declaring JavaScript variables, 37 decorating styled text, 131 default value (mouse cursors), 136 defining dynamic fonts, 262-264 HandleKeys function, 104 HTML document layers, 175 JavaScript functions, 40 layers, 289-290 menu items, 189-190 menus, 289 onKeyPress event, 102 definitions, JavaScript functions, 37 DeleteNode function, 97

deprecated HTML tags, 19 Describe function, 53-54 detecting Web browsers, 109, 232 browser sensing, 232-234 feature sensing, 234-236 for mouse pointer animations, 302 developing applications, 272 development tools, 349 DHTML (Dynamic HTML), 5 animation, 8 components, 9 continuing education, 339 cross-browser, 237 CSS (Cascading Style Sheets), 6, 9 DOM (Document Object Model), 6, 10 browser-specific, 12 DOM Level 0, 11 DOM Level 1, 12 DOM Level 2, 12 history, 11 dynamic Web pages, 6-7 example, 49, 54-55 HTML documents, 50 objects, 51-52 scripts, 53-54 future of, 338 HTML (Hypertext Markup Language), 6, 9 JavaScript, 6, 10 layers, 8 menus, 7

mistakes, avoiding, 274 objects, positioning, 8 static Web pages, 6-7 syntax too old, 274 text effects, 8-9 troubleshooting, 271-282 Web browsers, 12-13 Web sites, 348 differences of Web browsers, 232 direction variable, 202 DISABLED attribute (<link> tag), 162 disabling styles, 163 Display function, 66, 77, 123, 192, 246-247 displayers, font (Truedoc fonts), 261 DisplayEvent function, 109 displaying animations, 217 correct letters, Hangman game, 322-323 drop-down menus, 172, 178-179, 183 dynamic colors in Internet Explorer, 148 dynamic forms in Netscape, 249 errors in Internet Explorer, 275 in Netscape, 274 event logs, 108-110 fonts in Web browsers, 132 forms in Internet Explorer, 251 Hangman game, 329

376

displaying

HTML documents in Internet Explorer, 51, 219 with dynamic style functions in Netscape, 151 JavaScript errors, 275 menu trees in Internet Explorer, 195 menus, 178-179, 296 navigation bars, 226 scrolling messages in Internet Explorer, 298 in Netscape 6, 208 styled documents in Netscape, 140 tool tips, 338 Web browser sensing, 232-233 <div align=“center”> tag, 135 <div> tag, 22-23, 74, 79, 83, 175, 178 divisions, <div> tag, 22-23 document object, 363 child objects, 363 methods, 366 properties, 366 document object (DOM) methods, 66-67 Document Object Model. See DOM document.all array, 67, 236 getElementsByTagName method, 240 GetObject function, 240 Internet Explorer 4, 238 Internet Explorer 5.0 and 5.5, 239

document.anchors object, 363 document.applets object, 363 document.createElement method, 91 document.createElement (tag) method, 67, 366 document.createTextNode method, 90 document.createTextNode (text) method, 67, 366 document.document Element property, 366 document.forms object, 363 document.getElementById method, 90, 235-236 document.getElementById object, 178 document.getElementById (ID) method, 66, 366 document.getElementsBy TagName method, 90, 145, 235 document.getElementsBy TagName property, 163 document.getElementsBy TagName(*) method, 67 document.getElementsBy TagName(tag) method, 66, 366 document.images object, 363 document.layers array, 236-240 document.links object, 363 documentElement object, 91

documents anchors <a> tag, 22 buttons, <input> tag, 27 debugged, 280-282 debugging, 277-280 defining parts with HTML tags, 19-23 displaying, 20 divisions, <div> tag, 22-23 DOM (Document Object Model), 6 drop-down selection lists, 27 dynamic, 276 forms creating, 25-27 <form> tag, 25 <input type=“checkbox”> tag, 26 <input type=“radio”> tag, 26 <input type=“text”> tag, 26 headings, 21 HTML (Hypertext Markup Language), 50, 139 code, 28, 63 code before adding dynamic features, 50 code for scrolling windows, 339-340 code for structure, 20 code for style sheet example, 139 code for tool tips, 334-335 code to create, 163-164

DOM (Document Object Model)

377

code to create for forms, 247-248 code to create with dynamic styles, 149, 151 components to use CGI scripts, 252 creating, 164-166, 288 creating for scrolling windows, 339-341 creating for tool tips, 334-335 displaying in Internet Explorer, 51 DOM (Document Object Model), 63 dynamic layers example, 83-84 for dynamic Web sites, code, 290-293 forms, code to add elements, 250-251 layers, defining, 289-290 menus, defining, 289 modifying for dynamic Web sites, 297 style sheets, 124-125 testing, 335 testing for dynamic Web sites, 297 Web pages, laying out, 288-289 with dynamic style functions, displaying in Netscape, 151 HTML tags <a>, 22 <body>, 19-20

<br>, 20 <center>, 23 <div>, 22-23 <h1> through <h6>, 21 <head>, 19-20 <html>, 19-20 <img>, 22 <ol>, 21 <p>, 20 <span>, 22-23 <ul>, 21 images height attribute, 22 <img>, tag, 22 logo.gif, downloading, 29, 44 width attribute, 22 layered, 78-79 line breaks, <br> tag, 20 links, <a> tag, 22 methods ordered lists, <ol> tag, 21 paragraphs, <p> tag, 20 Web browser compatibility, 358 quotations, <blockquote> tag, 24 spans, <span> tag, 22-23 styles, 137-140 tables, 24 text styles, 23-24 unordered lists, 21 DOM (Document Object Model), 6, 10, 61 background Attachment property, 145 background Color property, 145

background Image property, 145 background Position property, 145 background Repeat property, 145 browsers, GetObject function, getElementById method, 240 children, 64 color property, 145 document object, methods, 66-67 document.createElement method, 91 document.createTextNod e method, 90 documentElement object, 91 elements, creating, 91 HTML documents, 63 AddNode function, 97 DeleteNode function, 97 nodes, code to add or remove, 97-98 setting up, 96-97 text, adding or removing, 96-98 HTML tag attributes, 95 JavaScript, 68 Level 0 DOM, 62 Level 1 DOM, 62-63 methods, 90-91 nodes, 64 appending, 92 attributes, 94-96 cloning, 92 innerHTML property, 89

378

DOM (Document Object Model)

inserting, 92-93 methods, 91-96 nodeValue property, 89 object, methods, 67 offset properties, 89-90 properties, 88 removing, 93-94 replacing, 93 objects, 64 code to hide and show, 69 document object methods, 66-67 hiding, 68-70 node object methods, 67 node relationship properties, 65 properties, 64-65 ShowHide function, 68-69 showing, 68-70 style properties, 65-66 parents, 64 properties, 90, 145 siblings, 64 structure, 62 children, 64 Level 0 DOM, 62 Level 1 DOM, 62-63 nodes, 64 parents, 64 siblings, 64 styles colors, 145-147 dynamic, 144, 149-151

property names, translating, 144 text, changing dynamically, 148 tagName property, 88 text nodes, 64, 88-90 W3C DOM, 357-358 Web programming languages, 14 window.status property, 43 DOM Level 0, 11, 362-364 DOM Level 1, 12, 364-366 DOM Level 2, 12 double quotation marks (“ ”), 102 font names, 159 javascript, links, 146 double-equal sign (==) (equality operator), 39 downloadable fonts. See dynamic fonts downloading [+] icon, 221 [-] icon, 221 Bitstream fonts, 261 code listings, 194 CSS files, 162 font displayer (Truedoc fonts), 261 graphics, 306 HTML files, 108, 138, 162 logo.gif file, 125, 178 logo.gif images, 29, 44 mouse.gif file, 216, 305 ogo.gif file, 293 style sheets, 138 Web Font Wizard demo version, 261

WEFT (Web Embedding Fonts Tool), 264 word lists, 327 DrawAlphabet function, 319-321 drawing, alphabets, Hangman game, 320-321 drop-down menus creating, 171-172 displaying, 172, 178-179, 183 <div> tag, 178 erasing, 179-180 event handlers, 173 <head> tag, 178 Highlight function, 180-181 HTML documents, 173-174 code to create, 175-177 creating, 173, 175-176, 178 layers, defining, 175 JavaScript code, 181-182 JavaScript functions creating, 178-181 Erase, 180 Menu, 178-180 menu items, highlighting, 180-181 Timeout, 179 layers, 173 logo.gif file, downloading, 178 menu terms, 172 menu.js file, 181 objects, 172 onMouseOut event handler, 173-175

errors

379

onMouseOver event handler, 173-175 <script> tag, 178 <table> tag, 178 <td> tag, 178 Timeout function, 181 UnHighlight function, 180 drop-down selection lists, 27 dynamic color style changes, 146-148 dynamic documents, 276 dynamic event handlers, 104 dynamic features for Hangman game, 317-318 dynamic fonts, 260 @font-face selector, 264 copyrighted, 263 defining, 262-264 Internet Explorer, WEFT (Web Embedding Fonts Tool), 260-261 Netscape, Truedoc fonts, 260-261 Truedoc fonts, 260-262, 266-268 Web browsers, 260-261 Web Font Wizard, 263 WEFT (Web Embedding Fonts Tool), 260-261, 264-266 dynamic forms, 246 displaying in Netscape, 249 HTML documents code to create, 247-248 form elements, code to add, 250-251

Dynamic HTML. See DHTML dynamic layers, 83-84 dynamic order forms creating, 253 HTML documents, 254-255 items, adding, 253 ship-to addresses, showing, 253 dynamic styles, 144, 149-151 dynamic text style changes, 148 dynamic Web pages, 6-7 dynamic Web sites complex DHTML sites, 288 creating, 287 HTML documents code, 290-293 creating, 288 features, combining, 288 layers, defining, 289-290 menus, defining, 289 modifying, 297 testing, 297 Web pages, laying out, 288-289 JavaScript files, 295 code, 294-295 creating, 293 HTML documents, 297 Menu function, modifying, 293-294 scrolling messages, 296-297

E
e-resize value (mouse cursors), 136 editors, debugging tool, 277 education, continuing for DHTML, 339 elements centering with CSS (Cascading Style Sheets), 135 creating, 91 of forms, modifying, 246 positionable. See layers em units, 120 embedded fonts. See dynamic fonts enabling styles, 163 ending Hangman game, 323-324 .eot file, 266 .eot file extension, 261 equality (==) operator, 273 equality operator (==, double-equal sign), 39 equal sign (=) (assignment operator), 39 Erase function (JavaScript), 180 erasing, 179-180 error messages in Web browsers, checking, 272 error-free tips for DHTML, 272 errors analyzing, 274 clock applications, 278-281

380

errors

displaying in Internet Explorer, 275 displaying in Netscape, 274 JavaScript displaying in Internet Explorer 4.0, 275 major in documents, fixing, 279 minor in documents, fixing, 279-280 event capturing, 105 event handlers, 102 ; (semicolon), 102 “ ” (double quotation marks), 102 ‘ ’ (single quotation marks), 102 adding to JavaScript scripts, 43 adding to scripts, 53 creating in JavaScript, 36 drop-down menus, 173 dynamic, 104 HTML (Hypertext Markup Language), 102 JavaScript, creating, 36 onKeyDown, 106 onKeyUp, 106 onLoad, 107 onMouseMove, 105, 303 onMouseOut, 43-44, 104-105, 173-175, 289-290 onMouseOver, 36, 43-44, 104-105, 174-175, 289-290 event object, 102-103 event properties, 103

event.altkey property, 103 event.button property, 103, 106 event.clientX property, 103 event.clientY property, 103 event.ctrlkey property, 103 event.keyCode property, 103, 107 event.modifiers property, 103 event.pageX property, 103-104 event.pageY property, 103-104 event.shiftkey property, 103 event.srcElement property, 103 event.target property, 103 event.type property, 102 event.which property, 103, 106-107 events capturing, for mouse pointer animations, 303 detecting in Web browsers, 109 event logs, 108-110 event object, 102-103 form, 107-108 keyboard, 106-107 menu trees, 189 mouse, 104 clicks, detecting, 105-106 onMouseMove event handler, 105 onMouseOut event handler, 104-105 onMouseOver event handler, 104-105

mouse button, 106 mouse clicks, detecting, 105-106 mouse pointer animations, 307-308 onBlur, 107 onChange, 107 onFocus, 107 onKeyPress, 102 onLoad event handler, 107 onMouseMove event handler, 105 onMouseOut event handler, 104-105 onMouseOver event handler, 104-105 onReset, 108 onSubmit, 108 W3C DOM Level 2 standard, 103 Web browsers, 104 ex units, 119-120 Expand function, 192-193, 222 expanding menu items (menu trees), 192-193 menu trees, 222 navigation bar items, 221 expanding main categories (menu trees), 188 extensions of files .css, 120 .eot, 261 .js, 181 external style sheet files, 273 external style sheets, 120, 138

fonts

381

F
Fade function, 204-205 fading text, 201, 204-205 feature sensing (Web browsers), 234-236 Figby Industries, 172, 290-293. See also dropdown menus files animenu.js, 218, 226 CSS, downloading, 162 .css extension, 120 .eot, 266 .eot extension, 261 external style sheets, HTML tags, 273 hangman.css, 328 hangman.js, 326 HTML (Hypertext Markup Language), downloading, 108, 162 JavaScript code for drop-down menus, 181-182 code for Hangman game, 324-326 code for scrolling windows, 341 code for tool tips, 337 creating for dynamic Web sites, 293 HTML documents, modifying for dynamic Web sites, 297 HTML documents, testing for dynamic Web sites, 297

Menu function, modifying, 293-294 scrolling messages, adding, 296 scrolling messages, code, 296-297 word list code for Hangman game, 326-327 .js extension, 181 logo.gif, downloading, 125, 178, 293 menu.js, 181 mouse.gif, 241 downloading, 216, 305 .pfr, 262 tree.js, 191 wordlist.js, 327 finding layer objects, 239-240 objects, 51-52 style objects, 240-241 firstChild property, 65, 364 fixed value (position property), 75 Flash, 215 float property, 133 font displayer (Truedoc fonts), 261 font objects (WEFT), 261 <font> tag, 117, 131, 156, 262 font-family attribute, 262 font-family property, 131 font-size property, 132 font-style property, 133 font-variant property, 133

font-weight property, 133 fonts, 131 @font-face selector, 264 Bitstream, downloading, 261 bold, 132-133 bold text, <b> tag, 23 choosing, 131-132 consistent styles, 158-160 copyrighted, 263 dynamic WEFT (Web Embedding Fonts Tool), 260 dynamic fonts, 260 @font-face selector, 264 defining, 262-264 Truedoc fonts, 261-262, 266-268 Web browsers, 260 Web Font Wizard, 263 WEFT (Web Embedding Fonts Tool), 261, 264-266 <font> tag, 24 italics, 23, 132-133 kerning, 130 Macintosh fonts, 159-160, 261 names, “ ” (quotation marks), 159 pixels, 132 point values, 132 sizes, consistent styles, 160 sizing, 132 small capitals, 132-133

382

fonts

Truedoc, 260-262 Bitstream Web site, 268 font code example, 266-268 font displayer, downloading, 261 Web site, 261 underlined text <u> tag, 23 units, consistent styles, 160 Web browsers, displaying, 132 WEFT (Web Embedding Fonts Tool), 260-261, 264-266 Windows fonts, 159 for keyword, 39 for loops (JavaScript), 39-40 for statements, 39 form events, 107-108 <form> tag, 80-81, 98, 108, 252 formatting scripts, 272 forms AddItem function, 249-250 buttons, <input> tag, 27 checkboxes, <input type=“checkbox”> tag, 26 creating, 25-27 data, 252 Display function, 246-247 displaying in Internet Explorer, 251

drop-down selection lists, 27 dynamic, 246 displaying in Netscape, 249 dynamic order forms creating, 253 HTML documents, 254-255 items, adding, 253 ship-to addresses, showing, 253 elements adding, 249 modifying, 246 <form> tag, 25 HTML documents code to create, 247-248 form elements, code to add, 250-251 radio buttons, <input type=“radio”> tag, 26 text input, <input type=“text”> tag, 26 forward slash (/), 18 forward slashes (//) (double), 35 function, move, 81 function keyword, 104 functions AddItems, 249-250, 253 AddLetter, 319 Hangman game, 322-323 AddNode, 97 AlignMe, 95 Average, 41 Blink, 200-201 Change, 150

ChangeDirection, creating for mouse pointers with multiple images, 309-310 ChooseWord, 319 Hangman game, 321 Collapse, 193 navigation bars, 222 colors, 146 cross-browser, 239-241 DeleteNode, 97 Describe, 53-54 Display, 246-247 DisplayEvent, 109 DrawAlphabet, 319 Hangman game, 320-321 dynamic styles, creating, 149 HTML documents, code to create, 149, 151 Erase (JavaScript), 180 Expand, 192-193 navigation bars, 222 Fade, 204-205 GameOver, 319 Hangman game, 323-324 getElementById, 52-53 GetObject, 239-241 GetStyleObject, 241 Guess, 319 Hangman game, 321-322 HandleKeys, defining, 104 Hang, 319 Hangman game, 323 HColor, 147

HandleKeys function, defining

383

HideTip, tool tips, 336-337 Highlight, 180, 290 JavaScript, 40 arguments, 41 calling, 41 creating for scrolling windows, 341-342 defining, 37, 40 for Hangman game, 318-324 values, returning, 41 variables, 319 Linebreak, 41 local variables, 41 manu, 289 Math.abs, 309 Menu, 293-294 Menu (JavaScript), 178-181 Move, 81, 202-203, 242 animations, 216 creating for mouse pointers with multiple images, 308-309 HTML documents, code, 216-217 position variable, 216 setTimeout method, 216 MoveHere, 105 MoveLeft, 223-224 MoveRight, 223-224 objects, finding, 51-52 PColor, 147 ScrollMessage, 206-208 SetPointer, 308 Setup, 303, 307-308 Hangman game, 319-320

Show ship-to addresses, 253 ShowHide, 68-69, 222-223 ShowIt, tool tips, 336 ShowTip, tool tips, 335-336 StartHere, 102 Style, 162-164 subdividing, 272 Timeout, 179, 181, 289 Toggle, 191-192, 221 UnHighlight, 180, 290 future of DHTML, 338 future of HTML, 339 future of JavaScript, 339

G
GameOver function, 319, 323-324 games. See Hangman game getAttribute(attribute_ name) method, 94, 365 getElementById function, 52-53 getElementById method, 68, 88 GetObject function, 240 mouse pointer animations, 303 getElementsByTagName method, 68, 163, 193, 240 GetObject function, 239-241 GetStyleObject function, 240-241

GIF (Graphics Interchange Format), 214 global variables, 37 and local variables, comparing, 273 mouse pointer animations, 307 graphics downloading, 306 Hangman game, creating, 318 logo.gif file, downloading, 125 mouse, Move function, 216-217 mouse pointer animation, creating, 306 updating for Hangman game, 323 Graphics Interchange Format (GIF), 214 greater than symbol (<), 35 227 Guess function, 319 Hangman game, 321-322

H
h1 nodes, 88 <h1> through <h6> tags, 21 <h1> tag, 64, 83, 88, 109, 118-119, 138, 147, 203, 206 <h2> tag, 118 HandleKeys function, defining, 104

384

handlers

handlers. See event handlers handling guesses (Hangman game), 321-322 Hang function, 319, 323 Hangman game alphabets, drawing, 320-321 correct letters, displaying, 322-323 displaying, 329 dynamic features, planning, 317-318 ending, 323-324 graphics creating, 318 handling, 321-322 updating, 323 HTML documents, 316-317 JavaScript file, 324-327 JavaScript functions AddLetter, 322-323 ChooseWord, 321 creating, 318-319 DrawAlphabet, 320-321 GameOver, 323-324 Guess, 321-322 Hang, 323 Setup, 319-320 variables, 319 style sheets, 327-328 testing, 328 words, choosing, 321 hangman.css file, 328 hangman.js file, 326

hasAttributes() method, 94, 365 hasChildNodes() method, 67, 365 hash symbol (#), 204 HColor function, 147 hcolor variable, moving text, 204 <head> tag, 19-20, 178, 297 head1.tagNam, 88 headings, 21 height, 76 height attribute, 22 height property, 79, 123, 133 Helios Software Solutions (TextPad) Web site, 349 help value (mouse cursors), 136 hex variable, moving text, 204 hex.length variable (if statement), checking, 205 hidden value (overflow property), 77 HideTip function, tool tips, 336-337 hiding JavaScript code, 34 >-- tag, 35 <!-- tag, 35 HTML comments, 35 <noscript> tag, 35 menus, 191-192 objects, 68-70, 76-77 tool tips, 336-337 Highlight function, 180-181, 290

History, DOM (Document Object Model), 11 browser-specific DOMs, 12 DOM Level 0, 11 DOM Level 1, 12 DOM Level 2, 12 history object, 363 history.back method, 363 history.forward method, 363 history.go method, 363 HomeSite Web site, 349 horizontal positions, 240 href attribute (<link: tag), 164 HTML (Hypertext Markup Language), 6, 9 <!-- and --> comment, 293 <a> tag, 22 <body> tag, 19-20 books to read, 349 <br> tag, 20 <center> tag, 23 code for Products menu, 175 DHTML (Dynamic HTML), 6 <div> tag, 22-23 documents, 50 action attribute, 252 AddNode function, 97 animations, 216-217 code, 28, 63 code before adding dynamic features, 50 code for scrolling windows, 339-340 code for structure, 20

code to add or remove. 96-98 Web pages. 19 standard. defining. 254-255 features. 21 <p> tag. 18 documentation. W3C Web site. 302 navigation bars. 108. defining. hiding. 26 <input> tag. 149. 19-20 <img> tag. 334-335 code to create. 116 style sheets cascading styles. 35 mistakes. 316 code to create with dynamic styles. 22 JavaScript code. 297 text. 252 modifying for dynamic Web sites. 25 <input type=“checkbox”> tag. 334-335 DeleteNode function. 19 tags. 82-84 dynamic order forms. 26 <input type=“radio”> tag. 288-289 with dynamic style functions. 63 drop-down menus. 219 DOM (Document Object Model). 18 . 25-27 <form> tag. 297 mouse pointer animations. 178 menus. 27 future of. code. 151 editors. 339-341 creating for tool tips. 164-166. 124-125 Submit button. 247-248 code to create for Hangman game. 17 <span> tag. 252 testing. 21 <head> tag. 117-121 rules. 290-293 for menu trees. 173-178 dynamic layers example. 119 inline styles. 119-120 syntax. 121 classes. 272-273 <ol> tag. 26 <input type=“text”> tag. adding or removing. 339 <h1> through <h6> tag. 139 code for tool tips. 19-20 <html> tag. 117 integrating. 288 creating for Hangman game. 335 testing for dynamic Web sites. 189-191 forms. 118 <style> tag. 138. debugging tool. creating. 250-251 layers. attributes. 118-119 external. avoiding. 120 IDs. 218-219 nodes. 19 structure. 252 creating. 289-290 logo. 163-164. 289 method attribute. 316-317 creating for scrolling windows. downloading. combining. 288 for dynamic Web sites. 27 <select> tag. 139. elements. 118 units. 151 components to use CGI scripts. downloading. 96-97 style sheets. 162 forms creating. 51. 97 displaying in Internet Explorer. 102 files. laying out. displaying in Netscape. 20 reviewing. 22-23 standard.gif file. 27 <option> tag. 277 event handlers. 18 tags.HTML (Hypertext Markup Language) 385 code for style sheet example. 97-98 setting up.

106 . 146. 147 position attribute. 131. 125. 106-109. 161 !-. setting. 109. 83. 182 <script src>. 27 <p>. 221-222 [-]. 88 <html>. 19-24 external style sheet files. 223-224 <<< or >>> ShowHide function. 24. 117. 107. 117-118. 139. 135 deprecated. 188-193 <<< MoveLeft function. 188-193 . 273 <font>. 23 <ul>. 22. 156. 201 <style>. 27 JavaScript files. 135. 297 head1. 172-175. 118 TYPE=“text/css” attribute. 164.> comment. 18-20 / (forward slash). 252 <h1>. 21. 125. 19-20.tagNam. 24.length variable. 74-75 <li>. 348 hyperlinks <a> tag. 83. 81. 173. 125 <br>. 19-20. 26 <input type=“text”>. 157 styles. 221-222 ID attributes. 107 <span>. 262 <form>. 22. 178. 262 <ol>. 91 <i>. attributes. 238 layers. 135 <div>. 21. See HTML hyphen (-). 109. 273 <layer>. 118. 189-190. 24. 218. 77. 25. 164 validators Web site. 297 <script>. 88. 21 <h2>. 205 mouse button events. 79. 27. 119 <img>. 135 Hypertext Markup Language. 83.386 HTML (Hypertext Markup Language) tags. 138. 108. 96. 118 <head>. 22 colors. 20 <center>. 65. 27-29 Web site. 24 <tr>. 162. 74. 138. 174 <u>. 102. 75 <pre>. 26 <input>. 223-224 >>> MoveRight function. 22-23. 24. 321-322 angle brackets (<>). 175. 295 <select>. 19 <div>. 91 attributes. 98. 138 <link>. 18. 80-81. 119. 302. 207-208. 95 <b>. 178. 136. 273 id properties. menu trees. 38 if statement hex. 88. menu trees. 19-20. 121. 178 <td>. 75. 118 <a>. 318 <input type=“checkbox”>. 18 <!--and -.and --> comment tag. 218. 364 if keyword (JavaScript). 118-119 <h1> through <h6>. code to change. 23 IDs.(minus sign). 189-193 documents. 164. 64. 133. 120. 23 <blink>. 77. 156. checking. 64. 51. 118 <table>. 131. 20. 222-223 [+]. 98. 24 <body>. 22-23 div align=“center”>. 64. 51. 138. 178. 174. 26 <input type=“radio”>. 136 <option>. 178 <th>. 200 <blockquote>. 77 I icons + (plus sign). 98. 277 Web pages. 120.

201 document. 342 tool tips.oldnode ) method. 219 style sheets. 22 images array. document. 215 with GIF (Graphics Interchange Format). displaying. properties. See also Netscape. 253 insertBefore(newnode. 252 Internet Explorer. 238-239 document. 239 Internet Explorer 5. 203 scrolling messages. 358 W3C DOM object properties and methods compatibility. 103 forms. 275 navigator object. 239 fading text. 22 <img> tag. 125 menu trees. displaying. 250. 22. 214 with Flash.Internet Explorer 5. 318 indented layer. 51. 222 infinite loops. installing in Windows. 260-261. 302.0 387 images animating movies. 240 style object. displaying. 148 errors. 44 width attribute. 281 DHTML example. displaying. navigation bars. displaying. 117-121 interactive acceptance. JavaScript example. 214 GIF (Graphics Interchange Format).0 animations. 298 scrolling windows. 238 GetObject function. displaying.all array. 117 inline value (display property). properties. 276 integrating style sheets with HTML (Hypertext Markup Language). animating. 45 WEFT (Web Embedding Fonts Tool). 130 indexOf string method. 107. 106 mouse pointer animations with multiple images. 201 navigator object. 133. data on forms. 240 JavaScript errors. 67 insertBefore(node. 214 height attribute. 65. CGI (common gateway interface).all array. 195 mouse button events. 365 inserting DOM nodes. displaying. 40 inherit value (overflow property). 266 Internet Explorer 4. 201 moving text. supporting. 214 with Java. 217 blinking text. 215 with Dynamic HTML. 92-93.style. 276 W3C DOM document properties and methods compatibility. 234 scrolling messages. supporting. 92-93 installing Internet Explorer versions in Windows. 252 interfaces. 358 W3C DOM properties and methods compatibility. displaying. 275 event properties. 233-234 obj. 215 with JavaScript. 220 indenting styled text. creating. 55 dynamic colors. Web browsers clock application. 364 insertBefore method. 29. Web-browser accommodation.0 DHTML. 207 . 251 HTML documents displaying.all array. oldnode) method. 357 Web pages. 89.gif. 312 moving text.left property. 221 <img> tag. downloading. 77 innerHTML property. 22 logo. 338 versions. 78 inline styles.

hiding. 39 “ ” (quotation marks). 348 italic fonts. defining. 319 future of. 80-81 local variables. 35 HTML tags.tag. 39 debugger Web site. 39-40 for statements. 296-297 for keyword. 180-181 J Java images. 294-295 for Hangman game. 319.tag.all array. 339 GameOver function. 277 Display function. 341 code for tool tips.js file extension. 37 menu. (comma). 180 HTML comments. 322-323 AddNode function. 35 HTML comments. 215 Sun Web site. 38 images. 41 . creating. 246-247 DOM (Document Object Model). 249-250 AddLetter function. 97 animenu. 39 functions.5 Internet Explorer 5. 36 ( ) (parentheses). 233 Internet Related Technologies DOM crossreference Web site. 33-35 . 293-294 scrolling messages. 6. 318-324 local variables. 40 . navigation bars. animating. displaying in Internet Explorer 4. 202-203 . 239 Web browser information. 41 calling. modifying. 181 mistakes. 297 Menu function. animating. avoiding. 132-133 italic text. 324-327 HTML documents. 215 JavaScript. 181 layers. 214 infinite loops. 40 for Hangman game. 35 <!-. 10.js file. creating.5 document.tag. 40 arguments. 68 DrawAlphabet function. 293 for dynamic Web sites. expanding or collapsing. 319. 39 == (double-equal sign) (equality operator). 323-324 global variables. 341-342 definition. manipulating. <i> tag. 218. creating. 37. 37 Guess function. 41 variables. 221 on drop-down menus. 319-321 dynamic Web pages.tag. 39. 224-226 code. 41 >-. 34 >-.388 Internet Explorer 5. returning. 319-322 Hang function. 204-205 files code for scrolling windows. 275 event handlers.0. 23 items adding to dynamic order forms.js file. 35 <!-. displaying. 273 if keyword. 35 comments. 36 Fade function. 226 Average function. (semicolon). 319. 273 Move function. 253 navigation bars. 321 code. 35 <noscript> tag. 323 Highlight function. 41 Blink function. 349 ChooseWord function. 337 creating for dynamic Web sites. 41 creating for scrolling windows. 39 AddItem function. 319. highlighting. 272 conditional operators. 39 for loops. 200-201 books to read. 41 values. 35 = (equal sign) (assignment operator). 6 errors.

348 JavaScript functions Blink. 193 drop-down menus. 36-38 Web pages. adding. 348 JavaScript: command. 37 variables. 34 event handlers. 192-193 menus. 42 onMouseOut event handler. 193 menu items. 178-180 menu items. 37 return. 348 JavaScript tags >--. 104 if (JavaScript). errors. 41 var. 36. 180 var keyword. 41 <script> tag. 40 . 146 . 106-107 keywords case-sensitive. 149-151 property names. 39 function. 107 keyboards. code example. changing dynamically. 40 window.js file. 191-193 Expand function. 347 JavaScript FAQ Web site. 180-181 Move. “ ” (double quotation marks). 148 Timeout function. hiding and showing. 181 tree. 40 while loops. 204-205 for menu trees code. 68-69 statements. 206-208 Setup function. 347-348 while keyword. 42-45 beginning and ending. 206-208 Timeout. 35 <!--. 37 <noscript> tag. 34-36. 144. 35 objects. 44 scripts. translating. highlighting. 43-44 return keyword. Netscape. 193 creating. 35 static Web pages. 38 new. 35 <script>. 179 Toggle. events. 350 JavaScript Developer Central Web site. 191-192 Menu. 191-192 Toggle function. 275 JavaScript debugger Web site. 200-201 Collapse. 35 <noscript>. 43-44 Web sites. 10 adding to Web pages. 44 JavaScript Workshop Web site. 43 JavaScript console. 145-147 dynamic. 192-193 Fade. 130 key codes. displaying in Netscape. 37 while. 43-44 onMouseOver event handler. 144 text. collapsing. 191 UnHighlight function.keywords 389 new keyword. 178-182 Erase.status property. 191-192 JavaScript Reference Web site. 180 Expand. 6 styles colors.js file extension. 181 K kerning. 43 ScrollMessage function. 202-203 ScrollMessage. 34-36. 319-320 ShowHide function. 192-193 menu items. 275 links. 193-194 Collapse function. expanding. 273 for.

navigation bars. defining. 74 contact.left property. 78 coordinates.top property. 75 support. 220 <span> tag. 82-83 dynamic layers example. 130 <link> tag. 220 defining. 76-77 overflow property. 137 listings of code. 362-363 navigator object. 130 left property. 238-240 <layer> tag. 77 border property. 65. 123 left-border-width property. 27 list-style (style attribute). 220 text. 82 obj. 363 images array. 221 obj. 77-78 units. 21 word list JavaScript file code for Hangman game. navigation bars.style. 137 list-style-type (style attribute). 79. 75 obj. 8. code to create. 364 layer objects. setting. 238 layers. 363 history object. <br> tag. 139. positioning. 122. 175 HTML tags. displaying for Hangman game. 121. 82 objects. 137 list-style-image (style attribute). 137 list-style-position (style attribute). 362 Level 1 DOM. 21 styles. DOM (Document Object Model). 41 line-height property. 14 lastChild property.style. 362 objects. 162-164. navigation bars. 76. 75 position:absolute. 138 line breaks. 75 style attribute. 76 position attribute. 120. 364-365 <li> tag. 220 laying out Web pages. navigation bars. 134 less than symbol (). 289-290 <div> tag. 361 window object. 288-289 leading values. 220 layered documents. 62 document object.style. 137 ordered. 326-327 . 75 products. 252 Web programming. 74 drop-down menus. 74-75 indented navigation bars. 75-76 objects. 75 position property. 80-81 navigation bars. 130 letters. setting. 262 links. 136-137 unordered. 363-364 Netscape Web site. 322-323 Level 0 DOM. 84 HTML documents. See hyperlinks list-item value (display property). 77 list-style (style attribute). navigation bars. 220 tree. downloading. correct. 66. 137 list-style-image (style attribute). <ol> tag. showing and hiding. 221 location object. 173 <dynamic> (HTML documents). 227 letter-spacing property.position. 137 list-style-type (style attribute). 194 lists drop-down selections. 220 nested menu trees. 78-79 manipulating with JavaScript. <ul> tag. 366 objects. 137 list-style-position (style attribute).390 languages L languages server-side Web sites. 20 Linebreak function. 62-63 document object. 75 background properties.

41 location object.(minus sign) icon. 160 overflows. 279 manipulating layers with JavaScript. 29. 179-180 items. comparing. hiding and showing. 362 location. 189-192 menu trees. 221 objects. expanding or collapsing. 363 logo.target property. 189-191 JavaScript functions code.host property. 178. 192 navigation bars. 133 margin-bottom property. 133 setting. fixing. 362 location. code. 191-192 Toggle.messages 391 local variables. 289. highlighting. 309 Menu function. mouse pointer animations. 133 margins clipping. 44 logs.hostname property.js file. 192-193 menus. 215 main categories (menu trees). expanding or collapsing. 362 location. checking. 296 code. See also dropdown menus defining. HTML code. 208 displaying in Internet Explorer. 293-294 menu items (menu trees). 175 messages error.protocol property.href properties. 193-194 Collapse. 293 images. 191-193 Expand. 178-179 in Netscape. 172. 188 menu items. 349 Macromedia Web site (Flash). 133 Math. 362 location. 39-40 Lynx Web site. 189 .gif file.pathname property. 188-193 . 125. 296 erasing. 133 margin-top property. 362 location. in Web browsers. 362-363 location. 180-181 Products. 195 events. 178-180. 207-208 creating. 188-193 displaying in Internet Explorer. expanding or collapsing. 276 M Macintosh fonts. downloading. 118 menu. 363 location. 133 margin-right property. 273 JavaScript functions. event 108-110 loops. 192-193 menu items. 7 displaying. 189 HTML documents. 80-81 margin property. 37 and global variables. 42. 134 consistent styles. 133 margin-left property. 222 nested categories.hash property.query property. 181 menus. 297 JavaScript files. 362 location. 188-189 nested layers. 272 scrolling adding. downloading.menu class. 362 location. 289 DHTML. 134 properties. 191-192 main categories.port property. 193 creating. 206 displaying in Netscape 6. 159-160 Macromedia (HomeSite) Web site. 298 HTML documents. 188 + (plus sign) icon. 296-297 .abs function. 188 major error in documents.

67 replaceChild(node. 90. 365 case-sensitive. 277. 206 newtext variable.createElement (tag). 145. 250. 272 nodes. 365 getElementById. oldnode).back. 264. 366 document. 94.setTimeout. 42 naming. 67. 67 document. 363 indexOf string. avoiding. 365 createElement. 272-275 models. oldnode). 240 mouse pointer animations. 163. 206-207 ScrollMessage function. 180. 250. 252 methods appendChild.getElementBy Id(ID). 136 drop-down menus. 365 replaceNode.getElementBy Id.forward. 206 scripts. 88 GetObject function.createText Node. 7. 67 removeNode. 363 history. 90-96 getAttribute(attribute_ name). 222 insertBefore. detecting. 309 Move function. 336 toString. 90. 363 history.createText Node(text). 350 Microsoft Script Debugger. creating. value). 253 document object. 365 removeChild(oldnode). 364 minor error in documents. 357-358 window. 365 JavaScript objects. 240 GetStyleObject. 92-93. oldnode). 90 document. tool tips.getElementsBy TagName. 365 setTimeout. 94 replaceChild. 93 setAttribute(attribute_ name. 173 Move function. 366 document. 188-193 mistakes. 363 history. 366 document.getElementsBy TagName(*). 66-67 document. 207 pos variable. 67. 216-217 . 274 clearTimeout method. 240 hasAttributes(). 67. 91 document. 366 document object (DOM). 91-96. 92 cloneNode(). 66.392 messages msg variable. 365 removeChild. 277 mimeTypes (Web browser version information). 204 W3C DOM. fixing. 366 DOM (Document Object Model). 92 appendChild(newnode). 365 removeAttribute(attribute _name). 207 MicroEdge (SlickEdit) Web site. 193. 279-280 minus sign (-) icon. event handlers. 67 appendChild(node). 337 cloneNode. 253 insertBefore(newnode. 68. 68. 365 hasChildNodes(). 93-94 removeChild(node). 207 method attribute. 261. 349 Microsoft. 303 getElementsByTagName.getElementsBy TagName(tag). 66. menu trees. 94.go.createElement. 206-208 Web browsers. 105-106 cursor attribute values. 93 replaceChild(newnode. 235-236 document. 235 document. 202 mouse pointer animations. 67. 94. 94. 6 mouse clicks. DOM (Document Object Model). 67 insertBefore(node. 365 history object. oldnode). Web browser compatibility. 216 tool tips.

scrolling messages. 104-105 onMouseOver event handler. 173-175 onMouseOver event handler. 188-189 objects. 306 mouse pointer. 191-194 main categories. 188 + (plus sign) icon. 305 code. creating. code. capturing. creating. 302. 203 scripts. 304-305 events. creating. 241. 303-304 for mouse pointers with multiple images. 188-193 events. 307-308 graphics. 188 nested categories. 144 naming. menu trees. 136 name attributes. tracking. 223-224 MoveRight function. 302 Math. 216 move value (mouse cursors). 216. 242 creating for mouse pointer animations. 106 mouse cursors. 188-193 . 105-106 onMouseMove event handler. 306 ChangeDirection function. 222 contact layer. 202 Web browsers.(minus sign) icon. 202-203. 303-304 SetPointer function. 202 style. 217 . 81. 202-203 pos variable. 308-309 variables. 307-308 Web browser types. 202 hcolor variable. 216 setTimeout method. 309-310 code.abs function.gif file. 189 HTML documents. 105 onMouseOut event handler. 215 moving text code. 201 Mozilla team (Netscape) Web site.left property. 203 Move function. 173-175 mouse button events. 216. 303 HTML documents. 136 MoveHere function. 136 mouse events. 189-191 JavaScript functions. 206 N n-resize value (mouse cursors). 308 mouse. creating.navigation bars 393 onMouseOut event handler. 310-312 events. 43-44. 303. 307 tracking. setting up. creating. setting up. expanding or collapsing. detecting. 309 Move function. 220 creating. 202 position style attribute. detecting. 202-203 direction variable. 273 names of properties. 350 msg variable. 204 hex variable. 308 Setup function. 272 navigating Web sites. 189 navigation bars Collapse function. 43-44. translating. 308-309 HTML documents. 223-224 movies. 302 animations with multiple images. 204 in Internet Explorer. 104 mouse clicks. 308 Move function. 305 Move function. 105 MoveLeft function. 104-105 mouse pointers animations. 216-217 position variable.

140 Truedoc fonts. 64 h1. 221 JavaScript code. 151 JavaScript console. 94-96 cloning. 201 moving text.left property. 103 HTML document with dynamic style functions. 92 DOM (Document Object Model). 296 mouse button events. menu trees. displaying. 238 menus. 268 Netscape 6 animations. displaying. 305-306 styled documents. 364 node object (DOM) methods. 273 Netscape. 55-56 drop-down menus. planning. supporting. 207-208 new keyword. 218-219 indented layer. 188-189 nested layers. 67 node relationship properties. 221 tree layer. 224-226 layers. 224 MoveRight function. code to add or remove. 92 attributes. 110 fading text. 249 errors. feature sensing. 275 layer object.style. 240 style object. 201 navigation bars. 357-358 Web browsers. errors. 236 Web site DOM Level 0. displaying. 242 DHTML Web-browser accommodation. 222-223 support layer. 226 Expand function. 65 nodeName property. displaying.layers array. 220 ShowHide function. 183 dynamic forms. 217 blinking text. 238 Truedoc fonts.left property. 348 Mozilla team. 88 HTML documents. displaying. displaying. 362 JavaScript debugger. 220 text layer. 363-364 ne-resize value (mouse cursors). expanding or collapsing. 350 JavaScript Developer Central. 358 W3C DOM object properties and methods compatibility. displaying. 97-98 . 220 items. 226 navigator object. 221 nesting tags improperly. 37 newtext variable. 275 javascript: command. 238 GetObject function. correcting. 232-234. 201 event logs. 136 nested categories (menu trees). properties. 274 event properties. 240 obj. 350 Netscape 4 cross-browser animation example. 220 Toggle function. 106 mouse pointer animations. 64.394 navigation bars displaying. 96 DHTML example. See also Internet Explorer. 65. displaying. expanding or collapsing. Web browsers attribute changing example. 364 nodes appending. 347 JavaScript Reference. displaying. 207 nextSibling property. 240 scrolling messages. 260-261 W3C DOM document properties and methods compatibility. 223-224 products layer. 234 obj. 220 navigator object. document. scrolling messages. displaying. 220 menu trees. 222 MoveLeft function. 222 HTML documents.

363 documentElement. 52 with DHTML functions. 43-44 positioning. 365 relationship properties. 66-67 methods. 189 Web browser compatibility. 366 properties. 88-90 nodeType property. changing horizontal position. 12 document object methods. 88 properties. 89-90 p. 363 (DOM) methods.style. 82 objects case-sensitive. 233-234 Web browser detection. 362-363 code to hide and show. 93-94 replacing. 102-103 finding.top property. 274 child. Web browser support. 363 child objects. 69 document. 363 location object.object. 136 O obj. 67 node relationship properties.position.links. 11 DOM Level 1. 362-363 menu trees. 89 inserting. 75 obj. 363-364 properties. 136 <noscript> tag. 92-93 methods. 178 document. 77 none value (mouse cursors). 240 obj. 91 DOM (Document Object Model). 364 node methods. 64 browser-specific.top property.left property. 364 offset properties. 261 hiding. 365 node properties. 6. 89 offset properties. 364 innerHTML. 88 DOM Level 1. 82 onMouseOut event handler. 362-363 navigator object. 89 offset. 362 Level 1 DOM. 365 location. 240 obj. 65. 67 obj. 366 document. 51-52 font (WEFT). 65-66 DOM Level 0. 363 JavaScript. 51 before accessing. 8 background properties.left property. 365 nodeValue property. 238-240 Level 0 DOM.forms. 68-70. 12 drop-down menus. 172-173 events. 232 node (DOM) methods.getElementByI d. 363 document.style.images. 89 nodeValue. 64-65 style properties. 82. 77 border property. 363-364 window object. 76-77 history.objects 395 innerHTML property. 66-67 node object methods. 35 nw-resize value (mouse cursors). 364 nodeValue property. 363 document. 93 text. 361 document object.properties. 91-96.left property. 363 document. 363 history object. 89. 65 properties. 82 obj.applets. 42 layer. 364 none value (display property). 364 style properties. 64.style. 240 obj. 81 navigator. 89-90 removing.style. 65. 78 .style. 358 move function.anchors. 363 document. 12 DOM Level 2. 240 obj. 43-44 onMouseOver event handler. 274 Web browser support.

104-105. equal sign). 76-77 on layers. 107 onKeyDown event handler. 64. 105. 75. 132 pointer value (mouse cursors). 107 onChange event. 206 position property. 20 parameters. 173 Menu function. 134. 21. 216 . 76 Web browser compatibility. 106 onLoad event handler. 108 Opera Web site.396 objects coordinates. 188-193 point sizes. 39-41 parentNode property. comparing. 43-44. 289 onReset event. 365 offsetLeft property. 80-81 paragraphs. 89-90. 273 assignment (=. doubleequal sign). 68-70. 56. 65. 362 offset properties. 123 position style attribute. moving text.). 160 point units. 303 onMouseOut event handler. 75-76 objects properties. DOM (Document Object Model). 118. 203 position variable (Move function). 136 onBlur event. 134 panels. 120 period (. 90. 132 planning dynamic features for Hangman game. See mouse pointers points (pt) units. 174-175 drop-down menus.menu class. control. 20. 104-105. showing and hiding. 90. 75 overflow property. 68-69 showing. 102 onKeyUp event handler. 290 Menu function. <p> tag.com Web site. 262 PHP Web site. 76-77 style finding. 119 pos variable moving text. 21 overflow property. 90. defining. <ol> tag. 107 onFocus event. 123 objects. 108 onSubmit event. 119. 350 . 240-241 Internet Explorer 4. 88. 239 Netscape 4. 106 onKeyPress event. 276 operators assignment (=) and equality (==). 250 parentheses ( ). 358 ShowHide function. 351 pixels. 365 offsetHeight property. 119 Perl. 202 scrolling messages. 138. 77-78. 289 Timeout function. 39 equality (==. 289 Timeout function. 39 conditional (JavaScript). 365 offsetWidth property. 290 onMouseOver event handler. 90. 365 offsetTop property. 77-78 units. fonts. insertBefore method. 107 onMouseMove event handler. 340 P p nodes. 365 <ol> tag. 147 percent sign (%) units. 317-318 plug-ins (Web browser version information). creating. 238 window. 39 ordered lists. fonts. 136 pointers. 36. 289 UnHighlight function. 364 plus sign (+) icon menu trees. . 160 point values of fonts. 364 parents. setting. 43-44. 147 padding property. 173 Highlight function.pfr file. 88 <p> tag. 64 PColor function. 77. 174-175 drop-down menus.

145 border.hash. 42. 103. 116 previousSibling property. 65. 202 positioning variables.getElementsBy TagName. 364 products layer. 122. 364 . 122 background Attachments. 103 event. 307 position: absolute. 77. 134 childNodes. 133 font-weight.srcElement. 65. 77 document object. 364 classname. 103 event.protocol. 75 <pre> tag. 133 clip. 122. 145 background Repeat. 145 disabling style sheets. 163 display. 103 event. 8. 144 navigator object. 103 event. 163 DOM (Document Object Model). 77. 65. 133 names.type. 76 positioning objects properties. Web browser support. 133 margin-left. HTML code. showing and hiding. 362 location. 79. 90 node relationships. 103 event. navigation bars. 122. 362 location. 42 lastChild. 364 float. 65 objects.query. 134 letter-spacing. mouse pointer animations. 65. 75 background properties. 134 bottom.clientX. 123 positioning text. 77-78 units. 65. 364 clear. 66. 103 event. 362-363 location. 133 id. 65. 132 font-style. 89. 123 bottom-border-width. 364 innerHTML.target. 363 location. translating. 65. 362 location.href.altkey. 207-208. 366 document. 133 margin-top. versus content. 65. 133 font-variant. 79. 123 left-border-width.ctrlkey.documentElem ent. 133 margins. 121-122 background. 145 background Images. 103-104 event. 297 presentations.button. 366 document. 78. 77 border property. 123. 133 height. 103-104 event. 130 line-height. 103 event. 76. 362 location. 76-77 overflow property. 133 font-family. 363 margin-bottom. style sheets. 131 font-size. 362 location.pathname. 220 Products menu.which. 123 menu items. See layers positioning objects.properties 397 positionable elements. 121.modifiers. 362 location.keyCode.shiftkey. 133 margin-right. 233-234 nextSibling. 122. 364 JavaScript objects. 66. 65-66 events. 103. 122. 122. 175 properties aligning text. 106 event. 145 background Positions.target. setting. 362 location. 134 colors.hostname.clientY.port. 102 event. 103 event. displaying. 122. 103 event. 66. 364 left. 77.host. 103. 107 event. 106-107 firstChild.pageY. 130 location object. 75-76 objects. 78 coordinates. 64-65 styles. 192 values. 145 background Colors.pageX.

77. 205 window. 192. 88 text-align. bold. 364 nodeType. 134 padding-right. 134 style.left. 130 text-transform. 123. 358 white-space. positioning. 130 text-decoration. 133 window. 90. 132-133 HTML documents. 133 centering elements with CSS (Cascading Style Sheets). 123 top-border-width. 134 borders. 135 a:hover.top. 365 offsetLeft. 340 padding. 130 z-index. 134 margins. 65. 340-341 tagName. small capitals. 365 offsetWidth. 139 leading values.object horizontal position. 88 DOM Level 1. 123. 123 previousSibling. 123 right-border-width. 119 . 123 style sheets. 130-131 styled text. 43 word-spacing. 135 pt (points) units. 75. 76. 365 offsetTop. 121-122 background images. creating.left. 135 list styles. 76. 134 margins. 90. 135 a:visited. setting. moving text. 137-138 fonts. 130 width. 121. 131-132 fonts. 132 fonts. 132-133 fonts. 133 margins. 364 relationships. 89-90 DOM Level 1. 365 offsetHeight. 134 padding-left.left. 240 obj. 66.top. 79. 131 top. 123 of backgrounds. 240 obj. choosing. 131 text-indent.status. 132-133 fonts.style. 122. 66. 64. spacing. 364 nodes. 134 padding-bottom.398 properties node relationship. 364 right. 136-137 margins. properties. DOM Level 1. creating. 240 ojb. aligning. 365 overflow. 82.style. 65. properties. 76. sizing. 122. 134. 365 objects. 122 color. 364 position. 79. 65. 77 of DOM (Document Object Model). 123 pseudo-classes (CSS) a:active. 77-78. 130 link styles. 65 nodeName. 131 fonts. 66. italic. setting. 122 DOM Level 1. 131 styled text. setting. 119 px (pixels) units. changing. Web browser compatibility. 364 nodeValue. decorating. overflows. 145 offset. clipping. capitalizing. 130 visibility. 133 mouse cursor styles. 202 style. 134 padding-top. 82 objects. setting. 130 style. 135 creating. 89. 134 vertical-align. indenting. 135-137 styled documents. 121-123 aligning text. 135-136 a:link. 90. 130 styled text. 130 styled text. 357 Web browser compatibility. setting. 136 style attributes.setTimeout. positioning. 335 W3C DOM. creating. 65-66. 65. setting. 137-139 styled text. 76. 129 borders. 134 parentNode. 131 styled text. 90. 364 obj.

350 development tools. 348 HTML books. 17 right property. creating. 98. 36. oldnode) method. 206-208 Web browsers. <blockquote> tag. 24 radio buttons. 97-98 text. 364 relative value (position property). 44. 202-203 scrolling messages creating. 206 newtext variable. 134 rules. 76. 341-342 . 365 replaceNode method. 67 removeNode method. 207 scrolling windows creating. See events restraint. 146 font names. 34 blinking text. 206-207 ScrollMessage function. DOM Level 1. 365 removeChild(oldnode) method. creating. 207-208 creating. 173 <script src> tag. 349 Web sites. 339-341 JavaScript. 77 scrolling messages adding. 53 Describe function. 206 scripts. 43. 53 fading text. properties. 200-201 creating. oldnode) method. 272 scroll value (overflow property). 350 <script> tags. 45 beginning and ending. 204-205 formatting. 67 replaceChild(node. 93 replaceChild(newnode. 83. 41 returning values for JavaScript functions. style sheets. 34-36. 272 variables. 277. adding. 41 reviewing HTML (Hypertext Markup Language). creating. 102 quotations. consistent styles. 272 JavaScript comments. 159 single (‘ ’). 350-351 debugging tools. 96-98 replaceChild method. 26 relationships. 349 JavaScript books. 42-43. 206-208 subdividing. 10 adding to Web pages. 164. 296 code. 339. 208 HTML documents. 365 removeChild method. 94. creating. 102. 298 in Netscape 6. naming. <input type=“radio”> tag. 93-94 removeChild(node) method. 339 HTML document. 206 displaying in Internet Explorer. naming. 93-94 HTML documents nodes. 156 return keyword. 66. 296-297 msg variable. 207 pos variable. 295 scripting languages. 123 right-border-width property. 53-54 event handlers. 94 removing DOM nodes. 349 DHTML. 206-207 ScrollMessage function. 347-348 responding to events. 118 S s-resize value (mouse cursors). See also Web sites CGI (common gateway interface). 75 removeAttribute(attribute _name) method. 272 methods. 297 JavaScript files. 272 moving text. 93 replacing DOM nodes.scrolling windows 399 Q–R quotation marks double (“ ”). 136 Script Debugger (Microsoft)Web site. See JavaScript scripts. 93 resources.

documents. 62-64 HTML (Hypertext Markup Language). 125. 132-133 spacing styled text. 336 ShowTip function. 75 static Web pages. 222-223 showing menus. 189 standards HTML (Hypertext Markup Language). 20. 335-336 ShowIt function. 102 static value (position property). See also CSS a:active pseudo-class. 135 a:visited pseudo-class. 162-164 style objects finding. 161-162 . 135-136 a:link pseudo-class. 335-336 siblings. troubleshooting. 134 borders. 202 mouse pointer animations. 136 sections ending. 65-66. 134 content versus presentation. See style sheets ship-to addresses. mouse pointer animations. 18 // (double forward). 239 Netscape 4. 349 small capital fonts. 35 SlickEdit Web site. 121-123. 303. 273 sensing Web browsers. 222 JavaScript variables.400 ScrollMessage function ScrollMessage function. tool tips. 135 a:hover pseudo-class. 109. 98. 133-134 bottom-border-width property. 133 Setup function. Web sites. 116 creating. 308 setTimeout method. 132 slashes / (forward). 201 speed control of animations. 160 sizing fonts. 124. 365 SetPointer function. value) method. 116 style attribute. tool tips. 336 setting borders and margins. 319 Hangman game. 96. 253 ShowHide function. events. 130 <span> tag. 224 SRC attribute (<script> tag). 64 single quotation marks (‘ ’). 135 classes. 68-69. 252 setAttribute(attribute_na me. 68-70. 75. 121 centering elements. 273 <select> tag. 319-320 mouse pointer animations. 253 tool tips. 307-308 sheets. 134 border-width property. 309 Move function. 94. 116. 135 border-color property. 76-77 ship-to addresses on dynamic order forms. 137-138. 206-208 se-resize value (mouse cursors). 161. incorrect. 232-236 server-side languages. 365 style sheets. 107 selector syntax. 118-119 clear property. 240-241 Internet Explorer 4. 253 Show function. 19 W3C DOM Level 2. 103 StartHere function. 6-7 strings indexOf string method. 134 cascading styles. 22-23. See Web sites sizes (points) of fonts. 102 sites. DOM (Document Object Model). 134 border-style property. 191-192 objects. 216 tool tips. 75 Style function. ship-to addresses. 38 structures DOM (Document Object Model). 133 clip property. 238 style properties. showing on dynamic order forms. showing on dynamic order forms.

137 margin property. 133 fonts. 130 white-space property. moving text. creating. 137-138 . 138 files and HTML tags. 133 font-weight property. 133 margins. 163 downloading. 133 margin-right property. 202 style. 137 list-style-type (style attribute). 130 width property. 139 code to create. creating. 129-130 right-border-width property.top property. 121-123 <style> tag. 136 overflow property. 118 style. 133 margin-left property. 117-121 left-border-width property. setting. 139 style sheets. 200 styled documents creating.left property. 137-139 displaying in Netscape. 133 margin-bottom property. creating. 118 style. 130 text-transform property. 134 letter-spacing property. 136-137 list-style (style attribute). 120 code. 132 font-style property. 133 font-family property. 133 margin-top property. 119 inline styles. 133 word-spacing property. 161 <!-. 119-120 vertical-align property. 117 integrating with HTML (Hypertext Markup Language). 134 rules. 137 list-style-position (style attribute). setting. 136 disabled property. 163-164 creating. 130-131 text-align property. 162-164 style properties. 130 <style> tag. 133-134 mouse cursor styles. 130 text-decoration property. 131 font-size property. 340-341 style. 134 traditional approach.styled documents 401 cursor attribute values. 117 style attributes. 139. 130 line-height property. blinking text. 164-166 IDs. 134 padding-bottom property. 131 text-indent property. 116-117 units. 134 padding-right property. 134 padding-left property. setting. 138 external. 137-140 styled text. adding to substance. 134 properties. 140 HTML documents. 117-118. 134 padding-top property.visibility attribute. 137 list-style-image (style attribute). 118 styled documents. 135 list styles. setting. 118 TYPE=“text/css” attribute. 133 HTML documents code. 131 top-border-width property.and --> comment tag. 131-133 Hangman game. 138. 135-137 Style function. 130 link styles. 133 font-variant property. 120. 134 padding property. 273 float property. 327-328 height property.

setting. 157 inline. changing dynamically. 149. 163 <font> tag. 117 code to create. 24 <th> tag. 161-162 disabled property. 157-158 changing dynamically. 19 tags. 162. 24 <i> tag. 156 borders. changing dynamically. 157 <font> tag. 146-147 functions. 24 changing dynamically. 220 supporting. 156 Web browser support. setting. 136 <script> tag. 151 dynamic. 158-160 getElementsByTagName method. calling. 149. 24 <td> tag. 24 <u> tag. 163 DOM (Document Object Model). 19 selectors.getElementsBy TagName property. 23 <ul> tag. 130-131 styles attributes. 148 colors. old and new Web browsers. 164 usability. 144. 215 support layer. 160 disabling. 163 HTML documents. 157 background image colors. 145-147 dynamic. 163-166 Style function. 146 properties. 23-24 <b> tag. 241-242 sw-resize value (mouse cursors). 144 property names. setting. setting. navigation bars. creating. incorrect. 161 adding to substance. 149 HTML documents. translating.402 styled text styled text. creating. 159-160 margins. 121 colors. code to create HTML documents. 147 code to change dynamically. 149 dynamic styles. 160-161 Windows fonts. 164 list. 162-163 <style> tags. 149-151 dynamic styles. 18 standard. 145-147 dynamic. 163 hyperlink colors. 23 <blockquote> tag. 144 dynamic. 144 colors. 164 style sheets. 151 property names. 18 tags. 144 text. troubleshooting. translating. 136 syntax DTHML. 155-156 CSS (Cascading Style Sheets). 144 text. code to create. 160 mouse cursors. 145. 149 functions. creating functions. 159 subdividing scripts and functions. 274 HTML (Hypertext Markup Language). 23 <table> tag. 252 Sun Web site (Java). 117 JavaScript colors. 144 enabling. 149 property names. 24 <tr> tag. 163 document. 272 Submit button. 18 W3C Web site. attributes. 161 text. 135-137 background colors. 273 . 145 consistent. 160 cascading (style sheets). translating. 148 dynamic. 158 <blink> tag. 136-137 Macintosh fonts. 135 <link> tag. 156 fonts. 148 link.

131 changing dynamically. creating. 202 quotations. 24. 121-122 Blink function. 281 cross-browser DHTML. 18 nesting improperly correcting. 200-201 bold style. 255 Hangman game. 122. 131 text-indent property. 204 hex variable. 24 scrolling messages code. 81. 24 underlined style. 276 text aligning text style properties. 338 displaying. 317 testing clock application with errors. 201 positioning. <input type=“text”> tag. creating. 277 effects. 135 color properties. 130 capitalizing. See also HTML. 204-205 Web browsers. 336 showing.left property. 202 style. 178 tagName property. 51. 335-336 . 289 Toggle function. 125. 202-203 direction variable. 207-208 creating. 221 tool tips clearTimeout method. 237 debugged documents. 178. 148 creating. <u> tag. 157 editors. 337 setTimeout method. 122. 24 HTML documents. 51. creating. 204 in Internet Explorer. 130 text-decoration property. 334. 131 TextPad Web site. 206 scripts. 203 scripts. 273 <td> tag. 206-208 styles aligning. 206-207 ScrollMessage function. 136 text-align property. 281 dynamic documents. 288. 8-9 text layer. 122 colors. 334-335 JavaScript file. 328 HTML documents for dynamic Web sites. 23 Web pages. 205-206 Fade function. 26 italic style. 130 tables. 172-175. 201 code. 336-337 HTML documents. 199 fading. 203 Move function. 130 spacing. 130-131 decorating. 201 <font> tag. 220 text nodes. 202 Web browsers. 122. 96-98 input on forms. 23 <center> tag. creating. 335 Web browser compatibility. 278. 337 creating. debugging tool. tags. <blockquote> tag. 276 dynamic order forms. 202-203 pos variable. 88 tags.tool tips 403 T <table> tags. 88-90 text value (mouse cursors). <b> tag. 202 hcolor variable. 349 Timeout function. <i> tag. JavaScript tags attributes. 297 tool tips. 131 indenting. 23 moving. HTML documents. 204 code. 204-205 scripts. 130 text-transform property. 174. 64. 191-192. 202 position style attribute. 179-181. 23. adding or removing. 338 hiding.

downloading. 136 overflow property. 240 help (mouse cursors). 160 unordered lists. 174 tracking. 118 underscore (_). 77-78 pointer (mouse cursors). 120 em. 336 ShowTip function. HTML Web site. positioning. 349 TextPad Web site.404 tools tools debugging. 77 se-resize (mouse cursors). 119-120 objects. 23 e-resize (mouse cursors). 136 default (mouse cursors). 290 units % (percent sign). consistent styles. 77. 75 auto (mouse cursors). 75 returning for JavaScript functions. 261 TYPE=“text/css” attribute (<style> tag). 266-268 font displayer. 260-262 Bitstream Web site. 220 tree. 277 values absolute (position property). 144 tree layer navigation bars. 268 dynamic fonts. 336-337 ShowIt function. 363 V validators. 78 block (display property). 134 toString method. 136 ne-resize (mouse cursors). mouse pointers. 119 px (pixels). <u> tag. 136 hidden (overflow property). 350 development. 136 position property. 77 list-item (display property). 79. 77 cursor attribute. 261 Web site. 277. <ul> tag. 21. 136 nw-resize (mouse cursors). 51. 308 translating property names. 77 U <ul> tag. 136 scroll (overflow property). 119-120 units (sizes) of fonts. 77 none (mouse cursors). 136 . 125. 21 updating graphics. 191 trees. 349 HomeSite Web site. 204 <tr> tag. 136 n-resize (mouse cursors). 222 UnHighlight function. 76. 349 tooltips HideTip function. 156 userAgent (Web browser version information). 138. 136 auto (overflow property). 164 underlined text. 136. 77 move (mouse cursors). 75 GetObject function. 119 style sheets. 41 s-resize (mouse cursors).js file. 136 none (display property). 123 top-border-width property. 136 fixed (position property). 77 inherit (overflow property). 120 ex. 335-336 top property. 180. 136 display property. See menu trees Truedoc fonts. 76 pt (points). 75 relative (position property). Hangman game. 323 usability. 66. 78 inline (display property).

moving text. 66. 136 var keyword. 132 headings. 12-13. 202 scrolling messages. 75 sw-resize (mouse cursors). 12 dynamic fonts. 38 JavaScript functions. 121. supporting. See also Internet Explorer.length (if statement). 272 events. 216 vertical-align property. 204 hex. 77 w-resize (mouse cursors). 237 cross-browser functions. 123. 195 Internet Explorer 4 DHTML. 239-247 detecting.Web browsers 405 static (position property). 36 arrays. 205 JavaScript. 201 fonts. 350 wait value (mouse cursors). 302 differences. 13 Netscape 4 DHTML. accommodating. 41 local and global. 104. 136 text (mouse cursors). 235-236 detecting types of for mouse pointer animations. 319 local. checking. moving text. 272 newtext. 109 fading text. 206 position (Move function). 234-235 feature sensing. 19. 307 msg. scrolling messages. 136 Web browser compatibility (W3C DOM). displaying. 232-233 compatibility testing. 201 navigator object properties. displaying. 136 wait (mouse cursors). 77. supporting. 12. 162 DOM (Document Object Model). 37 declaring. 232 DISABLED attribute (<link> tag). 232 browser sensing. 206 naming. 201 browser sensing. 238 new browsers. 136 visible (overflow property). 20. checking. 37 strings. Netscape blinking text. 37 variables. 34 moving text. 241-242 cross-browser DHTML. 103 W3C HTML Validation Service Web site. 260-261 error messages. displaying. direction. 207 pos moving text. 192. 204 hex. 357-358 W3C DOM Level 2 standard. 21 Internet Explorer menu trees. 276 cross-browser animation example. 9. 136 W3C (World Wide Web Consortium). finding. 233-234 Netscape. comparing. 357-358 Web browsers. scrolling messages. 335 visible value (overflow property). 232-234 feature sensing. 202 global. accommodating. 52 . 241-242 objects. 37 hcolor. 37. 238-239 JavaScript support. code. 273 mouse pointer animations. Hangman game. 348 W3C DOM. 77 W–Z w-resize value (mouse cursors). moving text. 130 visibility property. code to display.

178.(minus sign) icon. 261 CGI Resource Index. code. 215 GIF (Graphics Interchange Format) images. 14 Web sites AI Internet Solutions (CSE HTML Validator) Web. 349 menu trees. laying out. 241-242 scrolling messages. 189 HTML documents. 138. defining. 293 Lynx. 207 styles. 348 Web Embedding Fonts Tool (WEFT). 349 Bitstream. 125. downloading. 29. 276 Macromedia 215. DOM (Document Object Model).gif. displaying in Web browsers. 261 graphics. 214 Dynamic HTML. 188-193 events.406 Web browsers older browsers accommodating. code to create. 277. defining. 347 JavaScript FAQ. 350 CSS files. 363-364 Web Design Group Web site. 10 JavaScript code example. 215 JavaScript images. 288-289 HTML files. downloading. 214 Java. 350 code listings. downloading. 188-193 . 348 Internet Related Technologies DOM cross-reference. downloading. 289-290 menus. 191-194 main categories. 20 DOM (Document Object Model). 289 Web pages. logo. 6 images. 290-293 layers. 44 JavaScript. expanding or collapsing. 162 DHTML resources. creating. 43-44 JavaScript scripts. 160-161 versions. 347-348 JavaScript Workshop. 42-45 laying out. downloading. 263 Web pages creating with HTML (Hypertext Markup Language). 348 JavaScript Reference. 194 complex DHTML sites. 6-7 headings. 350 Allaire (HomeSite). 306 Helios Software Solutions (TextPad). 237 supporting. 6. 348 JavaScript resources. downloading. 277 HTMLcenter. 21 HTML (Hypertext Markup Language). 8-9 Web programming languages. 350 JavaScript Developer Central Web site. 288-289 static. 188 . 214 movies. 6-7 text effects. downloading. 214 Flash. downloading. 189-191 JavaScript functions. 261 dynamic fonts. 215 Bare Bones Software (BBEdit). 6 dynamic.gif file. 348 font displayer (Truedoc fonts). 27-29 CSS (Cascading Style Sheets). 348 logo. 349 animations. 6 displaying. 288 CSE HTML Validator. 349 HTML documents creating. 188 + (plus sign) icon. 348 JavaScript debugger. 260 Web Font Wizard demo version. 162 HTML validators. 288 for dynamic Web sites.

348 writing. 277.com DHTML Lab. 40 white-space property.com Web site. 12. 237 z-index property. 348 WebReview.z-index property 407 nested categories. 123 . 264-266 WEFT (Web Embedding Fonts Tool) while keyword. 261 Script Debugger. 76. 350 Website Abstraction.status property. 348 Mozilla team. 362 JavaScript debugger. 350 Opera. 349 Microsoft DHTML menus. 133 wildcards. 350 JavaScript Developer Central. 252 SlickEdit.js file. 327 word lists.com DHTML Lab Web site. 205 window. downloading. 348 WebReference. 339 HTML document. 159 Internet Explorer versions. 350 Netscape DOM Level 0. 9. 351 Script Debugger (Microsoft). 19. 56. 341-342 wizards Web Font Wizard demo version. 339-341 JavaScript function. 216. downloading.gif file. 348 word lists. 348 W3C HTML Validation Service. 348 WEFT (Web Embedding Fonts Tool). 350 Web Design Group. 22 width property. 350 server-side languages.setTimeout method. cross-browser DHTML. 40 while loops (JavaScript). 12. downloading. 66 window object. 43 Windows fonts. 207 window. 347 JavaScript Reference. 130 words. 189 MicroEdge (SlickEdit). 305 Mozilla team (Netscape). 180. 276 windows creating. downloading. 362 window. 79. 130 width attribute. 327 word-spacing property. 260-261. 350 WEFT (Web Embedding Fonts Tool). 123. 7 fonts. 349 style sheets. 264 mouse. 19. Hangman game. 261 dynamic fonts. installing. 348 WebReview. 261 W3C (World Wide Web Consortium).com. 138 Sun (Java). 326-327 wordlist. 215 Truedoc fonts. choosing for Hangman game. 321 World Wide Web Consortium (W3C). 188-189 objects. 276 Perl.setTimeout property. 76.com. 350 Website Abstraction Web site. 327 WebReference. 350 PHP. * (asterisk). 263 word list JavaScript file.

Sign up to vote on this title
UsefulNot useful