JavaScript® Weekend Crash Course™ Steven W. Disbrow
Hungry Minds, Inc. New York, NY • Cleveland, OH • Indianapolis, IN
Preface
T
his book is for anyone who needs to learn how to create a JavaScript-based Web site. If you have no programming experience, you’ll find a complete introduction to the JavaScript language along with examples of how to carry out common Web-programming tasks. If you already know about “JavaScript the language,” you’ll find a ton of tips and techniques that you can use to enhance your existing Web sites.
Who Should Read this Book If you need to put together a Web site that does something more than just sit there, this book is for you. Over the course of one weekend, you’ll learn about the JavaScript language and how it fits into the scheme of Web page creation. Along the way, you’ll learn about lots of other Web-based technologies and how JavaScript can work with them to create interactive and interesting Web sites. It’s important to note that this is not a JavaScript reference book! If you are looking for table after table of JavaScript language minutiae, you won’t find it here. Instead, you’ll find examples of how JavaScript can be used to solve real Web-programming challenges.
What’s in this Book This book is divided into 30 sessions, each addressing one aspect of the JavaScript language or some technique for which JavaScript can be used. Each of these sessions should take you about 30 minutes to get through, although you can expect
x
Preface
to spend more time with each session if you examine the source code on the accompanying CD-ROM. Because the goal of this book is to teach you the basics of JavaScript in a weekend, it’s been broken into six parts: Part I contains four lessons (which should take about two hours to complete) that will teach you the basics of the JavaScript language and how JavaScript fits into a Web page. Part II is six sessions long (and should take about three hours to complete). It will introduce you to some of JavaScript’s built-in objects, the Browser Object Model, and the concept of browser events. Part III is also six sessions in length. The focus of this part of the book is on how JavaScript can be used to dynamically create HTML and manipulate the various controls that are found in an HTML form. Part IV is just four sessions long, but that’s just enough time to give you an understanding of how you can create your own objects with JavaScript and use them to enhance your Web pages. The last session in this part also tells you how you can dynamically build and execute JavaScript statements after your Web page has been loaded. Part V is six sessions long. The sessions in this part focus on identifying different browsers, using Dynamic HTML and Cascading Style Sheets, and working with windows and frames. Part VI is four sessions long and focuses on how JavaScript can be used to communicate with other processes. These include server-side CGI processes, browser plug-ins, and Java applets. At the end of each session, you’ll find a short summary and a set of questions, both designed to remind you of what you’ve learned in that session. At the end of each part, you’ll find twenty questions that will test how much you actually remember from the previous sessions. Some of these will be simple short-answer questions, but many are actual programming puzzles. You are encouraged to try and solve these on your own, but, if you need the answers right away, you’ll find them on your CD-ROM. Once you’ve finished the entire book, you’ll probably want to try the self-assessment test on the CD-ROM. This is a simple multiple-choice test that will give you a good idea of how much you’ve actually learned. In keeping with the title Weekend Crash Course, you’ll find that this book is about learning how to get things done with JavaScript. Because of that, this book is a bit different from most of the other JavaScript books out there. Whereas most books start off by telling you how fragmented the JavaScript “standard” is (each version of each browser has its own flavor of JavaScript) and then spend a tremendous amount of time teaching you how to work around all the differences, you’ll
Acknowledgments
O
f course, I have to thank Neil Romanosky, Barbra Guerra, Galen Mayfield, Maarten Reilingh, Dale White, Debra Williams Cauley, and all the other great folks at Hungry Minds. I had always feared that writing a book would be hard, but these guys made it seem like a piece of cake. I’d also like to thank Lisa Swayne and everyone at the Swayne Agency for taking a chance on me and looking out for me. Finally, I need to thank Zack Czengöldi, Jami Lowery, and Jeff Berger for donating their time and effort to “reality check” the book as I wrote it. Thanks, guys!
Contents at a Glance Preface ........................................................................................................ix Acknowledgments ......................................................................................xiii
FRIDAY.......................................................................................................2 Part I—Friday Evening ...........................................................................4 Session 1–Getting to Know JavaScript .............................................................5 Session 2–Statements and Operators ..............................................................13 Session 3–Flow of Control Statements ............................................................23 Session 4–How to Write JavaScript Functions ..................................................37
SATURDAY ...............................................................................................48 Part II—Saturday Morning ..................................................................50 Session 5–Working with JavaScript Strings .....................................................51 Session 6–Working with JavaScript Arrays ......................................................61 Session 7–Understanding the Browser Object Model .........................................75 Session 8–Working with the window Object ....................................................85 Session 9–Working with the document Object .................................................97 Session 10–Reacting to Events .....................................................................109 Part III—Saturday Afternoon ...........................................................124 Session 11–Dynamically Creating an HTML Page ............................................125 Session 12–Working with HTML Forms ..........................................................135 Session 13–Working with HTML Controls .......................................................145 Session 14–Working with Images .................................................................163 Session 15–Validating Form Data .................................................................175 Session 16–Cooking up Cookies with JavaScript ............................................187
Part IV—Saturday Evening ................................................................204 Session 17–Understanding JavaScript Objects ................................................205 Session 18–Creating and Using Methods .......................................................217 Session 19–Enhancing HTML with JavaScript Objects ......................................227 Session 20–Dynamically Creating and Executing JavaScript .............................237
Contents
xv
SUNDAY .................................................................................................250 Part V—Sunday Morning ...................................................................252 Session 21–Working with Cascading Style Sheets ...........................................253 Session 22–Creating Dynamic HTML with JavaScript .......................................267 Session 23–Working with Frames .................................................................281 Session 24–Working with Windows ...............................................................293 Session 25–Improving the User Interface ......................................................303 Session 26–Working with Different Browsers .................................................315 Part VI—Sunday Afternoon ..............................................................332 Session 27–Working with Dates, Numbers, and Web Addresses .........................333 Session 28–Communicating with Server-Side Processes ...................................347 Session 29–Supporting Multimedia ...............................................................359 Session 30–Working with Java Applets .........................................................373 Appendix A–Answers to Part Reviews .........................................................381 Appendix B–What’s on the CD-ROM ............................................................393 Index .......................................................................................................397 End User License Agreement.......................................................................423 CD-ROM Installation Instructions ................................................................427
Contents Preface ........................................................................................................ix Acknowledgments ......................................................................................xiii
FRIDAY.......................................................................................................2 Part I—Friday Evening ...........................................................................4 Session 1–Getting to Know JavaScript ............................................................5 So, What Can JavaScript Do? ....................................................................7 What JavaScript Can’t Do .........................................................................8 How JavaScript Fits into a Web Page ..........................................................8 Creating Your First JavaScript Program .....................................................11 Session 2–Statements and Operators ...........................................................13 Assignment Statements .........................................................................14 JavaScript Variables ..............................................................................14 Data types .................................................................................................15 Variable names ...........................................................................................16 Assignment Operators ...........................................................................17 The += operator ..........................................................................................17 Other assignment operators ..........................................................................18 Mathematical Operators .........................................................................18 The increment and decrement operators .........................................................19 Modulus operator ........................................................................................20 Bit flag operators ........................................................................................20 Comments: The Statements That Aren’t ....................................................21
Session 3–Flow of Control Statements ..........................................................23 Understanding Boolean Values and Expressions .........................................23 Comparison operators ..................................................................................24 The equality operator ..............................................................................25 The inequality operator ............................................................................26 Logical operators ........................................................................................26 The logical AND operation ........................................................................26 The logical OR and exclusive OR operations .................................................26 The logical negation operation ..................................................................27 Understanding Flow of Control Statements ...............................................27 The code block ...........................................................................................28 The if and if . . . else statements ..................................................................28
xviii
Contents The assignment error ...................................................................................30 The switch and break statements ..................................................................31 The while and do . . . while statements .........................................................32 The for statement .......................................................................................33 The continue statement ............................................................................34 The ?: operator .......................................................................................35
Session 4–How to Write JavaScript Functions ...............................................37 Creating a Function ..............................................................................38 Calling a function .......................................................................................39 Using a function to reduce code size .............................................................40 Understanding the finer points of functions ...................................................40 Understanding JavaScript Scope Rules .....................................................41 Using External Source Code Files .............................................................43
SATURDAY ...............................................................................................48 Part II—Saturday Morning ..................................................................50 Session 5–Working with JavaScript Strings ...................................................51 String Mechanics ..................................................................................51 Concatenation ............................................................................................52 Simple numeric conversion ...........................................................................53 String Methods and Properties ................................................................53 Using String methods and properties .............................................................54 String methods you can use .........................................................................55 The charAt() method ...............................................................................55 The indexOf() method ..............................................................................56 The lastIndexOf() method .........................................................................57 The split() method ..................................................................................58 The substring() method ...........................................................................58 The toLowerCase() and toUpperCase() methods ...........................................58
Session 6–Working with JavaScript Arrays ....................................................61 What Is an Array? ................................................................................62 How to use an array ....................................................................................62 Using numbered array elements ................................................................63 Using named array elements .....................................................................63 What kind of data can you put into an array? ................................................65 What’s a Multidimensional Array? ...........................................................65 How to access data in a multidimensional array ..............................................66 Array Methods .....................................................................................67 The Array() constructor method ....................................................................67 The concat() method ...................................................................................67
Contents
xix
The join() method .......................................................................................68 The pop() method .......................................................................................68 The push() method .....................................................................................68 The reverse() method ..................................................................................69 The shift() method ......................................................................................69 The slice() method ......................................................................................69 The sort() method .......................................................................................69 The splice() method ....................................................................................70 The toString() method .................................................................................71 The unShift() method ..................................................................................71 The String.split() method ............................................................................71 Putting It All Together ..........................................................................72
Session 7–Understanding the Browser Object Model ......................................75 What’s in the Browser Object Model? ........................................................76 The window object ......................................................................................76 The document object ...................................................................................79 JavaScript and the Browser Object Model ..................................................80 A simple example ........................................................................................80
Session 8–Working with the window Object ..................................................85 Properties of the window Object .............................................................86 The closed property .....................................................................................86 The defaultStatus property ...........................................................................86 The document property ...............................................................................86 The frames array .........................................................................................86 The history property ...................................................................................86 The location property ..................................................................................87 The name property ......................................................................................87 The navigator property ................................................................................87 The opener property ....................................................................................87 The parent property ....................................................................................88 The screen property ....................................................................................88 The status property .....................................................................................88 The top property .........................................................................................89 Methods of the window Object ................................................................89 The alert() method ......................................................................................90 The blur() method .......................................................................................90 The clearInterval() and clearTimeout() methods ..............................................90 The close() method .....................................................................................90 The confirm() method .................................................................................91 The focus() method .....................................................................................91 The moveBy() method .................................................................................91 The moveTo() method ..................................................................................91
xx
Contents The open() method .....................................................................................92 The prompt() method ..................................................................................92 The resizeTo() method .................................................................................93 The scroll() and scrollTo() methods ...............................................................93 The scrollBy() method .................................................................................93 The setInterval() and clearInterval() methods ................................................94 The setTimeout() and clearTimeout() methods ................................................94
Session 9–Working with the document Object ..............................................97 Properties of the document Object ..........................................................98 The alinkColor property ...............................................................................98 The anchors array .......................................................................................99 The applets array ........................................................................................99 The bgColor property .................................................................................100 The cookie property ..................................................................................100 The domain property .................................................................................100 The embeds array ......................................................................................101 The fgColor property ..................................................................................101 The forms array .........................................................................................101 The images array .......................................................................................101 The lastModified property ..........................................................................101 The linkColor property ...............................................................................102 The links array ..........................................................................................102 The Link object .....................................................................................102 The location property ................................................................................104 The plugins array ......................................................................................104 The referrer property .................................................................................104 The title property ......................................................................................104 The URL property ......................................................................................105 The vlinkColor property .............................................................................105 Methods of the document Object ...........................................................105 The clear() method ....................................................................................105 The open() and close() methods ..................................................................105 The write() method ...................................................................................107 The writeln() method ................................................................................107
Session 10–Reacting to Events ..................................................................109 What Are “Events?” ............................................................................109 Creating Event Handlers ......................................................................110 Events You Can Handle ........................................................................112 The onabort event .....................................................................................112 The onblur event .......................................................................................112 The onchange event ..................................................................................113
Contents
xxi
The onclick and ondblclick events ...............................................................113 The onerror event ......................................................................................114 Trapping image errors ............................................................................114 Trapping JavaScript errors ......................................................................114 The onfocus event .....................................................................................115 The onkeydown, onkeypress, and onkeyup events .........................................115 The onload event ......................................................................................115 Trapping HTML document loads ...............................................................115 Trapping image loads .............................................................................116 The onmousedown event ............................................................................116 The onmousemove event ............................................................................116 The onmouseout event ...............................................................................116 The onmouseover event ..............................................................................116 The onmouseup event ................................................................................117 The onreset event .....................................................................................117 The onresize event ....................................................................................117 The onsubmit event ...................................................................................118 The onunload event ...................................................................................118 The Anchor Tag’s Nonevent ...................................................................118
Part III—Saturday Afternoon ...........................................................124 Session 11–Dynamically Creating an HTML Page ..........................................125 Dynamically Creating HTML ..................................................................126 HTML == JavaScript string ..........................................................................127 Storing HTML tags in string variables .......................................................127 Creating customized controls ...................................................................129 Debugging your dynamically created HTML ...............................................130 A complete example ..................................................................................131 Dynamically Creating JavaScript ............................................................132
Session 12–Working with HTML Forms ........................................................135 How the form Object Relates to the