JavaScript A Beginner’s Guide Third Edition About the Author John Pollock is employed as a Web Administrator during the day and works on Web sites and other projects during the evening He runs two Web sites devoted to Web development and design—PageResource.com (www.pageresource.com) is a development tutorial site, and JavaScript City (www javascriptcity.com) is a site that offers free JavaScript code to Web developers John holds a bachelor of arts in English from Sam Houston State University and currently lives in New Waverly, Texas with his wife Heather About the Technical Editor Scott Duffy is an author and consultant based in Toronto, Canada He designs and develops Web sites for small and medium-sized companies JavaScript A Beginner’s Guide Third Edition John Pollock New York Chicago San Francisco Lisbon London Madrid Mexico City Milan New Delhi San Juan Seoul Singapore Sydney Toronto Copyright © 2010 by The McGraw-Hill Companies All rights reserved Except as permitted under the United States Copyright Act of 1976, no part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of the publisher ISBN: 978-0-07-163296-6 MHID: 0-07-163296-4 The material in this eBook also appears in the print version of this title: ISBN: 978-0-07-163295-9, MHID: 0-07-163295-6 All trademarks are trademarks of their respective owners Rather than put a trademark symbol after every occurrence of a trad marked name, we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of infring ment of the trademark Where such designations appear in this book, they have been printed with initial caps McGraw-Hill eBooks are available at special quantity discounts to use as premiums and sales promotions, or for use in corporate training programs To contact a representative please e-mail us at bulksales@mcgraw-hill.com Information has been obtained by McGraw-Hill from sources believed to be reliable However, because of the possibility of human or mechanical error by our sources, McGraw-Hill, or others, McGraw-Hill does not guarantee the accuracy, adequacy, or completeness of any information and is not responsible for any errors or omissions or the results obtained from the use of such information TERMS OF USE This is a copyrighted work and The McGraw-Hill Companies, Inc (“McGraw-Hill”) and its licensors reserve all rights in and to the work Use of this work is subject to these terms Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit, distribute, disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill’s prior copsent You may use the work for your own noncommercial and personal use; any other use of the work is strictly prohibited Your right to use the work may be terminated if you fail to comply with these terms THE WORK IS PROVIDED “AS IS.” McGRAW-HILL AND ITS LICENSORS MAKE NO GUARANTEES OR WARRANTIES AS TO THE ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK, INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE McGraw-Hill and its licensors not warrant or guarantee that the functions contained in the work will meet your requirements or that its operation will be uninterrupted or error free Neither McGraw-Hill nor its licensors shall be liable to you or anyone else for any inaccuracy, error or omission, regardless of cause, in the work or for any damages resulting therefrom McGraw-Hill has no responsibility for the content of any information accessed through the work Under no circumstances shall McGraw-Hill and/or its licensors be liable for any indirect, incidental, special, punitive, consequential or similar damages that result from the use of or inability to use the work, even if any of them has been advised of the possibility of such damages This limitation of liability shall apply to any claim or cause whatsoever whether such claim or cause arises in contract, tort or otherwise To my wife Heather Pollock, Bruce and Joy Anderson, and Dr J D and Linda Andrews In memory of James D and Livian Anderson, John William and Edith Hopkins, Burley T and Aline Price, and “Doc” Flores This page intentionally left blank Contents at a Glance Introduction to JavaScript Placing JavaScript in an HTML File 15 Using Variables 33 Using Functions 59 JavaScript Operators Conditional Statements and Loops Event Handlers Objects 87 115 147 175 The Document Object 10 Window Object 11 JavaScript Arrays 205 241 273 12 Math, Number, and Date Objects 305 vii viii JavaScript: A Beginner’s Guide 13 Handling Strings 341 14 JavaScript and Forms 15 JavaScript and Frames 375 407 16 An Introduction to Advanced Techniques A Answers to Self Tests Index 435 467 479 Contents ACKNOWLEDGMENTS INTRODUCTION xix xxi Introduction to JavaScript What You Need to Know Basic HTML and CSS Knowledge Basic Text Editor and Web Browser Knowledge Which Version? Remember, It’s Not Java Similarities to Other Languages Beginning with JavaScript Object Based Client Side Scripting Language Putting It All Together Online Resources Try This 1-1: Use JavaScript to Write Text 3 8 8 9 10 10 ix Appendix: Answers to Self Tests 11 The concat() method is used to combine the elements of two or more arrays and return a new array containing all of the elements 12 The join() method is used to combine the elements of an array into a single string, with each element separated by a specified character 13 The pop() method is used to remove the last element from an array 14 C It sorts the contents alphabetically 15 D A string value Chapter 12: Math, Number, and Date Objects A Take the square roots and other such values of strings and return a number The E property holds the value of Euler’s constant The LN10 property holds the value of the natural logarithm of 10 B False C document.write(Math.PI); The SQRT2 property holds the value of the square root of C absolute The asin() method returns the arcsine of a number sent to it as a parameter The pow() method returns the numeric value of the first parameter raised to the power of the second parameter 10 C var rand_int= Math.floor(Math.random()*8); 11 The sqrt() method returns the square root of a number sent to it as a parameter 12 D An instance of the Date object 13 The getDay() method returns the number of days into the week 14 B False 15 B var weekday= rightnow.getDay(); Chapter 13: Handling Strings The String object provides properties and methods to get information about strings or to modify strings A Creating an instance of the String object and creating a string literal You can create a string literal by assigning a string value to a variable 475 476 JavaScript: A Beginner’s Guide C JavaScript takes the string literal and turns it into a temporary String object C length The length property returns the length of a string B var the_text= “Look at me!”; B charAt() The big() method adds and tags around a string value 10 The concat() method combines two or more strings together and returns the new combined string value 11 D The indexOf() method returns a numeric value that is the position of a character sent as a parameter, but only the position of the first occurrence of that character 12 The italics() method adds and tags around a string value 13 The toString() method returns the string literal value of a String object 14 To replace information in a string, you can use regular expressions and the replace() method of the String object 15 The match() method compares a regular expression and a string to see whether they match Chapter 14: JavaScript and Forms Each time you add a set of and tags to an HTML document, a(n) form object is created The forms array allows you to access a form using an index number B document.forms[3] A document.forms[2].length C document.forms.length Using form names or ids allows you to name the forms on the page that you want to access later A document.f1.e1.value The action property allows you to access the value of the action=“url” attribute in the opening form tag The elements property is an array that allows you to access each element in a specific form 10 The options property is an array that contains an element for each option listed in a select box in a form 11 The reset() method allows you to reset a form using your script Appendix: Answers to Self Tests 12 B true or false 13 When the viewer clicks the submit button on a form, a submit event occurs and can be captured with the onsubmit event handler 14 The submit() method allows you to submit a form without the viewer clicking the submit button 15 D The selectedIndex property Chapter 15: JavaScript and Frames Frames divide a window into two or more separate areas, each containing different content Frames differ from tables because the divisions in a frameset contain separate HTML documents The tags are used to create a frameset A single frame is created with the tags The cols attribute divides a frameset into columns If you want to have a more complex frameset that includes both rows and columns, you can nest one frameset within another A The frames array or a frame name A True C The number of frames in a window 10 B The frame should take up any remaining space in the window 11 A top 12 B top.right_side.location=“frame3.html”; 13 Using a target of top tells the browser to use the full window when opening a URL rather than opening the URL in a frame 14 A True 15 The rows attribute divides a frameset into rows Chapter 16: An Introduction to Advanced Techniques C document.write(“Is there an error?”); B window.alert(“Cool!”); 477 478 JavaScript: A Beginner’s Guide Logical errors are often tougher to find because the syntax of the code is correct Cross-site scripting might allow someone to obtain information from a user of an application Progressive enhancement provides content for all viewers, but enhances it for those with JavaScript in modern browsers A True AJAX stands for Asynchronous JavaScript and XML JavaScript libraries may make some advanced coding tasks easier by making the code easier to write B False 10 A cookie is a small text file that is stored on the end user’s computer 11 B The cookie property of the document object 12 D src 13 B Rollover effect 14 C No, but it can make reading it more difficult or annoying 15 Any answer is correct! Index // (forward slashes), 28 {} (curly brackets), 62–63, 128 + (addition operator), 47, 49–50, 90–92 && (AND operator), 107 = (assignment operator), 36, 88, 97 \ (backslash), 42–43, 47 (dot), 22 “ (quotation marks), 47 escaping characters, 44–46 == (is-equal-to) operator, 102–103 > (is-greater-than) operator103–104 >= (is-greater-than-or-equal-to) operator104–105 < (is-less-than) operator, 104 ), 103–104 is-greater-than-or-equal-to operator (>=), 104–105 is-less-than operator (=), 104–105 483 484 JavaScript: A Beginner’s Guide is-less-than operator (