This content was uploaded by our users and we assume good faith they have the permission to share this book. If you own the copyright to this book and it is wrongfully on our website, we offer a simple DMCA procedure to remove your content from our site. Start by pressing the button below!
To my beloved Tahirih for her support and encouragement.
Credits
Acquisitions Editor
Project Coordinator
Jim Minatel
Courtney MacIntyre
Development Editor
Graphics and Production Specialists
Sharon Nash
Elizabeth Brooks, Joyce Haughey, Jennifer Heleine, LeAndra Hosier, Heather Pope, Mary Gillot Virgin
Production Editor Felicia Robinson
Quality Control Technician
Technical Editor
John Tyler Connoley, John Greenough, Charles Spencer
Will Kelly
Proofreading and Indexing Copy Editor Joanne Slike
Editorial Manager Kathryn Malm
Vice President & Executive Group Publisher Richard Swadley
Vice President and Executive Publisher Robert Ipsen
Vice President and Publisher Joseph B. Wikert
Sossity R. Smith, Johnna VanHoose
About the Author Arman Danesh is the Internet Coordinator for the Bahá’í International Community’s Office of Public Information. In that capacity, he manages the development of numerous Web sites, including The Bahá’í World (www.bahai.org), the official Web site of the Bahá’í Faith, and the Bahá’í World News Services (www.bahaiworldnews.org), an online news service, both of which use JavaScript. Additionally, he is the Technical Director for Juxta Publishing Limited (www.juxta.com). He has been working with JavaScript since the mid-1990s and is the author of some of the earliest books on the subject, including Teach Yourself JavaScript in a Week and JavaScript Developer’s Guide. Arman has authored more than 20 books on technology subjects, including ColdFusion MX Developer’s Handbook (Sybex), Mastering ColdFusion MX (Sybex), SAIR Linux & Gnu Certified Administrator All-in-One Exam Guide (Osborne/McGraw-Hill), and Safe and Secure: Secure Your Home Network and Protect Your Privacy Online (Sams). He is pursuing an advanced degree in computer science at Simon Fraser University outside Vancouver, British Columbia.
Acknowledgments T
he task of writing these long computer books is a daunting one, and it is a process that requires significant contributions from many people who help these projects see their way to completion. For this project, I need to thank the entire team, including Sharon Nash and Jim Minatel at Wiley, as well as all the myriad others involved in preparing, designing, and producing the books there. I also need to thank my family for their patience during the writing of the book. In particular, my wife, Tahirih, and son, Ethan, deserve credit for tolerating the time I had to devote to the preparation of this book.
Contents
Credits
vi
About the Author
vii
Acknowledgments
ix
Introduction
Part 1: JavaScript Basics Task 1: Creating a script Block Task 2: Hiding Your JavaScript Code Task 3: Providing Alternatives to Your JavaScript Code Task 4: Including Outside Source Code Task 5: Commenting Your Scripts Task 6: Writing a JavaScript Command Task 7: Temporarily Removing a Command from a Script Task 8: Using Curly Brackets Task 9: Writing Output to the Browser Task 10: Creating a Variable Task 11: Outputting a Variable Task 12: Creating a String Task 13: Creating a Numeric Variable Task 14: Performing Math Task 15: Concatenating Strings Task 16: Searching for Text in Strings Task 17: Replacing Text in Strings Task 18: Formatting Strings Task 19: Applying Multiple Formatting Functions to a String Task 20: Creating Arrays Task 21: Populating an Array Task 22: Sorting an Array Task 23: Splitting a String at a Delimiter Task 24: Calling Functions
JavaScript in 10 Simple Steps or Less Task 25: Alerting the User Task 26: Confirming with the User Task 27: Creating Your Own Functions Task 28: Passing an Argument to Your Functions Task 29: Returning Values from Your Functions Task 30: Passing Multiple Parameters to Your Functions Task 31: Calling Functions from Tags Task 32: Calling Your JavaScript Code after the Page Has Loaded Task 33: Using for Loops Task 34: Testing Conditions with if Task 35: Using Short-Form Condition Testing Task 36: Looping on a Condition Task 37: Looping through an Array Task 38: Scheduling a Function for Future Execution Task 39: Scheduling a Function for Recurring Execution Task 40: Canceling a Scheduled Function Task 41: Adding Multiple Scripts to a Page Task 42: Calling Your JavaScript Code after the Page Has Loaded Task 43: Check If Java Is Enabled with JavaScript
Part 2: Outputting to the Browser Task 44: Accessing the document Object Task 45: Outputting Dynamic HTML Task 46: Including New Lines in Output Task 47: Outputting the Date to the Browser Task 48: Outputting the Date and Time in a Selected Time Zone Task 49: Controlling the Format of Date Output Task 50: Customizing Output by the Time of Day Task 51: Generating a Monthly Calendar Task 52: Customizing Output Using URL Variables Task 53: Dynamically Generating a Menu Task 54: Replacing the Browser Document with a New Document Task 55: Redirecting the User to a New Page Task 56: Creating a “Page Loading ...” Placeholder
Part 3: Images and Rollovers Task 57: Accessing an HTML-Embedded Image in JavaScript Task 58: Loading an Image Using JavaScript Task 59: Detecting MouseOver Events on Images
Contents Task 60: Detecting Click Events on Images Task 61: Switching an Image Programatically Task 62: Using Multiple Rollovers in One Page Task 63: Displaying a Random Image Task 64: Displaying Multiple Random Images Task 65: Using a Function to Create a Rollover Task 66: Using a Function to Trigger a Rollover Task 67: Using Functions to Create Multiple Rollovers in One Page Task 68: Creating a Simple Rollover Menu System Task 69: Creating a Slide Show in JavaScript Task 70: Randomizing Your Slide Show Task 71: Triggering Slide Show Transitions from Links Task 72: Including Captions in a Slide Show Task 73: Testing If an Image Is Loaded Task 74: Triggering a Rollover in a Different Location with a Link Task 75: Using Image Maps and Rollovers Together Task 76: Generating Animated Banners in JavaScript Task 77: Displaying a Random Banner Ad
Part 4: Working with Forms Task 78: Preparing Your Forms for JavaScript Task 79: Accessing Text Field Contents Task 80: Dynamically Updating Text Fields Task 81: Detecting Changes in Text Fields Task 82: Accessing Selection Lists Task 83: Programmatically Populating a Selection List Task 84: Dynamically Changing Selection List Content Task 85: Detecting Selections in Selection Lists Task 86: Updating One Selection List Based on Selection in Another Task 87: Using Radio Buttons instead of Selection Lists Task 88: Detecting the Selected Radio Button Task 89: Detecting Change of Radio Button Selection Task 90: Updating or Changing Radio Button Selection Task 91: Creating Check Boxes Task 92: Detecting Check Box Selections Task 93: Changing Check Box Selections Task 94: Detecting Changes in Check Box Selections Task 95: Verifying Form Fields in JavaScript Task 96: Using the onSubmit Attribute of the Form Tag to Verify Form Fields
JavaScript in 10 Simple Steps or Less Task 97: Verifying Form Fields Using INPUT TYPE=”button” Instead of TYPE=”submit” Task 98: Validating E-mail Addresses Task 99: Validating Zip Codes Task 100: Validating Phone Numbers Task 101: Validating Credit Card Numbers Task 102: Validating Selection List Choices Task 103: Validating Radio Button Selections Task 104: Validating Check Box Selections Task 105: Validating Passwords Task 106: Validating Phone Numbers with Regular Expressions Task 107: Creating Multiple Form Submission Buttons Using INPUT TYPE=”button” Buttons Task 108: Reacting to Mouse Clicks on Buttons Task 109: Using Graphical Buttons in JavaScript Task 110: Controlling the Form Submission URL Task 111: Validating a Numeric Text Field with Regular Expressions Task 112: Encrypting Data before Submitting It Task 113: Using Forms for Automatic Navigation Jumping
Part 5: Manipulating Browser Windows Task 114: Using the Window Object Task 115: Popping Up an Alert Dialog Box Task 116: Popping Up Confirmation Dialog Boxes Task 117: Popping Up JavaScript Prompts Task 118: Creating New Browser Windows Task 119: Opening a New Browser Window from a Link Task 120: Setting the Size of New Browser Windows Task 121: Setting the Location of New Browser Windows Task 122: Controlling Toolbar Visibility for New Browser Windows Task 123: Determining the Availability of Scroll Bars for New Browser Windows Task 124: Restricting Resizing of New Browser Windows Task 125: Loading a New Document into a Browser Window Task 126: Controlling Window Scrolling from JavaScript Task 127: Opening a Full-Screen Window in Internet Explorer Task 128: Handling the Parent-Child Relationship of Windows Task 129: Updating One Window’s Contents from Another Task 130: Accessing a Form in Another Browser Window Task 131: Closing a Window in JavaScript Task 132: Closing a Window from a Link
Contents Task 133: Creating Dependent Windows in Netscape Task 134: Sizing a Window to Its Contents in Netscape Task 135: Loading Pages into Frames Task 136: Updating One Frame from Another Frame Task 137: Sharing JavaScript Code between Frames Task 138: Using Frames to Store Pseudo-Persistent Data Task 139: Using One Frame for Your Main JavaScript Code Task 140: Using a Hidden Frame for Your JavaScript Code Task 141: Working with Nested Frames Task 142: Updating Multiple Frames from a Link Task 143: Dynamically Creating Frames in JavaScript Task 144: Dynamically Updating Frame Content Task 145: Referring to Unnamed Frames Numerically
Part 6: Manipulating Cookies Task 146: Creating a Cookie in JavaScript Task 147: Accessing a Cookie in JavaScript Task 148: Displaying a Cookie Task 149: Controlling the Expiry of a Cookie Task 150: Using a Cookie to Track a User’s Session Task 151: Using a Cookie to Count Page Access Task 152: Deleting a Cookie Task 153: Creating Multiple Cookies Task 154: Accessing Multiple Cookies Task 155: Using Cookies to Present a Different Home Page for New Visitors Task 156: Creating a Cookie Function Library Task 157: Allowing a Cookie to be Seen for all Pages in a Site
Part 7: DHTML and Style Sheets Task 158: Controlling Line Spacing Task 159: Determining an Object’s Location Task 160: Placing an Object Task 161: Moving an Object Horizontally Task 162: Moving an Object Vertically Task 163: Moving an Object Diagonally Task 164: Controlling Object Movement with Buttons Task 165: Creating the Appearance of Three-Dimensional Movement Task 166: Centering an Object Vertically Task 167: Centering an Object Horizontally
JavaScript in 10 Simple Steps or Less Task 168: Controlling Line Height in CSS Task 169: Creating Drop Shadows with CSS Task 170: Modifying a Drop Shadow Task 171: Removing a Drop Shadow Task 172: Placing a Shadow on a Nonstandard Corner Task 173: Managing Z-Indexes in JavaScript Task 174: Setting Fonts for Text with CSS Task 175: Setting Font Style for Text with CSS Task 176: Controlling Text Alignment with CSS Task 177: Controlling Spacing with CSS Task 178: Controlling Absolute Placement with CSS Task 179: Controlling Relative Placement with CSS Task 180: Adjusting Margins with CSS Task 181: Applying Inline Styles Task 182: Using Document Style Sheets Task 183: Creating Global Style Sheet Files Task 184: Overriding Global Style Sheets for Local Instances Task 185: Creating a Drop Cap with Style Sheets Task 186: Customizing the Appearance of the First Line of Text Task 187: Applying a Special Style to the First Line of Every Element on the Page Task 188: Applying a Special Style to All Links Task 189: Accessing Style Sheet Settings Task 190: Manipulating Style Sheet Settings Task 191: Hiding an Object in JavaScript Task 192: Displaying an Object in JavaScript Task 193: Detecting the Window Size Task 194: Forcing Capitalization with Style Sheet Settings Task 195: Detecting the Number of Colors Task 196: Adjusting Padding with CSS
Part 8: Dynamic User Interaction Task 197: Creating a Simple Pull-Down Menu Task 198: Creating Two Pull-Down Menus Task 199: Detecting and Reacting to Selections in a Pull-Down Menu Task 200: Generating a Drop-Down Menu with a Function Task 201: Placing Menu Code in an External File Task 202: Inserting a Prebuilt Drop-Down Menu Task 203: Creating a Floating Window Task 204: Closing a Floating Window
Contents Task 205: Resizing a Floating Window Task 206: Moving a Floating Window Task 207: Changing the Content of a Floating Window Task 208: Detecting Drag and Drop Task 209: Moving a Dragged Object in Drag and Drop Task 210: Changing Cursor Styles Task 211: Determining the Current Scroll Position Task 212: Creating an Expanding/Collapsing Menu Task 213: Creating a Highlighting Menu Using Just Text and CSS—No JavaScript Task 214: Creating a Highlighting Menu Using Text, CSS, and JavaScript Task 215: Placing Content Offscreen Task 216: Sliding Content into View Task 217: Creating a Sliding Menu Task 218: Auto-Scrolling a Page
Part 9: Handling Events Task 219: Responding to the onMouseOver Event Task 220: Taking Action When the User Clicks on an Object Task 221: Responding to Changes in a Form’s Text Field Task 222: Responding to a Form Field Gaining Focus with onFocus Task 223: Taking Action When a Form Field Loses Focus with onBlur Task 224: Post-Processing Form Data with onSubmit Task 225: Creating Code to Load When a Page Loads with onLoad Task 226: Executing Code When a User Leaves a Page for Another Task 227: Taking Action When a User Makes a Selection in a Selection List
Part 10: Bookmarklets Task 228: Downloading and Installing Bookmarklets Task 229: Checking Page Freshness with a Bookmarklet Task 230: Checking for E-mail Links with a Bookmarklet Task 231: E-mailing Selected Text with a Bookmarklet in Internet Explorer Task 232: E-mailing Selected Text with a Bookmarklet in Netscape Task 233: Displaying Images from a Page with a Bookmarklet Task 234: Changing Background Color with a Bookmarklet Task 235: Removing Background Images with a Bookmarklet Task 236: Hiding Images with a Bookmarklet Task 237: Hiding Banners with a Bookmarklet Task 238: Opening All Links in a New Window with a Bookmarklet Task 239: Changing Page Fonts with a Bookmarklet
JavaScript in 10 Simple Steps or Less Task 240: Highlighting Page Links with a Bookmarklet Task 241: Checking the Current Date and Time with a Bookmarklet Task 242: Checking Your IP Address with a Bookmarklet Task 243: Searching Yahoo! with a Bookmarklet in Internet Explorer Task 244: Searching Yahoo! with a Bookmarklet in Netscape
Part 11: Cross-Browser Compatibility and Issues Task 245: Detecting the Browser Type Task 246: Detecting the Browser Version Task 247: Browser Detection Using Object Testing Task 248: Creating Browser Detection Variables Task 249: Dealing with Differences in Object Placement in Newer Browsers Task 250: Creating Layers with the div Tag Task 251: Controlling Layer Placement in HTML Task 252: Controlling Layer Size in HTML Task 253: Controlling Layer Visibility in HTML Task 254: Controlling Layer Ordering in HTML Task 255: Changing Layer Placement and Size in JavaScript Task 256: Changing Layer Visibility in JavaScript Task 257: Changing Layer Ordering in JavaScript Task 258: Fading Objects Task 259: Creating a Page Transition in Internet Explorer Task 260: Installing the X Cross-Browser Compatibility Library Task 261: Showing and Hiding Elements with X Task 262: Controlling Stacking Order with X Task 263: Changing Text Color with X Task 264: Setting a Background Color with X Task 265: Setting a Background Image with X Task 266: Repositioning an Element with X Task 267: Sliding an Element with X Task 268: Changing Layer Sizes with X
ince the mid-1990s when Netscape introduced version 2 of its flagship Netscape Navigator browser, JavaScript has been part of the Web development landscape. Providing a mechanism to implement dynamic interactivity in the browser, without connecting to the server, JavaScript is at the core of the Dynamic HTML model, which allows today’s modern browsers to host sophisticated applications and user interfaces. This book is a recipe book that provides you with quick, digestible examples of how to perform specific tasks using JavaScript. These tasks range from simple tasks such as displaying dynamic output in the browser window to complex tasks such as creating a dynamic, interactive menu system. This book isn’t a tutorial in JavaScript. It is designed to be a useful reference when you are actively engaged in building your Web applications and need quick answers to the question “How do I do this in JavaScript?” For most tasks of low and medium complexity, you will likely find an example in this book. Completing complex tasks can often be achieved by combining more than one sample tasks from the book.
tip If you don’t have any experience with JavaScript, you will probably want to supplement this book with a tutorial introduction to programming in JavaScript. For instance, you might consider JavaScript for Dummies by Emily A. Vander Veer (John Wiley & Sons, 0-7645-0633-1).
About the Book This book is divided into 11 parts:
Part 1: JavaScript Basics This part provides tasks that illustrate some fundamental JavaScript techniques and skills. If you have never used JavaScript before, this part is for you. It provides examples that illustrate the basics of creating scripts and using JavaScript.
Part 2: Outputting to the Browser This part covers some core techniques for using JavaScript to generate dynamic output to the browser window, including outputting dynamic values such as dates.
xx
JavaScript in 10 Simple Steps or Less
Part 3: Images and Rollovers Using JavaScript, you can manipulate images, producing effects such as rollover effects and random slide shows. The tasks in this part illustrate techniques for working with images from JavaScript.
Part 4: Working with Forms Forms involve more than just submitting data to the server. This part illustrates how to create dynamic client-side forms in the browser and to build forms that work with the user without contacting the server.
Part 5: Manipulating Browser Windows This part provides tasks that illustrate the creation and closing of windows, how to manage the attributes of those windows, and how to work with frames. All these features are key to developing sophisticated user interfaces with JavaScript.
Part 6: Manipulating Cookies Normally, cookies are created by your server and sent to the browser for storage. The browser then sends them back to the server when the user connects to that server. Now with JavaScript, you can create cookies and access them later without any interaction with the server.
Part 7: DHTML and Style Sheets JavaScript is part of a threesome that forms Dynamic HTML. The other parts are the Domain Object Model and cascading style sheets. The tasks in this part show you how to work with the DOM and style sheets.
Part 8: Dynamic User Interaction This part provides tasks that illustrate some of the most popular uses of JavaScript for dynamic user interaction—from creating pull-down menus to producing floating windows and handling drag-and-drop user interaction.
Part 9: Handling Events JavaScript is an event-driven scripting language. This means you don’t create linear programs but instead can write your programs to respond to events. Events might be the user clicking on a button or the completion of a task by the browser, such as completing loading of the current document.
Part 10: Bookmarklets Bookmarklets are an interesting application of JavaScript that combines JavaScript with the bookmarks or favorites feature of browser. Bookmarklets are short, self-contained JavaScript scripts that perform some useful task that you can add to your favorites or bookmarks and then run at any time by selecting the relevant favorite or bookmark.
Introduction
xxi
Part 11: Cross-Browser Compatibility and Issues As JavaScript has become more advanced and its features have expanded, browser compatibility has become an issue. As would be expected, different browser vendors have different ideas about the right way to do things in their implementations of JavaScript. The result is a plethora of browsers with subtle differences in the way JavaScript works. The tasks in this part provide you with some techniques for handling these browser differences in your applications. The appendices provide you quick references to JavaScript and cascading style sheets you can consult in developing your applications when you need reminders of the correct property, method, or style attribute name. Finally, the complete source code for each task can be found on the companion Web site at www.wiley. com/10stepsorless. This makes it easy for you to try the code illustrated in the task or adapt the code for your own purposes.
Conventions Used in this Book As you go through this book, you will find a few unique elements. We’ll describe those elements here so that you’ll understand them when you see them.
Code If a single line of code is too long to appear as one line in the printed book, we’ll add the following symbol to indicate that the line continues: Æ
Text You Type and Text on the Screen Whenever you are asked to type in text, the text you are to type appears in bold, like this: Type in this address: 111 River Street. When we are referring to URLs or other text you’ll see on the screen, we’ll use a monospace font, like this: Check out www.wiley.com.
Icons A number of special icons appear in the margins of each task to provide additional information you might find helpful.
note
tip
caution
cross-reference
The Note icon is used to provide additional information or help in working in JavaScript.
The Tip icon is used to point out an interesting idea or technique that will save you time, effort, money, or all three.
The Caution icon is used to alert you to potential problems that you might run into when working in JavaScript.
Although this book is divided into tasks to make it easy to find exactly what you’re looking for, few tasks really stand completely alone. The Cross-Reference icon provides us the opportunity to point out other tasks in the book you might want to look at if you’re interested in this task.
Creating a script Block Hiding Your JavaScript Code Providing Alternatives to Your JavaScript Code Including Outside Source Code Commenting Your Scripts Writing a JavaScript Command Temporarily Removing a Command from a Script Using Curly Brackets Writing Output to the Browser Creating a Variable Outputting a Variable Creating a String Creating a Numeric Variable Performing Math Concatenating Strings Searching for Text in Strings Replacing Text in Strings Formatting Strings Applying Multiple Formatting Functions to a String Creating Arrays Populating an Array Sorting an Array Splitting a String at a Delimiter Calling Functions Alerting the User Confirming with the User Creating Your Own Functions Passing an Argument to Your Functions Returning Values from Your Functions Passing Multiple Parameters to Your Functions Calling Functions from Tags Calling Your JavaScript Code after the Page Has Loaded Using for Loops Testing Conditions with if Using Short-Form Condition Testing Looping on a Condition Looping through an Array Scheduling a Function for Future Execution Scheduling a Function for Recurring Execution Canceling a Scheduled Function Adding Multiple Scripts to a Page Calling Your JavaScript Code after the Page Has Loaded Check If Java Is Enabled with JavaScript
2
Task
1
Part 1
Creating a script Block
J
avaScript is a dynamic scripting language that allows you to build interactivity into otherwise static HTML pages. This is done by embedding blocks of JavaScript code almost anywhere in your Web page.
notes
• •
For the purposes of simplicity, you will use JavaScript as the value of the language attribute in all script tags in this book. The current version of JavaScript in the newest browsers in JavaScript 1.5.
To make this work, blocks of JavaScript code are delineated by opening and closing script tags: <script ...> JavaScript code goes here
The script tag takes one important attribute: language. This attribute specifies what scripting language you are using. Typically, its value will be either JavaScript or JavaScript1.0, JavaScript1.1, JavaScript1.2, and so on. By specifying a specific JavaScript version number, you indicate to the browser this script can only run on a browser that supports the specified version of JavaScript. Without that, every JavaScript-capable browser will assume the script is one it should try to run. For instance, the following is an example of a complete script tag: <script language=”JavaScript”> JavaScript code goes here
The following steps outline how to create a simple HTML document with a single embedded script block. The script is responsible for outputting the word “Hello” to the user’s browser: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the body of the document with opening and closing body tags:
3. Insert a script block in the body of the document: <script>
JavaScript Basics 4. Specify JavaScript as the language for the script tag:
3
Task
<script language=”JavaScript”>
1
5. Place any JavaScript code in the script block so that the final code looks like Listing 1-1. <script language=”JavaScript”> document.write(“Hello”);
Listing 1-1: Creating a script block.
6. Save the file. 7. Open the file in your browser. You should see the word “Hello” in your browser, as in Figure 1-1.
cross-reference Figure 1-1: Script code can be placed anywhere in your document, including in
the body of the document.
•
The JavaScript code here uses document.write to output text to the browser window. document.write is covered in a little more depth in Task 9 and in greater depth in Task 45.
4
Task
2
Part 1
Hiding Your JavaScript Code
T
ask 1 showed how to embed JavaScript code in your document. For instance, the following embeds one line of JavaScript code in the body of an HTML document:
notes
•
•
Luckily, JavaScript uses different comment syntax than HTML, so you can use HTML comments to hide JavaScript code without preventing execution of that code in browsers that support JavaScript. In the closing --> of the introductory source code (discussed in Step 5), you see it is preceded by two slashes. These indicate a JavaScript comment. What’s happening here is that once the first line of JavaScript appears in the script block, all subsequent lines are assumed to be JavaScript code. The double slash is a JavaScript comment that hides the closing HTML comment from being processed as JavaScript; otherwise, a JavaScript error would occur, since the browser would treat the closing HTML comment as JavaScript. JavaScript comments are discussed in Task 5.
However, there is a fundamental problem with this code: If this page is opened in a browser that doesn’t support JavaScript or if the user has disabled JavaScript in his or her browser, the user may see the code itself, depending on the specific browser he or she is using. To address this issue, you need to use HTML comments inside the script block to hide the code from these browsers. HTML comments work like this:
Used in the context of a JavaScript script, you would see the following: <script language=”JavaScript”>
The following steps show how to create a script block in the body of a document that includes these comments: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the body of the document with opening and closing body tags:
3. Insert a script block in the body of the document: <script>
JavaScript Basics
5
4. Specify JavaScript as the language for the script tag: <script language=”JavaScript”>
5. Place opening and closing HTML comments in the script block:
6. Place any JavaScript code in the script block so that the final code looks like Listing 2-1. <script language=”JavaScript”>
Listing 2-1: Creating a script block.
7. Save the file. 8. Open the file in a browser that supports JavaScript. You should see the word “Hello” in your browser. Open it in a browser that doesn’t support JavaScript, and you should see nothing, as in Figure 2-1.
Figure 2-1: Script code is hidden from non-JavaScript-capable browsers and is hidden from display.
Task
2
6
Task
3
Part 1
Providing Alternatives to Your JavaScript Code
I note
•
The noscript tag works on a simple principle: JavaScript-aware browsers will recognize the tag and will honor it by not displaying the text inside the block. Older, non-JavaScript browsers, on the other hand, will not recognize the tag as valid HTML. As browsers are supposed to do, they will just ignore the tag they don’t recognize, but all the content between the opening and closing tags will not be ignored and, therefore, will be displayed in the browser.
n Task 2 you saw how to hide JavaScript code from non-JavaScript browsers by using HTML comments. The result is that browsers that don’t support JavaScript see nothing at all where the script block normally would be. However, there are cases where the purpose of the JavaScript code is essential to the page and users of non-JavaScript capable browsers need to be told that they are missing this vital part of the page.
Luckily, there is a solution to this: the noscript tag. The noscript tag allows you to specify HTML to display to the browser only for browsers that don’t support JavaScript. If a browser supports JavaScript, it will ignore the text in the noscript block. To use this, you simply place any HTML for non-JavaScript browsers between opening and closing noscript tags. The following steps show how to embed a script in the body of a document and provide alternative HTML to display for non-JavaScript browsers: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the body of the document with opening and closing body tags:
3. Insert a script block in the body of the document: <script>
4. Specify JavaScript as the language for the script tag: <script language=”JavaScript”>
caution
•
It is important to consider carefully if you want to restrict use of your pages to users with JavaScriptcapable browsers. However small the percentage of users with these older browsers may be, you will be excluding part of your audience if you do this.
5. Place opening and closing HTML comments in the script block:
JavaScript Basics 6. Place any JavaScript code in the script block: document.write(“Hello”);
7. Add a noscript block immediately after the script block: <noscript>
8. In the noscript block, place any text to display to the nonJavaScript-capable browser: <noscript> Hello to the non-JavaScript browser.
9. Save the file. 10. Open the file in a browser that supports JavaScript. You should see the word “Hello” in your browser. Open it in a browser that doesn’t support JavaScript, and you should see the alternate message, as in Figure 3-1.
Figure 3-1: Other browsers display the text in the noscript block.
7
Task
3
8
Task
4
Part 1
Including Outside Source Code
A
s you begin to work more extensively with JavaScript, you will likely find that there are cases where you are reusing identical JavaScript code on multiple pages of a site. For instance, you might be creating a dynamic menu common to all pages in JavaScript.
notes
•
•
Even when there is no JavaScript code in the script block, you still need to close the script tag. Otherwise, all HTML code following the script tag will be seen by browsers as JavaScript and not HTML. This can cause errors in the browser and will definitely mean your pages will not look the way you expect. Notice that this file has no script tags. This will be an external JavaScript and not an HTML file. The script tag is an HTML file that marks the location of JavaScript code. In a JavaScript file, no such markers are needed.
In these cases, you don’t want to be maintaining identical code in multiple HTML files. Luckily, the script tag provides a mechanism to allow you to store JavaScript in an external file and include it into your HTML files. In this way you can build and maintain one JavaScript file containing the common code and simply include it into multiple HTML files. This is achieved using the src attribute of the script tag, which allows you to specify a relative or absolute URL for a JavaScript file, as in the following: <script language=”JavaScript” src=”filename.js”>
The following example uses this technique to include an external JavaScript file in an HTML document: 1. In your editor, create a new file that will contain the JavaScript file’s code. 2. In this file, enter any JavaScript code you want included in the external JavaScript file: // JavaScript Document document.write(“Hello”);
3. Save the file as 4a.js and close the file. 4. In your editor, create a new file that will contain the HTML file. 5. Create the body of the document with opening and closing body tags:
6. In the body of the document, create a script block: <script>
JavaScript Basics 7. Specify JavaScript in the language attribute of the script tag:
9
Task
<script language=”JavaScript”>
4
8. Use the src attribute of the script tag to include the JavaScript file created earlier in Steps 1 to 3: <script language=”JavaScript” src=”4a.js”>
9. Save the file and close it. 10. Open the HTML in your browser. The word “Hello” should appear in the browser window, as illustrated in Figure 4-1.
Figure 4-1: Including an external script file.
tip
•
The convention is to use the .js extension for JavaScript files.
10
Task
5
Part 1
Commenting Your Scripts
A note
•
In the second single line comment example, the comment starts at the double slash so the document.write
command is not part of the comment.
ll the script examples seen in the previous tasks have been short. At most they have been a couple of lines long. However, as your skills advance, you will likely build long, complicated scripts. To ensure that your scripts can be understood by other developers and also to help remind you of your own thinking when you return to your code after a period of time, you should insert comments into the code that explain why the code is designed the way it is. JavaScript provides two types of comments: • Single-line comments that start anywhere in the line and continue to the end of the line. Therefore, both of the following are valid singleline comments: // This is a comment document.write(“Hello”); // This is a comment
• Multiline comments that start with /* and end with */. The following is an example of a multiline comment: /* All of this is a comment */
You can include as many or as few comments as you like in your JavaScript code. The following example builds a simple HTML page with a JavaScript script containing two comments: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the body of the document with opening and closing body tags:
3. Insert a script block in the body of the document: <script>
4. Specify JavaScript as the language for the script tag: <script language=”JavaScript”>
JavaScript Basics
11
5. Place any JavaScript code in the script block:
Task
document.write(“Hello”);
5
6. Add a single-line comment before the document.write command: // This is a one-line comment document.write(“Hello”);
7. Add a multiline comment after the document.write command so that the final script looks like Listing 5-1. <script language=”JavaScript”> // This is a one-line comment document.write(“Hello”); /* This is a multiline comment */
Listing 5-1: Using comments.
8. Save the file. 9. Open the file in your browser. You should see the word “Hello” in your browser, as in Figure 5-1.
Figure 5-1: Only JavaScript code that is not part of a comment is executed.
tip
•
Commenting your code is considered good programming practice regardless of the language you are programming in. Writing clear, concise, meaningful comments to describe your code allows other developers you might work with to understand your code. Plus, they can help you as well: If you come back to your code after a long absence they remind you of the logic you used in building your programs or scripts.
12
Task
6
Part 1
Writing a JavaScript Command
I
n the previous tasks you have seen examples of JavaScript commands. All JavaScript scripts are made up of a series of commands. In its most basic form, a command is some set of JavaScript code ending with a semicolon. For instance, all the following could be considered commands:
notes
• •
A JavaScript program, or a script, is essentially a series of commands executed in sequence or following some specified order. There is no particular format to the commands. They might assign a value as in the first example, they might simply call a method as in the second example, or they might call a method in order to assign a value as in the third example. Still, they are all JavaScript commands.
var a = “Yes”; document.write(“Hello”); result = window.confirm(a);
You can string these commands together in pretty much any way: • Line-by-line: var a = “Yes”; document.write(“Hello”); result = window.confirm(a);
• On the same line: var a = “Yes”; document.write(“Hello”); result = Æ window.confirm(a);
• Any combination: var a = “Yes”; document.write(“Hello”); result = window.confirm(a);
The following task illustrates a script with three commands: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the body of the document with opening and closing body tags:
3. Insert a script block in the body of the document: <script>
4. Specify JavaScript as the language for the script tag: <script language=”JavaScript”>
5. Place opening and closing HTML comments in the script block:
JavaScript Basics 6. Create the first command in the script block. Make sure the command ends with a semicolon: document.write(“Hello”);
7. Create the second command, ending with a semicolon: document.write(“Hello”); document.write(“ there”);
8. Finally, add the third command to the script so that the final page looks like Listing 6-1. <script language=”JavaScript”>
Listing 6-1: Placing three commands in a script.
9. Save the file. 10. Open the file in a browser that supports JavaScript. You should see the phrase “Hello there.” in your browser, as in Figure 6-1.
Figure 6-1: The three commands ran in sequence.
13
Task
6
14
Task
7
Part 1
Temporarily Removing a Command from a Script
S
ometimes when you are working on some particularly complicated JavaScript code or are facing a bug that you just can’t locate, you need to remove lines of code one at a time until you identify the line of code that is causing you grief.
notes
•
•
Debugging is the act of finding and eliminating problems in your code; these problems are known as bugs and can range from simple typographical errors to obscure problems in the logic of your scripts.
However, you don’t want to really delete the line, because once you’ve identified and fixed the problem, you will need to re-create any lines you deleted. That’s where comments come in.
Commenting out lines of code is not the only debugging technique. There are numerous other approaches to debugging, including using tools designed to help you debug. These are advanced subjects not covered in this book.
var myVariable = “Hello”; //document.write(“Hello”);
By way of example, in the following code, the second line will not be executed because the document.write command is after the double slash:
In fact, if this code alone were executed by the browser, nothing would be displayed, since the only command for outputting anything to the browser is commented out. The following task starts with an existing script and shows the effects of commenting out portions of the script. This task starts with the script from Task 6. 1. Open the script from Task 6. 2. Comment out the second command by placing a double slash in front of it: //
3. Save the file and open it in a browser. You should see just the word “Hello .” as in Figure 7-1. Because of the comment, the second command will not execute. 4. Continue editing the file, and comment out the first command as well: // //
7. Save the file and open it in a browser. You should see an empty window, because all the commands are now contained in a multiline comment.
cross-reference
•
Comments were introduced in Task 5. They allow you to hide parts of your script so that they are not executed as JavaScript.
16
Task
8
Part 1
Using Curly Brackets
I
n addition to simple commands that end with a semicolon, such as those you saw in Task 7, JavaScript supports the notion of a compound command. A compound command is a group of commands that together are treated as a single command and can be used wherever JavaScript calls for a single command.
note
•
The compound command in the introductory source code starts with a curly bracket and ends with a curly bracket. The entire package from the opening to the closing bracket is considered a single command for the purposes of such things as the if statement.
As an example, consider a condition in JavaScript. You build a conditional operation in JavaScript as follows: if (condition) command
The basic logic of this statement is this: If the condition is true, then execute the command. For the command, you have two choices: Use a single command ending in a semicolon or use multiple commands bundled together as one. With a single command, you might have the following: if (condition) document.write(“Hello”);
Here, if the condition is true, then document.write is executed. Similarly, the following example groups together three document.write commands as a single compound command: if (condition) { document.write(“Hello”); document.write(“ there”); document.write(“.”); }
The following example shows how to build a compound command using curly brackets: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the body of the document with opening and closing body tags:
3. Insert a script block in the body of the document: <script>
JavaScript Basics 4. Specify JavaScript as the language for the script tag:
17
Task
<script language=”JavaScript”>
8
5. Place opening and closing HTML comments in the script block:
6. Create the first command in the script block. Make sure the command ends with a semicolon: document.write(“Hello”);
7. Create the second command, ending a semicolon: document.write(“Hello”); document.write(“ there”);
8. Finally, place opening and closing curly brackets before and after the two commands so that the final script looks like Listing 8-1: <script language=”JavaScript”>
Listing 8-1: A compound command built out of two commands.
9. Save the file. 10. Open the file in a browser that supports JavaScript. You should see the phrase “Hello there” in your browser.
cross-reference
•
Conditions and if statements are introduced in Task 34. We won’t look at specific conditions here.
18
Task
9
Part 1
Writing Output to the Browser
O
ne of the most practical aspects of JavaScript is the ability to output text and HTML into the browser output stream from within your scripts so that the text and HTML appears in the browser as if it were part of the actual HTML of the document.
notes
•
•
•
An argument is any value passed to a method. A method is a function associated with an object; when you use it, it performs some specified function based on the arguments you provide. The document object is an object associated with the current document being rendered into the browser window. It doesn’t matter that the document.write commands are on separate lines. All that gets sent is the text in the arguments, and document.write does nothing to create line separations after the text it outputs. If you look at the end of the introductory material, you’ll see that the key is that document.writeln is used to output the a.
The key to this is the document.write method. The document.write method outputs any text or HTML contained in its argument to the browser. For instance, if you issue the following document.write command: document.write(“<strong>Hello”);
the browser receives the following HTML and renders it: <strong>Hello
An important point to remember is that document.write does not output any end-of-line-type characters after the text it displays. This means that if you have two document.write commands in a row, the output from those two commands is right next to each other. To illustrate this, consider the following pair of commands: document.write(“Hello”); document.write(“Good-bye”);
You might be inclined to think this will result in the following being sent to the browser: Hello Good-bye
In reality, though, this is not the case. The following is sent: HelloGood-bye
To solve this problem, the document object also includes the writeln method. This method outputs the text followed by a new-line character. Consider the following JavaScript code: document.writeln(“a”); document.write(“b);
This would be sent to the browser as: a b
JavaScript Basics The following task illustrates the use of the document.write and document.writeln methods: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the body of the document with opening and closing body tags, and inside it specify pre tags: <pre>
3. Insert a script block in the body of the document: <script>
4. Specify JavaScript as the language for the script tag: <script language=”JavaScript”>
5. Place opening and closing HTML comments in the script block:
6. Create a series of document.write and document.writeln commands in the script block. The final page should look like Listing 9-1. <pre> <script language=”JavaScript”>
Listing 9-1: Using document.write and document.writeln.
7. Save the file. 8. Open the file in a browser that supports JavaScript. You should see the phrase “Hello there” in your browser.
19
Task
9
20
Task
10
Part 1
Creating a Variable
A
key programming concept is the notion of a variable. Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container. You create a variable by a simple assignment operation:
note
•
In this script you are not creating output to the browser. You are only creating a variable (see Step 3). The normal practice is to put all your JavaScript scripts in the header of your HTML documents and only place JavaScript code required for generating output to the browser in the body of your document.
variable name = some data;
For instance, you might create a variable named day and assign the value Tuesday to it: day = “Tuesday”;
As a matter of good programming practice, you will also want to declare your variables the first time you use them. Declaring a variable helps the browser efficiently and accurately process and manage your variables. To declare a variable, simply use the JavaScript statement var: var myVariable;
This declares a variable named myVariable but doesn’t assign any values to it. You can proceed to assign a value to it in a subsequent JavaScript command: var myVariable; ... myVariable = “some value”;
If you want to declare a variable and assign a value to it right away, you can use a shortcut to do this in one step: var myVariable = “some value”;
You can also assign values to variables multiple times and each time the value of the variable is replaced with the new value. For instance, consider the following:
caution
•
You need to be careful in selecting variable names. Names can include letters, numbers, and the underscore character (_). You should also start the names with a letter.
var day = “Tuesday”; day = “Thursday”; day = “Monday”;
At the end of this code, the value of the day variable is Monday. The following steps show the creation of an actual variable in the header of an HTML document: 1. Create a new HTML document in your editor.
JavaScript Basics
21
2. In the header of the document, create a script block:
Task
<script language=”JavaScript”>
10
3. In the script block, create the variable named myVariable and assign a value to it: var myVariable = “Hello”;
4. Create a body for the document to display any HTML you want to present in the browser. The final page looks like Listing 10-1. <script language=”JavaScript”> var myVariable = “Hello”; We created a variable in the header.
Listing 10-1: Creating variables.
5. Save the file and close it. 6. Open the file in a browser. You should only see the body of the document, as illustrated in Figure 10-1.
Figure 10-1: Creating a variable in JavaScript does not cause any output to be directed to the browser.
tip
•
Although you can get away without declaring variables, it doesn’t hurt to do it and it is good programming practice (see introductory paragraphs).
22
Task
11
Part 1
Outputting a Variable
V
ariables, introduced in Task 10, are containers that hold values. You can use them wherever you would normally use the same values. A perfect example of this is text strings.
note
•
Variables are named containers in which you can store data. You can then refer to that data in your script by the name of the container.
You can use the document.write method to output strings of text to the browser, for instance. There is no reason why a string of text could not be assigned to a variable and then the variable be used to output that text. You just use the variable in place of the string of text as the argument to the document.write method: document.write(myVariable);
This will output the contents of the variable myVariable. The following example shows how to set a variable and the output it in a script: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the body of the document with opening and closing body tags:
3. Insert a script block in the body of the document: <script>
4. Specify JavaScript as the language for the script tag: <script language=”JavaScript”>
5. Place opening and closing HTML comments in the script block: <script language=”JavaScript”>
JavaScript Basics 6. Create a variable named myVariable and assign a text string to it:
23
Task
<script language=”JavaScript”>
7. Use document.write to output the content of the variable so that the final code looks like Listing 11-1. <script language=”JavaScript”>
Listing 11-1: Outputting a variable.
8. Save the file. 9. Open the file in a browser that supports JavaScript. You should see the word “Hello” in your browser, as in Figure 11-1.
cross-reference
•
Figure 11-1: The contents of the variable, not its name, are output.
You will notice that there are no quotation marks around myVariable (see introductory paragraphs). As noted in Task 12, quotation marks denote a string of text; when outputting the content of a variable, you don’t use quotation marks. Otherwise, the name of the variable will be output instead of the content.
24
Task
12
Part 1
Creating a String
W
hen working with data and variables in JavaScript, you need to be aware of the data types you are using. Different data types are managed in different ways, and it is important to understand a few fundamental data types.
note
•
There are a number of different data types in JavaScript. The most basic types are numbers (numeric values), strings (text), and boolean (binary, either-or, values typically represented as true/false or 1/0).
One such data type is a string. A string refers to any sequence of text that can contain letters, numbers, and punctuation. When specifying a text string in JavaScript, you need to enclose the string in single or double quotes. For instance, the following are valid strings: “Hello there” ‘My Phone number is 123-456-7890’
But the following are not valid text strings: “Hello’ What is your name?
In the first case, the opening quote is a double quote, but the closing one is a single quote; you can use either single or double quotes, but the opening and closing ones must match. You use these strings in different contexts—for instance, as arguments to a function or method: document.write(“This is a string”);
You also use them as values assigned to variables: var aVar = “This is a string”;
In both these cases, failure to enclose the string in quotes will actually cause the browser to display an error, because it will treat the string as JavaScript code and the text in the string is not valid JavaScript code. The following task shows the creation of a variable containing a string value in a script: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the body of the document with opening and closing body tags:
JavaScript Basics 3. Insert a script block in the body of the document:
25
Task
<script>
12
4. Specify JavaScript as the language for the script tag: <script language=”JavaScript”>
5. Place opening and closing HTML comments in the script block: <script language=”JavaScript”>
6. Create a variable named myVariable and assign a text string to it: <script language=”JavaScript”>
7. Save the file and close it.
cross-reference
•
Task 10 introduces the creation of variables.
26
Task
13
Part 1
Creating a Numeric Variable
W
hen working with data and variables in JavaScript, you need to be aware of the data types you are using. Different data types are managed in different ways, and it is important to understand a few fundamental data types.
note
•
There are a number of different data types in JavaScript. The most basic types are numbers (numeric values), strings (text), and boolean (binary, either-or, values typically represented as true/false or 1/0).
One such data type is a number. A number refers to any number, positive or negative, that contains only numbers, minus signs, and decimal points. When specifying a number in JavaScript, you should not enclose the string in single or double quotes; if you do, it will be treated as a text string and not a number. For instance, the following are valid numbers: 100 -152.56
But the following are not valid text strings: “250.3” ab32
In the first case, the quotes make the value a text string, and in the second, the letters mean this is not a valid numeric value. You use these numbers in different contexts—for instance, as arguments to a function or method: document.write(375);
You also use them as values assigned to variables: var aVar = 375;
The following task shows how to create a variable containing a numeric value in a script: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the body of the document with opening and closing body tags:
JavaScript Basics 3. Insert a script block in the body of the document: <script>
4. Specify JavaScript as the language for the script tag: <script language=”JavaScript”>
5. Place opening and closing HTML comments in the script block: <script language=”JavaScript”>
6. Create a variable named myVariable and assign a number to it: <script language=”JavaScript”>
7. Save the file and close it.
27
Task
13
28
Task
14
Part 1
Performing Math
W
hen working with numeric values in JavaScript, you can perform mathematics with the numbers. Not only can you add, subtract, multiply, and divide numbers, but you can also perform other advanced mathematical calculations. The four basic mathematical operations are as follows:
note
•
In these types of complex expressions, the operations are evaluated in standard mathematical order, so that multiplication and division are evaluated first, and then addition and subtraction are performed.
• Addition: For instance, 10 + 20 • Subtraction: For instance, 20 – 10 • Multiplication: For instance, 10 * 20 • Division: For instance, 20 / 10 In addition, you can build complex mathematical expressions using combinations of these operations. For instance, the following expression subtracts 10 from the result of 100 divided by 5: 100 / 5 – 10
You can override the order of operation with parentheses. Consider the following mathematical expression: 100 / (5 – 10)
This will calculate the value of 100 divided by the result of subtracting 10 from 5. There are two important points to note about these sorts of mathematical expressions: • You can use them wherever JavaScript expects a single numeric value. For instance, you can assign the results of an expression to a variable: var myVariable = 100 / 5;
• You can use variables containing numeric values anywhere in your mathematical expressions in place of actual numbers. For instance, if thisVar is a variable with the value 5, then the results of the following JavaScript code are the same as the preceding example: var myVariable = 100 / thisVar;
The following task calculates and displays the result of adding 100 and 200 through the use of variables and mathematical operations: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the body of the document with opening and closing body tags:
JavaScript Basics 3. Insert a script block in the body of the document:
29
Task
<script language=”JavaScript”>
4. Create a variable named myVariable and assign the value 100 to it: var myVariable = 100;
tip
•
5. Create a second variable named anotherVariable and assign the value 200 to it: var anotherVariable = 200;
6. Add the values of myVariable and anotherVariable and assign the results to a third variable named anotherVariable: var finalResults = myVariable + anotherVariable;
7. Display the results so that the final page looks like Listing 14-1: <script language=”JavaScript”>
Expressions are a powerful programming concept available in many languages, including JavaScript. They can be mathematical, as in this task, or they can involve any other data types such as strings. At the core, though, they are simple: Expressions are specifications of one or more operations to perform on one or more values; the complete set of operations in the expressions must ultimately evaluate down to a single value. This means expressions can be used anywhere a discrete value would be used.
// -->
Listing 14-1: Performing mathematical operations.
8. Save the file and close it. 9. Open the file in a browser. You should see the number 300 displayed in the browser.
cross-reference
•
For examples of other types of expressions that are not mathematical, see Task 15, which provides an example of a string-based expression.
30
Task
15
Part 1
Concatenating Strings
W
ith text strings you cannot perform mathematical operations like those described for numbers in Task 14. The most common operation performed with text strings is concatenation. Concatenation refers to the act of combining two text strings into one longer text string. For instance, the following combines the strings “ab” and “cd” into the combined string “abcd”:
note
•
When you are working with strings, keep in mind that the plus sign no longer has its mathematical meaning; instead, it indicates that concatenation should be performed.
“ab” + “cd”
As with numeric mathematical operations, there are two points to note about concatenation: • You can use concatenation wherever JavaScript expects a single string value. For instance, you can assign the results of a concatenation to a variable: var myVariable = “ab” + “cd”;
• You can use variables containing string values anywhere in your concatenation in place of actual strings. For instance, if thisVar is a variable with the value “cd” then the results of the following JavaScript code are the same as the preceding example: var myVariable = “ab” + thisVar;
The following task concatenates two strings stored in variables and displays the results: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the body of the document with opening and closing body tags:
3. Insert a script block in the body of the document: <script language=”JavaScript”>
4. Create a variable named myVariable and assign the value “Hello” to it: var myVariable = “Hello”;
JavaScript Basics
31
5. Create a second variable named anotherVariable and assign the value “there” to it:
Task
15
var anotherVariable = “there”;
6. Concatenate the values of myVariable and anotherVariable, along with a space between them, and assign the results to a third variable named finalResults: var finalResults = myVariable + “ “ + Æ anotherVariable;
tip
•
7. Display the results so that the final page looks like Listing 15-1. <script language=”JavaScript”>
Listing 15-1: Using concatenation.
These concatenation examples are expressions. Expressions are a powerful programming concept available in many languages, including JavaScript. They can be mathematical, as in this task, or they can involve any other data types, such as strings. At the core, though, they are simple: Expressions are specifications of one or more operations to perform on one or more values; the complete set of operations in the expressions must ultimately evaluate down to a single value. This means expressions can be used anywhere a discrete value would be used.
8. Save the file and close it. 9. Open the file in a browser. You should see the string “Hello there” displayed in the browser as in Figure 15-1.
cross-reference
•
Anywhere you can use a string, you can use a concatenation expression like the examples in this task. For instance, you can use a concatenation expression as an argument to the document.write
method, which was introduced in Task 9.
Figure 15-1: Displaying the results of concatenation.
32
Task
16
Part 1
Searching for Text in Strings
W
hen working with text strings, sometimes you need to determine if a string contains some specific substring, and if it does, you need to determine where in the string that substring occurs.
notes
•
When you create a string value, an object with properties and methods associated with the string is created and you can access these properties and methods. Assuming you have assigned the string to a variable, you access these as variableName. propertyName and variableName. methodName
•
• •
If you count, you will see that “is” starts at the sixth character in the string. But JavaScript, like many programming languages, starts counting at zero, so the first character is in position 0, the second in position 1, and so on. Therefore, the sixth character is in position 5, and this is the number returned by the search method. If the substring is not found, then the search method returns -1 as the position. The number 6 is displayed (see Step 8), since “there” starts at the seventh character.
For instance, if you have the string “what is happening here” and you search for the substring “is”, you want to know that the string contains “is” but also where “is” occurs. You can perform this type of search with the search method of the string object. To perform this search is simple. If “what is happening here” is stored in the variable testVariable, you would search for “is” with the following: testVariable.search(“is”);
This method returns a numeric value indicating the position in the string where it found “is”. In this case, that position is 5. The following task searches for a substring in another string stored in a variable and displays the position where that substring is found: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the body of the document with opening and closing body tags:
3. Insert a script block in the body of the document: <script language=”JavaScript”>
4. Create a variable named myVariable and assign the value “Hello there” to it: var myVariable = “Hello there”;
5. Create a second variable named therePlace and assign the results of searching for “there” to it: var therePlace = myVariable.search(“there”);
JavaScript Basics 6. Display the results of the search so that the final page looks like Listing 16-1. <script language=”JavaScript”>
Listing 16-1: Searching for a substring.
7. Save the file and close it. 8. Open the file in a browser. You should see the number 6 displayed in the browser as in Figure 16-1.
Figure 16-1: Displaying the results of searching for a substring.
33
Task
16
34
Task
17
Part 1
Replacing Text in Strings
I
n Task 16 you saw that it is possible to search for text in strings. Sometimes, though, you will want to search for, find, and replace text in a string. The string object provides the replace method for just such purposes.
note
•
The replace method works in pretty much the same way as the search method, except that you must provide two strings as arguments: The first is the substring to search for, while the second is the substring to replace it with, assuming the first substring is found.
Consider a variable named thisVar containing the string “Today is Monday”. You could search and replace “Monday” with “Friday” with the following: thisVar.replace(“Monday”,”Friday”);
When you use the replace method, the method returns a new string containing the results of performing the replacement. The original string is not altered. For instance, consider assigning the results of the replacement above to a new variable: var newVar = thisVar.replace(“Monday”,”Friday”);
In this case, thisVar will continue to contain “Today is Monday” but newVar will contain “Today is Friday”. The following task creates a variable and assigns text to it, replaces that text with new text, and then displays the results in a browser: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the body of the document with opening and closing body tags:
3. Insert a script block in the body of the document: <script language=”JavaScript”>
4. Create a variable named myVariable and assign the value “Hello there” to it: var myVariable = “Hello there”;
JavaScript Basics 5. Create a second variable named newVariable and assign the results of replacing “there” with “Arman” to it: var newVariable = Æ myVariable.replace(“there”,”Arman”);
6. Display the results of the search and replace so the final page looks like Listing 17-1. <script language=”JavaScript”>
Listing 17-1: Search and replace in a string.
7. Save the file and close it. 8. Open the file in a browser. You should see the text “Hello Arman” displayed in the browser as in Figure 17-1.
Figure 17-1: Displaying the results of searching for a substring and replacing it.
35
Task
17
36
Task
18
Part 1
Formatting Strings
W
hen you create a text string in JavaScript, a string object is associated with that string. The string object provides a series of methods you can use to adjust the format of the string. This can be useful when you want to display a string and quickly apply some formatting to it. The methods are as follows:
note
•
Notice that each document.write
method in the introductory source code outputs the string adjusted by one of the formatting functions and then displays a br tag so that the browser will display each instance on separate lines. Without this, all the instances would appear on one continuous line.
• big: Returns the string in big tags • blink: Returns the string in blink tags • bold: Returns the string in b tags • fixed: Returns the string in tt tags (for fixed-width display) • fontcolor: Returns the string in font tags with the color attribute set to the color you specify as an argument • fontsize: Returns the string in font tags with the size attribute set to the size you specify as an argument • italics: Returns the string in i tags • small: Returns the string in small tags • strike: Returns the string in strike tags (for a strikethrough effect) • sub: Returns the string in sub tags (for a subscript effect) • sup: Returns the string in sup tags (for a superscript effect) • toLowerCase: Returns the string with all lowercase characters • toUpperCase: Returns the string with all upper case characters Assuming you have assigned a string to a variable, you call these methods as follows: variableName.big(); variableName.fontcolor(“red”); variableName.toLowerCase(); etc.
The following task displays the same string using each of these methods: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the body of the document with opening and closing body tags:
JavaScript Basics
37
3. Insert a script block in the body of the document: <script language=”JavaScript”>
4. Create a variable named myVariable and assign the value “Hello there” to it: var myVariable = “Hello there”;
5. Use the document.write method to display the value of the variable as altered by each of the formatting methods, as shown in Listing 18-1. <script language=”JavaScript”> ”); document.write(myVariable.blink() + “ ”); document.write(myVariable.bold() + “ ”); document.write(myVariable.fixed() + “ ”); document.write(myVariable.fontcolor(“red”) + “ ”); document.write(myVariable.fontsize(“18pt”) + “ ”); document.write(myVariable.italics() + “ ”); document.write(myVariable.small() + “ ”); document.write(myVariable.strike() + “ ”); document.write(myVariable.sub() + “ ”); document.write(myVariable.sup() + “ ”); document.write(myVariable.toLowerCase() + “ ”); document.write(myVariable.toUpperCase() + “ ”); // -->
Listing 18-1: Using string formatting functions.
6. Open the file in a browser. You should see the text “Hello there” displayed once for each of the formatting methods.
Task
18
38
Task
19
Part 1
Applying Multiple Formatting Functions to a String
I
n Task 18, you saw how to apply formatting functions to a string manually. However, you can apply multiple formatting if you want. An obvious way to do this is by assigning the new string to a variable at each step of the way:
note
•
Assigning the new string to a variable at each step works, but it is cumbersome and creates far more variables than are needed.
var firstString = “My String”; var secondString = firstString.bold(); var thirdString = secondString.toLowerCase(); etc.
You can shortcut this by relying on the fact that each of these formatting methods returns a string that is an object that, in turn, has its own set of formatting methods that can be called. This allows you to string together the functions like this: var firstString = “My String”; var finalString = firstString.bold().toLowerCase().fontcolor(“red”);
The end result of this is the following HTML stored in finalString: my string
In the following task you take a string and apply bolding, italicization, coloring, and sizing to it before displaying it: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the body of the document with opening and closing body tags:
3. Insert a script block in the body of the document: <script language=”JavaScript”>
4. Create a variable named myVariable and assign the value “Hello there” to it: var myVariable = “Hello there”;
JavaScript Basics 5. Apply bolding, italicization, coloring, and sizing to the string and assign the results to newVariable: var newVariable = Æ myVariable.bold().italics().fontcolor(“blue”).fontsizeÆ (“24pt”);
6. Use the document.write method to display the final string so that the final page looks like Listing 19-1. <script language=”JavaScript”>
Listing 19-1: Applying multiple styles.
7. Open the file in a browser. You should see the text “Hello there” displayed with the formatting applied as in Figure 19-1.
Figure 19-1: Displaying a string with multiple formats applied.
39
Task
19
40
Task
20
Part 1
Creating Arrays
I
n addition to simple data types such as text strings and numbers, JavaScript supports a more complicated data type known as an array. An array is a collection of individual values grouped together. An array essentially contains a series of numbered containers into which you can place values. Each container can contain a string, a number, or any other data type.
notes
•
• •
You probably noticed that the first container is numbered 0. Like many programming languages, JavaScript starts counting at zero, so the first container in an array is numbered 0.
You refer to containers in the array as arrayName[0], arrayName[1], arrayName[2], and so on. Each of these individual containers can be manipulated and used just like a regular variable. You can imagine an array as illustrated in Figure 20-1; here you see a set of boxes where each box is numbered and each box has something inside it. The box numbers are the indexes for each box, and the value inside is the value of each array entry.
The number representing each container in an array (such as 0, 1, or 2) is known as the index.
1
Contents of element 1
2
Contents of element 2
If you create an array with 5 elements, then the indexes of the elements are 0, 1, 2, 3, and 4.
3
Contents of element 3
4
Contents of element 4
5
Contents of element 5
Figure 20-1: Visualizing an array.
To create a new array, you create a new instance of the Array object: var arrayName = new Array(number of elements);
The number of elements is just the initial number of elements in the array; you can add more on the fly as you work with the array, but it is a good idea to initialize the array with the likely number of elements you will use. The array is then accessed through arrayName.
JavaScript Basics The following task creates an array in a script in the header of a document: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the head of the document with opening and closing head tags:
3. Insert a script block in the head of the document: <script language=”JavaScript”>
4. Create a variable named myArray and initialize it as a new array with five elements: <script language=”JavaScript”>
5. Save the file and close it.
41
Task
20
42
Task
21
Part 1
Populating an Array
T
ask 21 showed you how to create an array. An array isn’t very useful, however, unless you can populate its elements with values. You populate the elements of an array by assigning values to the elements just as you assign values to normal variables:
note
•
The numeric value for each container in an array is known as the index.
arrayName[0] = value 1; arrayName[1] = value 2; etc.
In addition, you can actually populate the array at the time you create it; instead of specifying the number of elements to create in the array when you create it, you can specify a comma-separated list of values for the elements of the array: var arrayName = new Array(value 1, value 2, value 3, etc.)
The following task illustrates the creation of two arrays that will contain an identical set of five elements. The two arrays are created and populated using these two different techniques. 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the head of the document with opening and closing head tags:
3. Insert a script block in the head of the document: <script language=”JavaScript”>
4. Create a variable named myArray and initialize it as a new array with five elements: var myArray = new Array(5);
JavaScript Basics
43
5. Assign values to the five elements: myArray[0] myArray[1] myArray[2] myArray[3] myArray[4]
6. Create a second array named anotherArray and assign five values to it at the time it is created. The final script should look like Listing 21-1.
tips
•
<script language=”JavaScript”>
Listing 21-1: Two methods for creating arrays.
7. Save the file and close it.
21
•
You don’t need to populate the elements in order and can leave elements empty. For instance, you might populate the fifth, first, and second elements in an array in that order and leave the third and fourth elements empty. That’s just fine. You can also assign other types of values to array elements other than strings. We just happen to use strings in this example. If you want, you could assign numbers or even other arrays as values of an array’s elements.
44
Task
22
Part 1
Sorting an Array
O
nce you have populated an array as outlined in Task 21, you might find it useful to sort the elements in the array. Sometimes you will want to output the elements of the array in the order in which they were created and added to the array, but at others times you will want them sorted.
note
•
Notice that in Step 6 the myArray.sort method is used as the argument for the document.write method. The latter expects a string value as an argument, and the former returns just that: a string containing a sorted list of elements.
The array object provides a sort method that does just this: It returns a commaseparated list of the elements in sorted order. Sorting is performed in ascending order alphabetically or numerically as appropriate. To use the method, simply call it: arrayName.sort();
The following task creates an array with five elements and then displays the elements in sorted order: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the body of the document with opening and closing body tags:
3. Insert a script block in the body of the document: <script language=”JavaScript”>
4. Create a variable named myArray, and initialize it as a new array with five elements: var myArray = new Array(5);
5. Assign values to the five elements: myArray[0] myArray[1] myArray[2] myArray[3] myArray[4]
= = = = =
“z”; “c”; “d”; “a”; “q”;
JavaScript Basics 6. Use the document.write method and the sort method to output the sorted list of elements so that the final script looks like Listing 22-1.
45
Task
22
<script language=”JavaScript”>
Listing 22-1: Displaying a sorted array.
7. Save the file and close it. 8. Open the file in a browser, and you should see a comma-separated list of elements sorted in alphabetical order, as in Figure 22-1.
Figure 22-1: Displaying a sorted list of elements from the array.
cross-reference
•
The techniques for creating an array are discussed in Task 20. Creating an array is the first step toward populating an array with values, which is the subject of Task 21.
46
Task
23
Part 1
Splitting a String at a Delimiter
I
n programming, it is not uncommon to deal with data represented in delimited lists. A delimited list is typically a string that contains a number of substrings separated by a specific character; each of the substrings is an element in the list. For instance, the following string has three elements separated by commas:
note
•
Notice in Step 8 that the letters have no spaces or other separators between them. This is because the document.write method does not insert any type of separator after the text it outputs, and you have not added any HTML to create the separation.
“First element,Second element,Third element”
The string object provides the split method, which you can use to split a string into elements at a specified delimiter. These elements are then placed in an array, and that array is returned by the method. For instance, consider the following: var thisVar = “First element,Second element,Third element”; var anotherVar = thisVar.split(“,”);
anotherVar is now an array containing three elements.
The following task illustrates this by splitting a string containing a list into its component elements and then outputting those elements from the resulting array: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the body of the document with opening and closing body tags:
3. Insert a script block in the body of the document: <script language=”JavaScript”>
4. Create a variable named myVariable and assign a commaseparated text string to it: var myVariable = “a,b,c,d”;
JavaScript Basics 5. Use the split method to split the string at the commas and assign the resulting array to the variable stringArray:
47
Task
23
var stringArray = myVariable.split(“,”);
6. Use the document.write method to output the elements of the array so that the final script looks like Listing 23-1. <script language=”JavaScript”>
Listing 23-1: Splitting a list into an array.
7. Save the file and close it. 8. Open the file in a browser, and you should see the text “abcd”, as in Figure 23-1.
cross-reference
•
Figure 23-1: Displaying elements from an array built from a comma-separated list.
The creation and population of arrays is discussed in Task 20 and 21.
48
Task
24
Part 1
Calling Functions
I
n many tasks throughout the book, you will see examples of calling functions or methods. A function is a self-contained procedure or operation that you can invoke by name. In invoking it, you can provide data to the function (known as arguments), and then the function, in turn, can return a result based on its operations.
notes
• •
•
Methods are the same as functions except that they are associated with specific objects. Calling them and using them is technically the same.
To call a function, you simply use the following form: functionName(argument 1, argument 2, etc.);
If a function expects no arguments, you still need the parentheses:
When embedding functions as the arguments to other functions, take care with the parentheses to make sure each opening parenthesis is closed by a closing one. A common mistake is to omit a closing parenthesis, which will cause errors in the browser and, at times, can be hard to identify when you try to debug you code.
functionName();
The Escape function takes a text string as an argument and returns it in URLencoded format. In URL-encoded format, special characters that are invalid in URLs (such as spaces and some punctuation) are converted into special code.
function1Name(function2Name());
Also, if a function returns a value, you can use that function call wherever you would use any other text or numeric value. For instance, you can assign the value to a variable: var variableName = functionName();
Similarly, you could use the results of one function as an argument to another function:
The following task calls the JavaScript Escape function and then displays the results that are retuned in the browser: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the body of the document with opening and closing body tags:
3. Insert a script block in the body of the document: <script language=”JavaScript”>
JavaScript Basics 4. Call the Escape function and pass a text string as an argument. Assign the string that is returned to the myVariable variable: <script language=”JavaScript”>
5. Use the document.write method to output the value of myVariable so that the final script looks like Listing 24-1. <script language=”JavaScript”>
Listing 24-1: Escaping a text string.
6. Save the file and close it. 7. Open the file in a browser, and you should see the text string in its URL-encoded representation as in Figure 24-1.
Figure 24-1: A URL-encoded text string.
49
Task
24
50
Task
25
Part 1
Alerting the User
T
he window object provides the alert method, which allows you to display a simple dialog box containing a text message followed by a single button the user can use to acknowledge the message and close the dialog box.
notes
•
•
The dialog boxes created by the window.alert method are quite generic and have clear indications that they come from the current Web page (Internet Explorer places its name in the title bar, and Netscape clearly says “JavaScript Application”). This is done for security: You can’t pop up a dialog box with this method that represents itself as anything but the result of a JavaScript script running in the current page. When the alert dialog box displays (see Step 4), interaction with the browser window is blocked until the user closes the dialog box by clicking the button in the dialog box.
Figure 25-1 illustrates an alert dialog box in Microsoft Internet Explorer; Figure 25-2 shows the same dialog box in Netscape.
Figure 25-1: An alert dialog box in Internet Explorer.
Figure 25-2: An alert dialog box in Netscape.
The following steps show how to display an alert dialog box: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the header of the document with opening and closing header tags:
JavaScript Basics 3. Insert a script block in the header of the document:
51
Task
<script language=”JavaScript”>
4. Call the window.alert method to display a message in a dialog box: <script language=”JavaScript”>
5. Save the file and close it. 6. Open the file in a browser, and you should see a dialog box like the one in Figure 25-3.
Figure 25-3: Displaying an alert dialog box.
cross-reference
•
Alert dialog boxes are the simplest you can create with JavaScript. There is no real user interaction; there is just text and a single button for closing the dialog box. This makes them good for displaying messages to the user. The next task illustrates how to create a slightly more complicated dialog box with two buttons: one to accept and one to cancel.
52
Task
26
Part 1
Confirming with the User
I
n addition to the alert method discussed in Task 25, the window object also provides the confirm method, which allows you to display a dialog box containing a text message followed by two buttons the user can use to acknowledge or reject the message and close the dialog box. Typically these buttons are labeled OK and Cancel.
notes
•
•
The dialog boxes created by the window.confirm method are quite generic and have clear indications that they come from the current Web page (Internet Explorer places its name in the title bar and Netscape clearly says “JavaScript Application”). This is done for security: You can’t pop up a dialog box with this method that represents itself as anything but the result of a JavaScript script running in the current page. The window.confirm method returns a value: true if the user clicks on OK or false if the user clicks on Cancel (see Step 4).
Figure 26-1 illustrates a confirmation dialog box in Microsoft Internet Explorer; Figure 26-2 shows the same dialog box in Netscape.
Figure 26-1: A confirmation dialog box in Internet Explorer.
Figure 26-2: A confirmation dialog box in Netscape.
The following steps show how to display a confirmation dialog box and then display the user’s selection in the browser: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the body of the document with opening and closing body tags:
3. Insert a script block in the body of the document: <script language=”JavaScript”>
JavaScript Basics 4. Call the window.confirm method to display a message in a dialog box; assign the selection of the user, which is returned by the method, to the result variable:
53
Task
26
<script language=”JavaScript”>
5. Save the file and close it. 6. Open the file in a browser, and you should see a dialog box like the one in Figure 26-3.
Figure 26-3: Displaying a confirmation dialog box.
7. If you click on OK, you should see “true” in the browser window as in Figure 26-4.
cross-reference
•
Figure 26-4: Displaying the user’s selection in the browser window.
Confirmation dialog boxes only provide primitive user interaction; they don’t let users enter any data. Task 117 illustrates how to create a slightly more complicated dialog box with a text entry field for the user to enter data.
54
Task
27
Part 1
Creating Your Own Functions
N
ot only does JavaScript have a large body of built-in functions and methods, it also allows you to create your own functions. Creating a function is fairly straightforward:
notes
•
•
The advantage here is that if you have tasks or operations that will be repeated multiple times in your application, you can encapsulate it in a function once and then call the function multiple times instead of repeating the code multiple times in your application. Typically, you will not use a function just to display a dialog box. You want to build functions to perform more complex tasks that you will need to repeat multiple times in your application. This is just used to illustrate the creation of a function.
function functionName() { Your function code goes here }
The code in the function can be any valid JavaScript code that you would use elsewhere in your scripts. The following task creates a function that outputs “Hello” to the browser and the proceeds to call that function in order to display the text: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the header of the document with opening and closing head tags:
3. Insert a script block in the header of the document: <script language=”JavaScript”>
4. Create a function named hello that takes no arguments: function head() { }
5. In the function, use document.write to output “Hello” to the browser: document.write(“Hello”);
6. Create the body of the document with opening and closing body tags:
JavaScript Basics 7. Insert a script block in the body of the document:
55
Task
<script language=”JavaScript”>
8. In the script block, call the hello function so that the final page looks like Listing 27-1. <script language=”JavaScript”> <script language=”JavaScript”>
Listing 27-1: Creating and calling your own function.
9. Save the file. 10. Open the file in a browser, and you should see “Hello” in the browser.
cross-reference
•
Functions perform operations on data and return the results of those operations. That means you will want to pass data to your functions (this is outlined in Task 28) and return the results of the function’s processing (this is outlined in Task 29).
56
Task
28
Part 1
Passing an Argument to Your Functions
T
ask 27 showed you how to create a function, but the function created in that task did not accept any arguments. To create a function that accepts arguments, you must specify names for each argument in the argument definition: function functionName(argumentName1,argumentName2,etc.) { Your function code goes here }
The following task creates a function that accepts a single numeric argument, squares that number, and outputs the result: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the header of the document with opening and closing head tags:
3. Insert a script block in the header of the document: <script language=”JavaScript”>
4. Create a function named square that takes one argument named number: function square(number) { }
5. In the function, square the number and assign the results to a variable, and then use document.write to output that result: var result = number * number; document.write(result);
6. Create the body of the document with opening and closing body tags:
JavaScript Basics
57
7. Insert a script block in the body of the document:
Task
<script language=”JavaScript”>
8. In the script block, call the square function and pass in a value of 100 so that the final page looks like Listing 28-1.
Listing 28-1: Creating and calling your own function with a single argument.
9. Save the file. 10. Open the file in a browser, and you should see 10000 in the browser.
•
The argument names in the introductory paragraph should appear in the order in which the arguments will be provided when the function is being called. The list of names essentially creates variables accessible only inside the function, and it is through these variables that you can access and work with the argument data provided when the function is called. To make effective use of functions, you need to be sensitive to the logic of your application. Functions are useful for encapsulating program logic that you will repeat multiple times. For instance, if you will be squaring numbers at several points in your script, you might want to consider a function for squaring numbers. If you do this in only one place, a function is not necessary.
58
Task
29
Part 1
Returning Values from Your Functions
I
n Task 28, you created a function that squares numbers and then outputs the result.
note
•
The value being returned can be a text string, a number, a variable that contains a value, or even a mathematical expression. Basically, anything that you could envisage assigning to a variable can be returned from a function.
The problem with this function is that it isn’t very practical. Instead of outputting the result of the operation, what you really want to do is return the result so that the result can be assigned to a variable or used in a mathematical expression. To do this, you use the return command as the last command in a function: function functionName() { some code return value; }
To illustrate this, the following task creates a function for squaring numbers that returns the result instead of outputting it. The function is then called, the result is stored in a variable, and then that variable is used to output the results: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the header of the document with opening and closing head tags:
3. Insert a script block in the header of the document: <script language=”JavaScript”>
4. Create a function named square that takes one argument named function square(number) { }
5. In the function, square the number and assign the results to a variable; then use return to return that result: var result = number * number; return result;
JavaScript Basics
59
6. Create the body of the document with opening and closing body tags:
Task
29
7. Insert a script block in the body of the document: <script language=”JavaScript”>
8. In the script block, call the square function, pass in a value of 10, and assign the results to the variable mySquare. Next, output that with document.write so that the final page looks like Listing 29-1. <script language=”JavaScript”> <script language=”JavaScript”>
Listing 29-1: Creating and calling your own function, which returns a result.
9. Save the file. 10. Open the file in a browser, and you should see 100 in the browser.
tip
•
To make effective use of functions, you need to be sensitive to the logic of your application. Functions are useful for encapsulating program logic that you will repeat multiple times. For instance, if you will be squaring numbers at several points in your script, you might want to consider a function for squaring numbers. If you do this in only one place, a function is not necessary.
60
Task
30
Part 1
Passing Multiple Parameters to Your Functions
I
n Tasks 28 and 29, you created functions that took single arguments. You also can create functions that take multiple arguments. To do so, you must specify names for each argument in the argument definition:
note
•
These names should be in the order in which the arguments will be provided when the function is being called. The list of names essentially creates variables accessible only inside the function, and it is through these variables that you can access and work with the argument data provided when the function is called.
function functionName(argumentName1,argumentName2,etc.) { Your function code goes here }
The following task creates a function that accepts two numeric arguments, multiplies them, and returns the result: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the header of the document with opening and closing head tags:
3. Insert a script block in the header of the document: <script language=”JavaScript”>
4. Create a function named multiple that takes two arguments named number1 and number2: function multiple(number1,number2) { }
5. In the function, multiply the numbers and assign the results to a variable; then use return to output that result: var result = number1 * number2; return result;
JavaScript Basics
61
6. Create the body of the document with opening and closing body tags.
Task
7. Insert a script block in the body of the document.
30
8. In the script block, call the multiply function and pass in the values 10 and 20; assign the result that is returned to a variable, and then output that variable so that the final page looks like Listing 30-1. <script language=”JavaScript”> <script language=”JavaScript”>
Listing 30-1: Creating and calling your own function with multiple arguments.
9. Save the file. 10. Open the file in a browser, and you should see 200 in the browser.
tip
•
To make effective use of functions, you need to be sensitive to the logic of your application. Functions are useful for encapsulating program logic that you will repeat multiple times. For instance, if you will be multiplying numbers at several points in your script, you might want to consider a function for squaring numbers (of course, JavaScript provides multiplication capabilities for you—this is just an example). If you do this in only one place, a function is not necessary.
62
Task
31
Part 1
Calling Functions from Tags
O
ne of the benefits of JavaScript is to be able to tie interactivity to elements of the HTML page. One way you can do this is to set up links in HTML that actually trigger calls to JavaScript functions when the link is clicked. There are two ways to do this:
notes
•
•
onClick is an event handler; this means it specified JavaScript code to execute when an event occurs. In this case, the event that must occur is the click event: The user must click on the link.
The question of which technique to use really depends on your circumstance and needs. For instance, with onClick you can also specify a URL to follow when the link is clicked so the JavaScript can be executed and then the link will be followed. You can’t do that with the javascript: URL approach.
1. Use the onClick attribute of the a tag to call the function: Link text
2. Use a javascript: URL in the href attribute of the a tag to call the function: Link text
The following task illustrates these two methods of calling a function from a link by creating a function that displays an alert dialog box to the user and then providing two separate links for the user to use to call the function: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the header of the document with opening and closing head tags:
3. Insert a script block in the header of the document: <script language=”JavaScript”>
4. Create a function named hello that takes no arguments: function hello() { }
5. In the function, use the window.alert method to display an alert dialog box: window.alert(“Hello”);
JavaScript Basics
63
6. Create the body of the document with opening and closing body tags.
Task
7. In the final page create two links that call the hello function using onClick and the javascript: URL techniques so that the final page looks like Listing 31-1.
8. Save the file. 9. Open the file in a browser, and you should see two links in the browser. 10. Click on either link and you should see a dialog box.
cross-reference
•
The process of creating functions is discussed in Tasks 27 to 30.
64
Task
32
Part 1
Calling Your JavaScript Code after the Page Has Loaded
S
ometimes you will want to execute JavaScript code only once the HTML page has fully loaded.
note
•
In Step 7 onLoad is an event handler; this means it specified JavaScript code to execute when an event occurs. In this case, the event that must occur is the completion of loading of the document.
Doing this requires two steps: 1. Place the code you want to execute after the page has completed loading into a function. 2. Use the onLoad attribute of the body tag to call the function. This results in code like the following: <script language=”JavaScript”> function functionName() { Code to execute when the page finishes loading } Body of the page
The following task creates a function that displays a welcome message in a dialog box and then only invokes that function once the page has completed loading: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the header of the document with opening and closing head tags. 3. Insert a script block in the header of the document: <script language=”JavaScript”>
JavaScript Basics
65
4. Create a function named hello that takes no arguments:
Task
function hello() {
32
}
5. In the function, use the window.alert method to display an alert dialog box: window.alert(“Hello”);
6. Create the body of the document with opening and closing body tags. 7. In the body tag, use the onLoad attribute to call the hello function:
8. In the body of the page, place any HTML or text that you want in the page so that the final page looks like Listing 32-1. <script language=”JavaScript”> The page’s content.
Listing 32-1: Using onLoad to call a function after the page loads.
9. Save the file. 10. Open the file in a browser, and you should see the page’s content, as well as the alert dialog box.
tip
•
You might want to wait for a page to load before executing your code, because your code relies on certain page elements being rendered or just because you don’t want a certain effect to occur too early.
66
Task
33
Part 1
Using for Loops
S
ometimes you will not want your code to proceed in a straight, linear fashion. In these situations you will want to make use of flow control techniques to adjust the way that the processing of your code proceeds. One such technique is looping, which allows you to specify that a section of code repeats one or more times before proceeding with the rest of your script. Typically, loops are created with a for statement:
for (conditions controlling the loop) command
The command, of course, can be a single command or multiple commands combined with curly brackets: for (conditions controlling the loop) { JavaScript command JavaScript command etc. }
Typically, for loops use an index variable to count, and on each iteration of the loop, the index variable’s value changes (usually incrementing) until the index variable reaches some limit value. For instance, the following loop counts from 1 to 10 using the variable i as the index variable: for (i = 1; i <= 10; i ++) { Code to execute in the loop }
Condition controlling the loop breaks down into three parts separated by semicolons: 1. The first part specifies the initial value of the index variable. This will be the value on the first iteration of the loop. 2. The second part specifies the condition that the index variable must meet for the next iteration of the loop to occur. Basically, this test occurs before each iteration of the loop, including the first. 3. The third part indicates how to change the value of the index variable at the end of each iteration of the loop. In this case, the index variable is incremented by one. Inside the body of the loop, the index variable is available and will contain the appropriate value for the current iteration.
JavaScript Basics
67
To illustrate this, the following steps use a for loop to count from 1 to 10 and display the numbers to the browser:
Task
33
1. Create a new HTML document in your preferred editor. 2. In the body of the document, create a script block. 3. In the script block, create a for loop: for () { }
4. Use the appropriate conditions to count from 1 to 10 in the loop, using i as the index variable: for (i = 1; i <= 10; i++) { }
5. In the loop, display the current value of the index variable followed by a br tag so each number displays in a separate line in the browser. The final page should look like Listing 33-1. <script> ”); } // -->
Listing 33-1: Using a for loop.
6. Save the file and close it.
cross-references
•
7. Open the file in a browser, and you should see the numbers 1 to 10 on separate lines.
•
Loop-based flow control, such as that created with a for loop, is not the only type of flow control. Another type of flow control is conditional branching, such as is illustrated in Task 34. The loops created with the for command are typically called index-based loops. Another form of looping is condition-based looping, which is discussed in Task 36.
68
Task
34
notes
•
•
The condition is any expression or value that evaluates down to true or false. Typically this means performing some type of comparison operation, such as testing equality (myVariable == “Hello”), testing magnitude (myVariable <= 20), or testing inequality (myVariable != 100). The window.confirm method returns true if the user clicks on OK and false if the user clicks on Cancel (see Step 4).
Part 1
Testing Conditions with if
A
s mentioned in the previous task, sometimes you will not want your code to proceed in a straight, linear fashion. In these situations you will want to make use of flow control techniques to adjust the way that processing of your code proceeds. One such technique is conditional branching looping, which allows you to specify that a certain section of code executes only when a certain condition exists. Conditional branching is performed with the if statement: if (condition) command
The command, of course, can be a single command or multiple commands combined with curly brackets: if (condition) { JavaScript command JavaScript command etc. }
To illustrate the effective use of if statements, the following presents a dialog box asking the user to click on OK or Cancel, and then tests the user’s response and displays an appropriate message in the browser window: 1. Create a new HTML document in your preferred editor. 2. In the body of the document, create a script block. 3. In the script block, use the window.confirm method to ask the user to click on OK or Cancel and to store the result in a variable named userChoice. var userChoice = window.confirm(“Choose OK or Æ Cancel”);
4. Create an if statement to test if the value of userChoice is true. If it is, the user has clicked on OK, and you need to display an appropriate message in the browser: if (userChoice == true) { document.write(“OK”); }
5. Create an if statement to test if the value of userChoice is false. If it is, the user has clicked on Cancel, and you need to display an
JavaScript Basics appropriate message in the browser. The final page should look like Listing 34-1.
69
Task
34
<script>
Listing 34-1: Using window.confirm.
6. Save the file and close it. 7. Open the file in a browser. You should see a confirmation dialog box like the one in Figure 34-1.
cross-reference
•
Figure 34-1: Letting the user choose between OK and Cancel.
8. Click on OK or Cancel, and an appropriate message should display in the browser window.
Refer to Task 26 for a discussion of the window. confirm method.
70
Task
35
Part 1
Using Short-Form Condition Testing
J
avaScript provides a short-form method of testing a condition and then returning a value based on that condition. It is useful when you want to assign a value to a variable: If a condition is true, it gets one value; otherwise, it gets another value.
note
•
The window.confirm method returns true if the user clicks on OK and false if the user clicks on Cancel.
This type of short-cut evaluation and assignment looks like the following: var myVar = (condition) ? value to assign if condition is true : Æ value to assign if condition is false;
The key syntactical components of this are as follows: • The condition must evaluate to true or false just like for an if statement (as mentioned in Task 34). • The question mark indicates this is short-form condition testing. • The colon separates the value to return if the condition is true from the value to return in a false condition. The value for true is always on the left of the colon. To illustrate effective use of short-form condition testing, the following presents a dialog box asking the user to click on OK or Cancel and stores the choice in a variable. Based on that a second variable is created with an output message dependant on the user’s choice; this is done with short-form testing. Finally, the message is displayed to the user. 1. Create a new HTML document in your preferred editor. 2. In the body of the document, create a script block. 3. In the script block, use the window.confirm method to ask the user to click on OK or Cancel and store the result in a variable named userChoice: var userChoice = window.confirm(“Choose OK or Æ Cancel”);
4. Use short-form condition testing on the value of userChoice to assign either “OK” or “Cancel” to a new variable called result: var result = (userChoice == true) ? “OK” : “Cancel”;
JavaScript Basics
71
5. Display the value of result so that the final page looks like Listing 35-1.
Task
35
<script>
Listing 35-1: Using short-form conditional testing.
6. Save the file and close it. 7. Open the file in a browser. You should see a confirmation dialog box. 8. Click on OK or Cancel, and an appropriate message should display in the browser window. Figure 35-1 shows the message that appears when the user clicks on Cancel.
cross-reference Figure 35-1: Clicking on Cancel.
•
You could achieve results identical to the introductory source code with an if statement (discussed in Task 34). This is just a more compact way to make a decision when assigning a value.
72
Task
36
Part 1
Looping on a Condition
I
n Task 33 you saw an example of a for loop; this loop was used for counting. Another useful type of loop is a conditional loop. The form of the loop is simple:
while (condition) command
notes
• •
A conditional loop continues as long as a single condition is true; once the condition becomes false, the loop ends. The condition must evaluate to true or false. Before each iteration of the loop, the condition is tested; if it is true, another iteration of the loop happens. Otherwise, the looping stops.
The command, of course, can be a single command or multiple commands combined with curly brackets so that you get the following: while (condition) { JavaScript command JavaScript command etc. }
This task illustrates this by repeatedly presenting a dialog box asking the user to click OK or Cancel until such a time as the user clicks on OK: 1. Create a new HTML document in your preferred editor. 2. In the body of the document, create a script block. 3. In the script block, use the window.confirm method to ask the user to click on OK or Cancel, and store the result in a variable named result: var result = window.confirm(“Choose OK or Cancel”);
4. Create a while loop: while () { }
5. As the condition for the loop, test if the user clicked on Cancel by comparing result to false: while (result == false) {
}
6. Inside the loop, call window.confirm again, and save the user’s selection in result: while (result == false) { result = window.confirm(“Choose OK or Cancel”); }
JavaScript Basics
73
7. After the loop, output a message indicating the user finally clicked on OK. The final page should look like Listing 36-1. <script>
Listing 36-1: Using a conditional loop.
8. Save the file and close it. 9. Open the file in a browser. You should see a confirmation dialog box. 10. The dialog box will keep reappearing until the user clicks on OK, and then a message will be displayed in the browser as illustrated in Figure 36-1.
Figure 36-1: Clicking on OK.
Task
36
74
Task
37
Part 1
Looping through an Array
T
ask 22 introduced the notion of an array: a set of numbered containers for storing values. Sometimes you will want to be able to loop through each element in the array. This can be done using a for loop so that the index variable of the loop matches one of the array indexes for each iteration through the loop. for loops were illustrated in Task 33.
notes
•
•
Notice that you start counting at 1. This is because the first index is 0 in any array. Similarly, you test for i being less than (not less than or equal to) the length of the array. This is because if the length of the array is 5, then the last index is 4. If you tested for being less than or equal to the length of the array, then the loop would count to 5 and not stop at 4 as it should. Notice in Step 6 the use of the variable i for the index of myArray in the loop. This works because i is being used to count through valid index values for the loop.
To do this, you want to be able to dynamically determine the length of the array so that you can set the conditions for the for loop. You do this with the length property of the array object. The following loop, for instance, loops through each of the indexes from the myArray array: for (i = 0; i < myArray.length; i++)
The following task creates an array and then loops through it to display each element of the array in the browser window: 1. Create a new HTML document in your preferred editor. 2. In the body of the document, create a script block: <script>
3. In the script block, create a new three-element array named myArray: var myArray = new Array(3);
4. Populate the elements of the array: myArray[0] = “Item 0”; myArray[1] = “Item 1”; myArray[2] = “Item 2”;
5. Create a for loop to loop through the array: for (i = 0; i < myArray.length; i++) { }
JavaScript Basics 6. In the loop, display the current element of the array to the browser window with document.write. The final page should look like Listing 37-1.
75
Task
37
<script> ”); } // -->
Listing 37-1: Looping through an array.
7. Save the file and close it. 8. Open the file in a browser, and a list of the elements should be displayed as in Figure 37-1.
cross-reference
•
Figure 37-1: Looping through an array to display its elements.
The document.write method, which is used to display output to the browser, is covered in Task 9.
76
Task
38
Part 1
Scheduling a Function for Future Execution
S note
•
The argument specifying the function to execute should be specified as a text string, and the string should include the complete call to the function including any arguments being passed to the function.
ometimes you will want to execute a function in an automated, scheduled way. JavaScript provides the ability to schedule execution of a function at a specified time in the future. When the appointed time arrives, the function automatically executes without any user intervention. Scheduling is done with the window.setTimeout method:
window.setTimeout(“function to execute”,schedule time);
The function to execute is specified as if you were calling the function normally but in a text string; the text string contains the actual text of the command to execute. The schedule time specifies the number of milliseconds to wait before executing the function. For instance, if you want to wait 10 seconds before executing the function, you need to specify 10000 milliseconds. To illustrate this, the following script creates a function that displays an alert dialog box and then schedules it to execute five second later: 1. Create a new HTML document in your preferred editor. 2. In the header of the document, create a script block: <script>
3. In the script block, create a function named hello that takes no arguments: <script>
JavaScript Basics 4. In the function, use window.alert to display a dialog box:
77
Task
<script>
5. After the function, schedule the function to execute five seconds in the future: <script>
6. Save the file and close it. 7. Open the file in a browser. Wait five seconds, and then an alert dialog box should appear, as in Figure 38-1.
cross-reference
•
Figure 38-1: Scheduling a function to execute.
The process of creating functions is discussed in Tasks 27 to 30.
78
Task
39
Part 1
Scheduling a Function for Recurring Execution
T
ask 38 showed you how to schedule a function for a single automatic execution in the future. But what if you wanted to schedule the same function to execute repeatedly at set intervals?
note
•
The alert dialog boxes will appear every five seconds indefinitely (see Step 8). To get out of this, simply close the browser window in one of the intervals between dialog boxes.
To do this, you need to do two things: • As the last command in the function, use window.setTimeout to reschedule the function execute again. • Use window.setTimeout outside the function to schedule initial execution of the function. The results look something like this: function functionName() { some JavaScript code window.setTimeout(“functionName()”,schedule time); } window.setTimeout(“functionName()”,schedule time);
To illustrate this, the following script creates a function that displays an alert dialog box and then schedules it to execute every five seconds: 1. Create a new HTML document in your preferred editor. 2. In the header of the document, create a script block. 3. In the script block, create a function named hello that takes no arguments: function hello() { }
4. In the function use window.alert to display a dialog box: function hello() { window.alert(“Hello”); }
5. Complete the function by using window.setTimeout to schedule the function to run every five seconds: function hello() { window.alert(“Hello”); window.setTimeout(“hello()”,5000); }
JavaScript Basics 6. After the function, schedule the function to execute five seconds in the future. The final page should look like Listing 39-1.
79
Task
39
<script>
Listing 39-1: Scheduling a function to execute.
7. Save the file and close it. 8. Open the file in a browser. Wait five seconds, and then an alert dialog box should appear, as in Figure 39-1. After you close the dialog box, another should reappear after five seconds. This should continue indefinitely.
cross-reference Figure 39-1: Scheduling a function to execute.
•
Task 25 discusses the use of the window.alert method to display dialog boxes.
80
Task
40
Part 1
Canceling a Scheduled Function
I
n Task 38 you saw how to schedule a function for future execution using window.setTimeout. Using a related method, window.clearTimeout, you can cancel a scheduled execution event before it occurs.
note
•
Just why would you want to cancel a scheduled function call? There are a number of reasons. For instance, you may want to use the scheduled function as a form of countdown. The user, for instance, may have a certain number of seconds to perform a task on the page before the page is cleared. You can schedule a function call to clear the page and then cancel it if the user performs the desired action.
When you create a scheduled event, the window.setTimeout method returns a pointer to that event. You can then use the pointer to cancel the scheduled event. You simply pass that pointer to window.clearTimeout: var pointer = window.setTimeout(...); window.clearTimeout(pointer);
The following task illustrates this by creating a function and scheduling it to execute five seconds after the page loads, but then immediately canceling that scheduled execution so that nothing happens: 1. Create a new HTML document in your preferred editor. 2. In the header of the document, create a script block: <script>
3. In the script block, create a function named hello that takes no arguments: function hello() { }
4. In the function use window.alert to display a dialog box: window.alert(“Hello”);
5. After the function, schedule the function to execute five seconds in the future, and save the pointer in a variable: var myTimeout = window.setTimeout(“hello()”,5000);
JavaScript Basics 6. Cancel the scheduled event so that the final page looks like Listing 40-1. <script>
Listing 40-1: Canceling a scheduled event.
7. Save the file and close it. 8. Open the file in a browser. Nothing should appear except a blank browser window, as in Figure 40-1.
Figure 40-1: Scheduling a function to execute and then canceling it.
81
Task
40
82
Task
41
Part 1
Adding Multiple Scripts to a Page
J
avaScript integrates into your HTML documents in a flexible way. In fact, there is nothing preventing you from having multiple script blocks wherever you need them in the header and body of your document. The script blocks will be processed by the browser in order with the rest of the HTML in the page. The following task illustrates two script blocks in a single document: 1. Create a new HTML document. 2. In the body of the document, create a script block: <script language=”JavaScript”>
3. In the script block, output some text with document.write: document.write(“The first script”);
4. After the script block, place some regular HTML code:
5. Create another script block: <script language=”JavaScript”>
6. In the second script block, output some more text so that the final page looks like Listing 41-1. 7. Save the file and close it.
JavaScript Basics
<script language=”JavaScript”>
tip
•
<script language=”JavaScript”>
You can actually include more than two script blocks in a page; there is no limit. The limits are practical more than anything else. Ideally, you want to group as much of your code together as possible in the header of your document in functions. Having lots of script blocks makes it harder to follow the logic of your application and debug and manage your code.
Listing 41-1: Multiple scripts in a page.
8. Open the file in a browser. You should see the results of both scripts, as illustrated in Figure 41-1.
Figure 41-1: Using multiple script blocks.
cross-reference
•
All scripts need to be contained in a script block. Task 1 introduces the creation and use of a script block.
84
Task
42
Part 1
Calling Your JavaScript Code after the Page Has Loaded
S
ometimes you will want to execute JavaScript code only when the user tries to leave your page. You might want to do this because you want to bid the user farewell or remind the user he or she is leaving your site.
note
•
onUnload is an event handler; this means it specified JavaScript code to execute when an event occurs. In this case, the event that must occur is the user navigating to another page.
Doing this requires two steps: • Place the code you want to execute after the page has completed loading into a function. • Use the onUnload attribute of the body tag to call the function. This results in code like the following: <script language=”JavaScript”> function functionName() { Code to execute when the page finishes loading } Body of the page
The following task creates a function that displays a goodbye message in a dialog box and then only invokes that function when the user leaves the page: 1. Open a new HTML document in your preferred HTML or text editor. 2. Create the header of the document with opening and closing head tags. 3. Insert a script block in the header of the document. 4. Create a function named bye that takes no arguments: function bye() { }
JavaScript Basics
85
5. In the function, use the window.alert method to display an alert dialog box: window.alert(“Farewell”);
6. Create the body of the document with opening and closing body tags. 7. In the body tag, use the onUnload attribute to call the bye function:
8. In the body of the page, place any HTML or text that you want in the page so that the final page looks like Listing 42-1. <script language=”JavaScript”> The page’s content.
Listing 42-1: Using onUnload to call a function after the user leaves a page.
9. Save the file. 10. Open the file in a browser, and you should see the page’s content. Navigate to another site and you should see the farewell dialog box.
Task
42
86
Task
43
Part 1
Check If Java Is Enabled with JavaScript
S note
•
Why might you want to test if Java is enabled in the browser? One reason would be if you plan to output HTML code to embed a Java applet in the browser: By testing first, you could output alternate HTML if the browser doesn’t support Java.
ometimes it is useful to know whether or not Java is enabled and to use that information in composing your pages. For instance, based on that information, you could dynamically adjust the content of your page to include or not include Java-based content.
Luckily, JavaScript provides a simple mechanism for determining this: the navigator.javaEnabled method. This method returns true if Java is enabled in the browser and false otherwise. The following task displays a message in the browser window indicating whether or not Java is enabled: 1. Create a new HTML document. 2. In the body of the document, create a script block: <script language=”JavaScript”>
3. In the script block, call navigator.javaEnabled and assign the results to a variable: <script language=”JavaScript”>
JavaScript Basics 4. Use document.write to display a relevant message to the user:
87
Task
<script language=”JavaScript”>
5. Save the file and close it. 6. Open the file in a browser. You should see an appropriate message based on the Java status in your browser. In Figure 43-1, Java is enabled.
Figure 43-1: Testing if Java is enabled.
cross-reference
•
As an example of a case where it might be useful to test if Java is enabled, see Task 243, which uses Java to obtain the IP address of the user’s computer.
Part 2: Outputting to the Browser Task 44:
Accessing the document Object
Task 45:
Outputting Dynamic HTML
Task 46:
Including New Lines in Output
Task 47:
Outputting the Date to the Browser
Task 48:
Outputting the Date and Time in a Selected Time Zone
Task 49:
Controlling the Format of Date Output
Task 50:
Customizing Output by the Time of Day
Task 51:
Generating a Monthly Calendar
Task 52:
Customizing Output Using URL Variables
Task 53:
Dynamically Generating a Menu
Task 54:
Replacing the Browser Document with a New Document
Task 55:
Redirecting the User to a New Page
Task 56:
Creating a “Page Loading ...” Placeholder
90
Task
44
note
•
The window.alert method takes a single string as an argument; the string should be the message you want to be displayed in the dialog box. In this case, the URL of the current document is what you want to display, and this has been placed in the myURL variable so you can just pass that variable as an argument to the method.
Part 2
Accessing the document Object
T
he document object is an extremely powerful and important object in JavaScript that allows you to output data to the browser’s document stream, as well as to access elements in the current document rendered in the browser. Using this object, you can generate dynamic output in your document, and you can manipulate the state of the document once rendered. The document object provides a lot of information, methods, and access to objects reflecting the current document, including the following: • Arrays containing anchors, applets, embedded objects, forms, layers, links, and plug-ins from the current document. • Properties providing information about the current page, including link colors, page background color, associated cookies, the domain of the page, the modification date, the referring document, the title, and the URL of the current document. • Methods to allow outputting text to the document stream, events to handle events, and an event to return text currently selected in the document.
The following example illustrates a simple use of the document object by displaying the domain of the current page in a dialog box: 1. Create a script block with opening and closing script tags: <script language=”JavaScript”>
2. Assign the current URL to a temporary variable called myURL with the following command: <script language=”JavaScript”> var myURL = document.URL;
Outputting to the Browser 3. Include the window.alert method to display a dialog box:
91
Task
<script language=”JavaScript”>
44
var myURL = document.URL; window.alert();
4. Pass the myURL variable to window.alert as its argument so that the final script looks like Listing 44-1. <script language=”JavaScript”> var myURL = document.URL; window.alert(myURL);
Listing 44-1: A script to display the current URL.
5. Save the script in an HTML file, and open the HTML in your browser. You should see a dialog box like Figure 44-1.
Figure 44-1: Displaying the current URL in a dialog box.
cross-references
• •
The creation of variables, including the appropriate selection of variable names, is discussed in Task 10. The window.alert method displays a dialog box with a single text message and a single button to dismiss the dialog box. This method is discussed in Task 25.
92
Task
45
Part 2
Outputting Dynamic HTML
W
henever you need to output dynamic HTML content into your document stream, you can do this using the document.write method. This method allows you to specify any text to be included in the document stream rendered by the browser.
notes
• •
In this task you see uses of concatenation. Concatenation is the act of combining one or more strings into one long string using the + operator. The document.write method takes a single argument. This argument must be a string. The concatenation operation used in Steps 4 and 5 evaluates down to a single string so the entire concatenation expression can be passed as an argument to document.write.
The concept is simple. Consider the following simple partial HTML document:
The following value is dynamic output from JavaScript:
<script language=”JavaScript”> document.write(“
<strong>Dynamic Content
”);
Thus ends the dynamic output example.
The result is that the browser will render output as if the following plain HTML source code had been sent to the browser:
The following value is dynamic output from JavaScript:
<strong>Dynamic Content
Thus ends the dynamic output example.
Using the document.write method, you can output any dynamic strings generated in HTML to the document stream. The following example outputs the referring page, the domain of the current document, and the URL of the current document using properties of the document object to obtain those values: 1. Start a script block with the script tag: <script language=”JavaScript”>
2. Display an introductory message using document.write: document.write(“
Here’s some information about this Æ document:
”);
3. Output a ul tag to start an unordered list: document.write(“
”);
4. Output the referring document as a list entry: document.write(“
Referring Document: “ + Æ document.referrer + “
”);
Outputting to the Browser
93
5. Output the domain of the current document as a list entry: document.write(“
Domain: “ + document.domain + Æ “
”);
Task
45
6. Output the URL of the current document as a list entry: document.write(“
URL: “ + document.URL + “
”);
7. Close the script by outputting a closing ul tag; the resulting script should look like Listing 45-1. <script language=”JavaScript”> document.write(“
Here’s some information about this Æ document:
”); document.write(“
”); document.write(“
Referring Document: “ + Æ document.referrer + “
”); document.write(“
Domain: “ + document.domain + Æ “
”); document.write(“
URL: “ + document.URL + “
”); document.write(“
”);
Listing 45-1: A script to dynamic information in the document stream.
8. Save the script in an HTML file, and open the file in a browser. The result should look like Figure 45-1.
cross-reference
•
Figure 45-1: Dynamic content displayed in the browser.
The document.write method is used to output content to the browser window from within your JavaScript script. The method is introduced in Task 9.
94
Task
46
Part 2
Including New Lines in Output
T
he document.write method is useful, but on occasion, it has limitations. In particular, the document.write method doesn’t output new-line characters at the end of each string it outputs. Consider the following JavaScript extract:
notes
•
•
Normally, the fact that document.write doesn’t output a new-line character doesn’t have much, if any, impact on your code. After all, new-line characters in standard HTML don’t actually get rendered in the browser. Still, this doesn’t mean that you can simply ignore the lack of new-line characters. In preformatted blocks of code, new-line characters are actually rendered as new-line characters. This means that if you expect that placing two output lines in document. write commands on separate lines will cause them to render on separate lines, you will be surprised by the results.
document.write(“<strong>a”); document.write(“b”);
In essence, this is the same as the following HTML code: <strong>ab
Notice that the “b” is on the same line as the “a”, although they are output in two document.write commands on separate lines of the JavaScript code. This means the output is displayed without a space between the letters, as in Figure 46-1. Figure 46-1: document.write does
not output new-line characters
Of course, this is a little different than if you had the HTML on two separate lines as: <strong>a b
In this case, the new line after the first line of code would be rendered as a space by the browser. This problem becomes more acute in blocks of preformatted text (text inside pre tags). To rectify the problem, the document object also offers the document .writeln method. This method is exactly the same as the document.write method, except that it outputs a new-line character to the browser at the end of the string. This means that the following code document.writeln(“<strong>a”); document.writeln(“b”);
is essentially the same as the following HTML code: <strong>a b
Outputting to the Browser
95
This is useful in situations where new lines are important and you want to ensure that a new line is output at the end of each line of text displayed through JavaScript.
Task
46
To illustrate the use of document.writeln, the following example is a variation of the example in Task 45, except that the data is output as preformatted text using the document.writeln method: 1. Start a script block with the script tag: <script language=”JavaScript”>
2. Display an introductory message using document.write: document.writeln(“
Here’s some information about this Æ document:
”);
3. Output a pre tag to start a section of preformatted text: document.writeln(“<pre>”);
4. Output the referring document: document.writeln(“ document.referrer);
Referring Document: “ + Æ
5. Output the domain of the current document: document.writeln(“
Domain: “ + document.domain);
6. Output the URL of the current document: document.writeln(“
URL: “ + document.URL);
7. Close the script by outputting a closing pre tag followed by a closing script tag: document.writeln(“”);
8. Save the script in an HTML file, and open the file in a browser. The result is as shown in Figure 46-2.
Figure 46-2: Dynamic content displayed in the browser in a preformatted text block.
tip
•
You need to be careful using document.write and document. writeln. In particular, if the string passed as an argument is contained in double quotes, then you can’t just include double quotes in the string. You would need to escape the double quote in the string as \”. If you don’t do this, the double quote will end the string and everything after it will not be considered part of the argument, causing JavaScript to generate an error message. The same applies if you enclose the string in single quotes: You need to escape single quotes in the string as \’.
96
Task
47
Part 2
Outputting the Date to the Browser
U
sing document.write and document.writeln becomes useful when there is a genuine need to display dynamic content in the browser that cannot be pregenerated but must be generated at the time the document is to be displayed.
notes
•
•
The Date method used here is known as a constructor method. Most objects have a constructor method that creates a new instance of the object. Here, using the Date constructor method with no arguments results in a Date object with the date set to the current date and time. The toString method of the Date object returns the current date and time in a standard format as a string. You don’t have any direct control of that formatting.
A good example of this is displaying the current date and time within a page. For instance, a site that delivers time-sensitive news probably wants people to know that the news on the site is up-to-date as of the current time and could do that by always displaying the current time in the page. Luckily, JavaScript provides a Date object with which you can quickly and easily obtain the current date and then output that date to the browser. Basic use of the Date object for these purposes is straightforward, and the following script can be inserted in an HTML file wherever you want to display the current date and time: 1. Start a script block with the script tag: <script language=”JavaScript”>
2. Create a new Date object and assign it to the variable thisDate: <script language=”JavaScript”> var thisDate = new Date();
3. Display the date using the toString method of the Date object: <script language=”JavaScript”> var thisDate = new Date(); document.write(thisDate.toString());
4. Close the script with a closing script tag; the final source code for this script should look like Listing 47-1. <script language=”JavaScript”> var thisDate = new Date(); document.write(thisDate.toString());
Listing 47-1: A script for displaying the current date.
Outputting to the Browser 5. Include this script anywhere in an HTML document that you want to display the current date. For instance, Listing 47-2 is a simple HTML document that includes the script; when displayed in the browser, this page looks like Figure 47-1.
The current date is: <script language=”JavaScript”> var thisDate = new Date(); document.write(thisDate.toString());
Listing 47-2: Including the script in the body of a document.
Figure 47-1: The date displayed in an HTML document.
97
Task
47
98
Task
48
Part 2
Outputting the Date and Time in a Selected Time Zone
U notes
•
•
By default, when you output the time, JavaScript uses the current local time and time zone of the browser for all its time generation and manipulation. This can cause problems, however. Consider, for instance, the case where you want to present information about whether your support desk is opened or closed. Ideally, you want to do this based on the time where your company is located and not the user’s time. However, you can’t predetermine the time zone the user will be in when you write your scripts. As an example of calculating the time zone offset, consider the following example: If the user is in Pacific Time in North America and is seven hours earlier than GMT, userOffset will be 7 and userOffset less myOffset will be 7 – (-2), or 9, which is the number of hours’ difference between Pacific Time and CET. Similarly, if the user is in Israel’s time zone, which is three hours later than GMT, then userOffset will be -3 and the difference will be -3 – (-2), or -1
sing Greenwich Mean Time (also known as Universal Time Coordinate) as a common starting point, you can create a script that will always be able to display the time in your time zone regardless of the time zone of the user’s computer. This is made possible because of two facts: • The Date object can tell you the offset of the user’s time zone from GMT time. So, if the user is five hours earlier than GMT, you can find this out. • You know your offset from GMT when you write your script. Combining these, you can always calculate the number of hours’ difference between your time zone and the user’s time zone and can adjust the time from the user’s time zone to yours before manipulating that data or displaying it for the user. Doing this requires the use of two methods of the Date object: • getTimezoneOffset: This method returns the number of minutes’ difference between the current browser’s time zone and GMT time. • setHours: This method is used to determine the hours part of the time in the current Date object. Using this you could reset the time to the time in your time zone. The following script displays the current time in Central European Time ( two hours later than Greenwich Mean Time). This will work regardless of the time zone of the user’s computer. 1. Start a script block with the script tag: <script language=”JavaScript”>
2. Set the time zone offset from GMT in the myOffset variable. This value should be the number of hours’ change needed to change the target time zone into GMT. For the case of Central European Time, which in the summer is two hours later than GMT, this means a value of -2 to indicate that it is necessary to move two hours back from CET to reach GMT: var myOffset = -2;
3. Create a new Date object with the current date and time, and assign it to the currentDate variable: var currentDate = new Date();
Outputting to the Browser
99
4. Use getTimezoneOffset to extract the offset for the user’s time zone; since this will be in minutes and this script is going to work in hours, this value should be divided by 60. The final value is stored in the userOffset variable:
Task
48
var userOffset = currentDate.getTimezoneOffset()/60;
5. Calculate the time zone difference between the target time zone and the user’s time zone, and assign the number of hours’ difference to the variable timeZoneDifference.: var timeZoneDifference = userOffset - myOffset;
6. Reset the hours part of the time using the setHours method. The new time should be the current hours (using getHours) plus the time zone difference. Luckily, using setHours like this will accommodate cases where the time zone difference pushes the date into the previous or next day and will adjust the date accordingly. currentDate.setHours(currentDate.getHours() + Æ timeZoneDifference);
7. Display the current date and time in the browser window with the document.write method: document.write(“The time and date in Central Europe is: Æ “ + currentDate.toLocaleString());
8. Close the script block with a closing script tag. The final script looks like Listing 48-1. <script language=”JavaScript”> var myOffset = -2; var currentDate = new Date(); var userOffset = currentDate.getTimezoneOffset()/60; var timeZoneDifference = userOffset - myOffset; currentDate.setHours(currentDate.getHours() + Æ timeZoneDifference); document.write(“The time and date in Central Europe is: Æ “ + currentDate.toLocaleString());
Listing 48-1: A script for displaying the date in another time zone.
9. Save the script in an HTML file and open that file in a browser to see the date and time in Central Europe displayed, as in Figure 48-1.
Figure 48-1: Displaying the date and time in Central Europe.
tip
•
To make this script in Listing 48-1 display the time and date in a time zone other than Central Europe, just change the value of myOffset appropriately.
100
Task
49
Part 2
Controlling the Format of Date Output
I
n addition to the toString method, the Date object also offers the following methods for quickly outputting the current date and time: • toGMTString: Returns the time as a string converted to Greenwich Mean Time. The results look like this:
notes
•
•
UTC stands for Coordinated Universal Time or Universal Time Coordinate. UTC is the same as Greenwich Mean Time but has become the preferred name for this default standard time zone. Using the JavaScript event model, you can run JavaScript code when a user clicks on an object. This is done using the onClick event handler. The onClick event handler is commonly used with form buttons and links, but you can apply it to other objects as well.
Thu, 17 Apr 2003 17:47:44 UTC
• toLocaleString: Returns the time as a string using the date formatting conventions of the current locale. The results look like this in Canada: April 17, 2003 10:47:44 AM
• toUTCString: Returns the time as a string converted to Universal Time. The results look like this in North America: Thu, 17 Apr 2003 17:47:44 UTC
In addition, the Date object has a series of methods to return specific information about the current date that you can then combine into a fully customizable presentation of the date and time: • getDate: Returns the current day of the month as a number • getDay : Returns the current day of the week as a number between 0 (Sunday) and 6 (Saturday) • getFullYear: Returns the four-digit year • getHours: Returns the hour from the current time as a number between 0 and 23 • getMinutes: Returns the minutes from the current time as a number between 0 and 59 • getMonth: Returns the current month as a number between 0 (January) and 11 (December) Using these methods, for instance, it is possible to output the current date in a custom form such as: 22:00 on 2003/4/15
The following code outputs the date in just this way: 1. Start a script block with the script tag: <script language=”JavaScript”>
2. Create a new Date object and assign it to the variable thisDate: var thisDate = new Date();
Outputting to the Browser
101
3. Build a string containing the time by using the getHours and getMinutes methods; this string is assigned to the variable thisTimeString: var thisTimeString = thisDate.getHours() + “:” + Æ thisDate.getMinutes();
4. Build a string containing the date by using the getFullYear, getMonth, and getDate methods; this string is assigned to the variable thisDateString: var thisDateString = thisDate.getFullYear() + “/” + Æ thisDate.getMonth() + “/” + thisDate.getDate();
5. Display the date and time to the browser using the document.write method: document.write(thisTimeString + “ on “ + thisDateString);
6. Close the script with a closing script tag. The final source code looks like Listing 49-1. <script language=”JavaScript”> var thisDate = new Date(); var thisTimeString = thisDate.getHours() + “:” + Æ thisDate.getMinutes(); var thisDateString = thisDate.getFullYear() + “/” + Æ thisDate.getMonth() + “/” + thisDate.getDate(); document.write(thisTimeString + “ on “ + thisDateString);
Listing 49-1: A script for displaying the current date in a custom format.
7. Include the script in an HTML document where you want to display the date, and then open that document in a Web browser. The date displays as shown in Figure 49-1.
Figure 49-1: The custom formatted date displayed in a Web browser.
Task
49
102
Task
50
Part 2
Customizing Output by the Time of Day
R
ather than just presenting this time information to the user and trusting the user not to attempt to use the chat application during the time in question, you can customize the output of the relevant support page based on the time of day so that a link to the chat application only appears during the appropriate hours of the day.
notes
•
•
Some sites will customize the output of their Web pages based on the current time of day. A common example of this is a site that offers live Web support in the form of some type of chat application. It is likely that this service will only be offered during certain hours of the day. The conditional expression in this if statement is quite complicated. It contains two boolean subexpressions that are joined by an AND operator. The first subexpression tests if the current date is a weekday; the second makes sure the time is between 9 A.M. and 5 P.M.
The following example is a script that could be included in such an application. Between 9 A.M. and 5 P.M. on weekdays, a link to the chat application is displayed to the user, but outside those hours, a notice indicating that live Web support is closed is presented. 1. Start a script block with the script tag: <script language=”JavaScript”>
2. Create a new Date object and assign it to a variable named thisDate: var thisDate = new Date();
3. Test the current date to see if it represents a weekday and is in the correct time range using an if statement (refer to Task 34 for an introduction to the if statement): if ((thisDate.getDate() >= 1 && thisDate.getDate() <= 6) Æ && (thisDate.getHours() >= 9 && thisDate.getHours() <= Æ 15)) {
4. Display the HTML for the case where the support desk is open: document.write(“The support desk is open. Click here for live Web support.”);
5. Use the else statement to provide an alternative action: } else {
6. Display HTML for the case where the support desk is closed: document.write(“The support desk is closed now. Come Æ back between 9 a.m. and 5 p.m. Monday to Friday.”);
7. Close the if block with a closing curly bracket: }
8. Close the script block with a closing script tag. The final code should look like the following: <script language=”JavaScript”> var thisDate = new Date();
Outputting to the Browser if ((thisDate.getDate() >= 1 && thisDate.getDate() <= Æ 6) && (thisDate.getHours() >= 9 && thisDate.getHours() Æ <= 15)) { document.write(“The support desk is open. Click here for live Web support.”); } else { document.write(“The support desk is closed now. Æ Come back between 9 a.m. and 5 p.m. Monday to Friday.”); }
9. Include this script in an HTML document, and open the document in a browser. Between 9 A.M. and 5 P.M. on weekdays, you should see the message shown in Figure 50-1. At other times you will see the message shown in Figure 50-2.
Figure 50-1: When the support desk is open, users can link to live Web support.
Figure 50-2: When the support desk is closed, users are told when to return.
103
Task
50
104
Task
51
Part 2
Generating a Monthly Calendar
I
t is simple to leverage the Date object, using looping (as discussed in Task 33) and the output capabilities of the document.write method to generate a calendar for the current month.
notes
•
•
• •
•
In many applications, you will want to display a monthly calendar. You might use this simply to display the current month so the user can type in the current date. You might choose to display event information inside the calendar. In any case, there is some basic JavaScript logic you can use to render a monthly calendar in a table without having to manually code the calendar for a specific month. The setDate method of the Date object is related to the getDate method. Where getDate returns the current day of the month as a number, the setDate method resets the day of the month; you provide the numeric value of the day of the month as an argument to the method. The day of the month is selected by using the value of the currentMonth variable as the index for the months array. If the first day of the month is not Sunday, then you need to display blank table cells for the days prior to the first day of the month in the first row of table dates in the table. To do this, make sure the current day is not a Sunday, and if it is not, loop from 0 to the day before the current day of the week and display an empty table cell for each day. The while loop should continue as long as the current date being processed is in the month being displayed (which is stored in the currentMonth variable).
Use the following steps to create a script to generate a calendar in a table in your documents: 1. In a script block, create an array containing the names of months: var months = new Array(); months[0] = “January”; months[1] = “Feburary”; months[2] = “March”; months[3] = “April”; months[4] = “May”; months[5] = “June”; months[6] = “July”; months[7] = “August”; months[8] = “September”; months[9] = “October”; months[10] = “November”; months[11] = “December”;
2. Create a new Date object for the current date, and store it in the currentDate variable. Take the month from the current date and store it in the currentMonth variable; then set the day of the month to the first day using the setDate method of the Date object: var currentDate = new Date(); var currentMonth = currentDate.getMonth(); currentDate.setDate(1);
3. Output the top of the table plus the first row, which contains the day of the month. The second row of the table, after the month name, should be column headers indicating the days of the week: document.write(“
”); document.write(“
”); document.write(“
” + Æ months[currentMonth] + “
”); document.write(“
”); document.write(“
S
”); document.write(“
M
”); document.write(“
T
”); document.write(“
W
”); document.write(“
T
”); document.write(“
F
”); document.write(“
S
”); document.write(“
”);
Outputting to the Browser 4. The next step is to handle the case where the first day of the month is not a Sunday. The result, for instance, is a first row of the table dates like the one illustrated in Figure 51-1, when the first day of the month falls on a Tuesday: if (currentDate.getDay() != 0) { document.write(“
”); for (i = 0; i < currentDate.getDay(); i++) { document.write(“
”); } }
105
Task
51
tip
•
Figure 51-1: Blank table cells may be needed to pad the first row of the month.
5. The next step is a while loop to display each day’s individual cell:
Since the getMonths method of the Date object returns 0 for January, 1 for February, and so on, January is placed at index 0 in the array, February at index 1, and so on up to the 11th place in the array, which holds December.
while (currentDate.getMonth() == currentMonth) {
6. Inside the loop, check if the current date is a Sunday, and if it is, then start a new row with a tr tag. Next, display a cell with the current date. If the current date is a Saturday, finish the row with a closing tr tag. Finally, add one to the value of the current day of the month using setDate to move to the next day. while (currentDate.getMonth() == currentMonth) { if (currentDate.getDay == 0) { document.write(“
”); } document.write(“
” + Æ currentDate.getDate() + “
”); if (currentDate.getDay() == 6) { document.write(“
7. After all the days have been displayed, you need to see if any more empty cells are necessary to complete the last row of the table. This is done with another for loop: for (i = currentDate.getDay(); i <= 6; i++) { document.write(“
”); }
8. Finally, close the table by outputting a closing table tag. When the script is executed, you will see the current month’s calendar displayed in your browser. document.write(“
”);
cross-reference
•
An array is a variable that contains one or more containers into which you can store individual values. Typically, these containers are numbered sequentially, starting with the first container, which is numbered zero. Arrays are introduced in Task 20.
106
Task
52
Part 2
Customizing Output Using URL Variables
W note
•
The logic of the code in this task is simple: Split the string at the question mark, take the part to the right of the question mark and split it at each ampersand, and then take each of the resulting substrings and split them at the equal sign to split the URL parameters between their name and value parts. Using the split method of the string object helps make this process easy.
hen you build a URL for a page, you can add a series of name-value pairs to the end of the URL in the following form:
Essentially, these parameters are like variables: named containers for values. In JavaScript, the document object provides the URL property that contains the entire URL for your document, and using some manipulation on this property, you can extract some or all of the URL parameters contained in the URL. The following code displays all URL parameters for the current document: 1. In a script block in the body of a document, separate the current document’s URL at the question mark and store the two parts in the array urlParts: var urlParts = document.URL.split(“?”);
2. Split the part of the URL to the right of the question mark into one or more parts at the ampersand. This places each name-value pair into an array entry in the parameterParts array. var parameterParts = urlParts[1].split(“&”);
3. Output the HTML code to set up a table and display column headers for the table using the document.write method: document.write(“
”); document.write(“
”); document.write(“
<strong>Name
Æ <strong>Value
”);
caution
•
The code in this task will only work properly if there is at least one URL parameter passed to the script. When doing this, keep a couple points in mind: First, you must access the file through a Web server and not open it as a local file, and second, you must include at least one namevalue pair after the question mark in the URL.
4. Start a for loop that loops through each element in the parameterParts array. This means the loop should start at 0 and count up to one less than the length of the array; this is because in an array of 10 elements, the first index is 0 and the last index is 9. for (i = 0; i < parameterParts.length; i ++) {
5. Output HTML to start a table row for each name-value pair: document.write(“
”);
6. Separate the name-value pair at the equal sign, and store the results in the pairParts array. The first entry (at index 0) contains the name of the pair, and the second entry (at index 1) contains the value of the entry: var pairParts = parameterParts[i].split(“=”);
Outputting to the Browser
107
7. Display the name and value in table cells. Make sure the value of the pair is unencoded with the unescape function:
Task
52
document.write(“
” + pairParts[0] + “
”); document.write(“
” + unescape(pairParts[1]) + “
”);
8. Output HTML to close the table row, and close the loop with a closing curly bracket: document.write(“
”);
tips
•
}
9. Output HTML to complete the table, and then close the script with a closing script tag. The final source code should look like Listing 52-1, and when viewed in the browser, if the URL has parameters, they will be displayed in a table like the one illustrated in Figure 52-1. <script language=”JavaScript”> var urlParts = document.URL.split(“?”); var parameterParts = urlParts[1].split(“&”); document.write(“
”); document.write(“
”); document.write(“
<strong>Name
Æ <strong>Value
”); for (i = 0; i < parameterParts.length; i ++) { document.write(“
”); var pairParts = parameterParts[i].split(“=”); document.write(“
” + pairParts[0] + “
”); document.write(“
” + unescape(pairParts[1]) + Æ “
”); document.write(“
”); } document.write(“
”);
Listing 52-1: A script to display URL parameters in a table.
Figure 52-1: Displaying URL parameters as name-value pairs in a table.
•
•
One of the powerful features of any dynamic programming language for Web pages, including JavaScript, is the ability to pass data between pages and then act on that data in the target pages. One of the most common ways to pass data between pages is to use URL parameters. Not all characters are valid in URLs. For instance, spaces are not allowed. To handle this, URL parameter values are escaped where these special characters are replaced with codes; for instance, spaces become %20. To really work with your URL parameters, you will want to unencode the values of each parameter to change these special codes back to the correct characters. The unescape function returns a string unencoded in this way. To separate the URL at the question mark, use the split method of the string object, which will return the part to the left of the question mark as the first entry (entry 0) in the array and the part to the right of the question mark that contains the URL parameters as the second entry in the array (entry 1).
108
Task
53
Part 2
Dynamically Generating a Menu
T
o illustrate some of the power of dynamic output combine with URL parameters, this task shows how to build a simple menu system. In this example, a single JavaScript page handles a menu of five choices and renders appropriate output for each of the five choices.
notes
•
•
•
The logic of the script is straightforward. Extract the choice parameter from the document’s URL. Next, display a menu of five choices; the choices should be clickable links, except for the current selected choice. Finally, display the content for the selected choice; if this is the first visit to the page, no choice is selected and no content other than the menu in the previous step should be displayed. To extract the choice URL parameter, simply extract the name and value into the variables pairName and pairValue. Check if pairName is the choice URL parameter, and if it is, assign the value of pairValue to the choice variable. For each menu entry you need to check if the variable choice indicates that selection. If it does, display the menu entry as regular text; otherwise, make a link back to the same page, with the URL parameter choice set appropriately.
This script assumes that the user’s current selection is passed to the script through the URL parameter named choice. The actual practical implementation is as follows; this code assumes the script is in a file called menu.html: 1. Start a script block with the script tag: <script language=”JavaScript”>
2. Create a variable called choice to hold the user’s selection; by default, the value is zero, which indicates no selection: var choice = 0;
3. Split the URL into the array urlParts at the question mark: var urlParts = document.URL.split(“?”);
4. Use the if statement to check if, in fact, there are any URL parameters. If there are, then the length of the urlParts array should be greater than 1: if (urlParts.length > 1) {
5. Split the list of URL parameters into their parts, and check if the pair is named choice; if it is, store the value of the pair in the choice array created earlier: var parameterParts = urlParts[1].split(“&”); for (i = 0; i < parameterParts.length; i++) { var pairParts = parameterParts[i].split(“=”); var pairName = pairParts[0]; var pairValue = pairParts[1]; if (pairName == “choice”) { choice = pairValue; } }
6. Close the if statement with a closing curly bracket: }
Outputting to the Browser 7. The next step is to display the menu itself. This requires five if statements: one for each menu entry. Each if statement looks like the following, adjusted for a particular choice and the appropriate output for that choice. The result is a menu that might look like Figure 53-1. if (choice == 1) { document.write(“<strong>Choice 1 ”); } else { document.write(“Æ Choice 1 ”); }
109
Task
53
tip
•
When working with JavaScript that manipulates URL parameters, you must be accessing the page through a Web server using a URL such as http:// my.url/test.html
and not directly using a local file path such as c:\myfiles\test. html. URL parameters are
not available with file path access to files.
Figure 53-1: The menu as displayed when no choice is selected.
8. Display a divider to separate the menu from the body text of the page using the document.write method: document.write(“”);
9. Use five if statements, which test the value of the choice variable to display the appropriate body content. Each if statement should look like the following but be adjusted for the appropriate choice value and output: if (choice == 1) { document.write(“Body content for choice 1”); }
10. Close the script with a closing script tag; when viewed in a browser, a page might look like Figure 53-2:
cross-reference
•
Figure 53-2: A completed page with Choice 3 selected.
Refer to Task 52 for a discussion of how to split a URL into its parts and extract the namevalue pairs of the URL parameters.
110
Task
54
Part 2
Replacing the Browser Document with a New Document
Y
ou can replace the browser document with a new document by using two main methods of the document object:
note
•
In addition to outputting content into the current document stream that the browser is rendering, you can also use the document object to replace the currently displayed object with new content without sending the user to the server for the new document.
• document.open: Opens a new document stream • document.close: Closes a document stream opened by document.open
To use these methods, you use a structure like the following: document.open(); One or more document.write or document.writeln commands document.close();
The following example creates a page with a JavaScript function that displays a new document using document.open and document.close. The user can click on a link to trigger the function and display the new page without accessing the server. 1. Start a script block with the script tag: <script language=”JavaScript”>
2. Start a new function called newDocument: function newDocument() {
3. Open a new document stream with document.open: document.open();
4. Write out the content of the new document: document.write(“
This is a New Document.
”);
5. Close the document stream with document.close: document.close();
6. Close the function with a closing curly bracket: }
7. Close the script with a closing script tag:
Outputting to the Browser
111
8. In the body of the HTML document, include a link with an onClick event handler that calls the newDocument function; a sample final page is shown in Listing 54-1.
Task
54
<script language=”JavaScript”> function newDocument() { document.open(); document.write(“
Listing 54-1: This code displays a second document stream to the browser.
9. Open the document in a browser. Initially you will see the body text of the HTML document as in Figure 54-1. After clicking on the link, you should see the content output by the newDocument function.
cross-reference
•
Figure 54-1: The original HTML page.
Event handlers are discussed in Part 9. The onClick event handlers are introduced in Task 220.
112
Task
55
Part 2
Redirecting the User to a New Page
U
nlike the document.URL property, which is static, the window.location property allows you to actually reset the location associated with a window and effectively redirect users to a new URL. For instance, consider the following simple page:
notes
•
•
The window object provides properties and methods for manipulating the current window. One of the properties is the location property, which contains the URL of the document displayed in the current window.
The onClick attribute takes as its value JavaScript code to execute when the user clicks on the button.
In this case, the text “You are here now” will not even display in the browser; as soon as the page loads, the user will immediately be directed to the Yahoo! Web site. The following script leverages the window.location property to allow users to enter the location they would like to visit in a form field and then takes them there when they click on the Go button: 1. Start a form with the form tag. This form will never be submitted anywhere, so it doesn’t actually need method or action attributes:
6. Store the form in an HTML file, and open that file in a Web browser. You will see a form. 7. Enter a URL in the form’s text field, as illustrated in Figure 55-1.
tip
•
In an event handler used for a form such as onClick, you can refer to the current form as this.form. That means this.form.url refers to the text field named url, and this.form.url. value refers to the text entered in the url text field.
Figure 55-1: Entering a URL in the form.
8. Click on the Go button, and you will be redirected to the URL you entered, as shown in Figure 55-2.
cross-reference
•
Figure 55-2: Redirecting to the new URL.
This task accesses data in forms and uses event handlers. Part 4 of the book addresses working with forms, while Part 9 discusses event handlers.
114
Task
56
Part 2
Creating a “Page Loading ...” Placeholder
T
his task looks at how to create a “page loading” placeholder that pops up in a separate window while the main document is loading. When the main document finishes loading, the placeholder window will close.
notes
•
•
Some sites create “page loading” placeholder pages. These are typically used when loading a page that will take a long time to load either because of the amount of content being loaded or, more commonly in the case of dynamic content, when processing the page for delivery to the user will take a long time. You can use a number of strategies for creating a “page loading” placeholder. Such strategies can involve content being pushed from the server, or they can be entirely implemented in JavaScript on the client. This task takes the latter approach.
This task uses two methods of the window object plus one event handler: • window.open: Opens a new window and loads a document in that window • window.close: Closes a window • onLoad: Used in the body tag to trigger JavaScript to execute when a document continues loading The following steps create the placeholder window: 1. Create an HTML file to serve as the content of the “page loading” placeholder window. Any content you want the user to see in that window should be placed in this file. Name the file holder.html. The following is a simple file that tells the user the main page is loading: Page Loading ... <strong> Page Loading ... Please Wait
2. Create the HTML file for your main document in the same directory. For this task, the file is named mainpage.html. A simple mainpage.html file might look like this: The Main Page
This is the main page
Outputting to the Browser 3. In mainpage.html, add a script block to the header of the document:
115
Task
56
<script language=”JavaScript”>
4. In the script block, open a new window with window.open. This method takes three arguments: the file to load in the window, the name of the window, and a series of parameters that define the features of the window—in this case, the width and height of the window are set to 200 pixels. The method returns a reference to the window’s objects so that it is possible to manipulate the window later. This reference is stored in the variable placeHolder: var placeHolder = window.open(“holder.html”,”Æ holderWindow,”width=200,height=200”);
5. Add an onLoad attribute to the body tag:
6. As the value of the onLoad attribute, use placeHolder.close(). This closes the placeholder window once the main document finishes loading. The final mainpage.html code looks like Listing 56-1. <script language=”JavaScript”> var placeHolder = Æ window.open(“holder.html”,”placeholder”,”width=200,Æ height=200”); The Main Page
This is the main page
Listing 56-1: Integrating the placeholder code into an HTML document.
7. Make sure holder.html and mainpage.html are in the same directory and then load mainpage.html in your browser window. A window with the contents of holder.html should appear above the main window and then disappear as soon as the main window finishes loading.
tip
•
This type of placeholder doesn’t make much sense for a document as short as mainpage.html. In this case, the placeholder will appear and disappear almost immediately. You really need a long, complicated HTML document or a dynamic document that takes time to generate to make this type of placeholder worthwhile.
Part 3: Images and Rollovers Task 57:
Accessing an HTML-Embedded Image in JavaScript
Task 58:
Loading an Image Using JavaScript
Task 59:
Detecting MouseOver Events on Images
Task 60:
Detecting Click Events on Images
Task 61:
Switching an Image Programatically
Task 62:
Using Multiple Rollovers in One Page
Task 63:
Displaying a Random Image
Task 64:
Displaying Multiple Random Images
Task 65:
Using a Function to Create a Rollover
Task 66:
Using a Function to Trigger a Rollover
Task 67:
Using Functions to Create Multiple Rollovers in One Page
Task 68:
Creating a Simple Rollover Menu System
Task 69:
Creating a Slide Show in JavaScript
Task 70:
Randomizing Your Slide Show
Task 71:
Triggering Slide Show Transitions from Links
Task 72:
Including Captions in a Slide Show
Task 73:
Testing if an Image Is Loaded
Task 74:
Triggering a Rollover in a Different Location with a Link
Task 75:
Using Image Maps and Rollovers Together
Task 76:
Generating Animated Banners in JavaScript
Task 77:
Displaying a Random Banner Ad
118
Task
57
Part 3
Accessing an HTML-Embedded Image in JavaScript
J note
•
The images array contains one entry for image in the order in which the images are specified in your code. Therefore, the first image’s object is document. images[0], the second is document.images[1], and so on.
avaScript makes it easy to access and manipulate images in your HTML pages. Accessing images in JavaScript is done through the Image object. An Image object is created for each image you include in your HTML code. You either access these Image objects through the images array of the document object or directly by name. If you specify a name for an image using the name attribute of the img tag, then you can directly refer to the image as document.imageName. For example, consider the following image in your HTML document:
You could refer to this in JavaScript with document.myImage. Each Image object has numerous properties that can be used to access information about an image. These include height (the height of the image in pixels), width (the width of the image in pixels), src (the value of the src attribute of the img tag), hspace (the size of horizontal image padding in pixels), and vspace (the size of vertical image padding in pixels). The following task illustrates how to use these properties to display an image and then provide links to display the height and width of the image in dialog boxes: 1. Use an img tag to include an image in the page; name the image myImage using the name attribute:
2. Include a link for displaying the width, and add an onClick event handler to the a tag; this event handler will use the window.alert method to display the image’s width in a dialog box. Notice how the image’s width is obtained by referring to document.myImage .width: Width
3. Include a link for displaying the height, and add an onClick event handler to the a tag; this event handler will use the window.alert method to display the image’s height in a dialog box. Notice how the image’s height is obtained by referring to document.myImage .height. Add any necessary HTML for your preferred layout, and your final code might look something like the following: Width
4. Save the code in an HTML file, and open it in a Web browser; you should see a page with links for displaying the width and height.
57
5. Click on the Width link, and the dialog box in Figure 57-1 appears.
tip
•
By using JavaScript’s ability to manipulate images, you can achieve many different effects. These include dynamically changing images on the fly to create a slide show, creating mouse rollover effects on images, and even generating animated images or banners using JavaScript.
Figure 57-1: Displaying an image’s width.
6. Click on the Height link, and the dialog box in Figure 57-2 appears.
cross-reference Figure 57-2: Displaying an image’s height.
•
The window.alert method (see Step 2) displays a dialog box with a single text message and a single button to dismiss the dialog box. It takes a single string as an argument, which should be the message to be displayed in the dialog box. This method is discussed in Task 25.
120
Task
58
Part 3
Loading an Image Using JavaScript
I
n addition to creating Image objects by loading an image in HTML, you can create an Image object programmatically in JavaScript. Loading an image in JavaScript is a two-step process: 1. Create an Image object and assign it to a variable: var myImage = new Image;
2. Assign a source image URL to the src attribute of the object: myImage.src = “image URL goes here”;
The following task illustrates the programmatic loading of an image by loading an image in this way and then providing links to display the height and width of the image in dialog boxes as in Task 57: 1. Create a script block with opening and closing script tags. 2. In the script, create a new Image object named myImage: myImage = new Image;
3. Load the image by assigning its URL to the src attribute of myImage: myImage.src = “image1.jpg”;
4. In the body of the page’s HTML, include a link for displaying the width and add an onClick event handler to the a tag; this event handler will use the window.alert method to display the image’s width in a dialog box. The image’s width is obtained by referring to document.myImage.width: Width
caution
•
As mentioned in Task 57, the images array contains one entry for image in the order in which the images are specified in your code. Therefore, the first image’s object is document. images[0], the second is document.images[1], and so on. This only applies to images in your HTML document. Image objects created in JavaScript as shown in this task do not appear in the images array.
5. Include a link for displaying the height, and add an onClick event handler to the a tag; this event handler will use the window.alert method to display the image’s height in a dialog box. The image’s width is obtained by referring to document.myImage.height. The final page should look like the following: <script language=”JavaScript”> myImage = new Image; myImage.src = “Tellers1.jpg”;
6. Save the code in an HTML file, and open the file in your browser; the page with two links should appear, but the image itself won’t be displayed, as shown in Figure 58-1.
121
Task
58
tip
•
You could create an Image object in JavaScript when you want to load an image without displaying it and then use that image later in your scripts. As an example, you might use the image in a slide show or as the rollover image when the mouse moves over an image.
Figure 58-1: Displaying Width and Height links.
7. Click on the Width link, and a dialog box like the one in Figure 58-2 appears, showing the width of the image. Click on the Height link, and a dialog box for displaying the image’s height appears.
cross-reference
•
Figure 58-2: Displaying an image’s width.
Task 57 discusses the loading of images in HTML and then accessing those images from JavaScript.
122
Task
59
Part 3
Detecting MouseOver Events on Images
U
sing the onMouseOver event handler, you can detect when the mouse pointer is over an image. You can then trigger actions to occur only when the mouse moves into the space occupied by the image. Typically, this is used to create rollover effects, as shown in the following tasks.
notes
•
•
•
In this example, the JavaScript code is executed when the mouse pointer moves over anything inside the opening and closing a tags; in this case, only the image is inside the a block. The onMouseOver event is often used for rollover effects. If you are using an images as a menu button and want to display an alternate highlight image when the mouse is over the button, you will use onMouseOver. In these cases, the image will be part of a link and you will use onMouseOver in the a tag. This is the most common way the onMouseOver event is used, and it is rarely used in the img tag itself. The onMouseOver event is available in the a tag on any JavaScript-capable browser but is only available for the img tag in newer browsers (Netscape 6 and above or Internet Explorer 4 and above).
To specify an event handler, you need to use the onMouseOver attribute of the img tag to specify JavaScript to execute when the mouse rolls over the image. For example:
In the case where you are using an image as a link—for instance, an image serving as a button in a menu—you typically place the onMouseOver attribute in the a tag that encompasses the img tag:
The following shows the use of onMouseOver in both the img and a tags and causes an appropriate message to display in a dialog box when the mouse pointer moves over an image: 1. In the body of your document, place an img tag to display the first image:
2. Add an onMouseOver attribute to the img tag:
3. As the value for the onMouseOver attribute, use the window.alert method to display a message when the mouse pointer moves over the image:
4. Add a second img tag to display another image:
5. Place opening and closing a tags around the second image; no URL needs to be specified, and you should add an onMouseOver attribute to the a tag. As the value for the onMouseOver attribute, use the window.alert method again to display a message when the mouse pointer moves over the second image. The resulting code should look like this:
Images and Rollovers
6. Save the code to an HTML file, and open the file in a browser. The page will look like Figure 59-1.
Figure 59-1: Displaying two images.
7. Move the mouse pointer over the first image, and a dialog box like Figure 59-2 appears. Move the mouse over the send image, and a dialog box indicating you are over the link appears.
Figure 59-2: Displaying a dialog box when the mouse moves over an image.
123
Task
59
124
Task
60
Part 3
Detecting Click Events on Images
I
n much the same way as code can be specified to respond to onMouseOver events (see Task 59), you can specify action to take only when the user clicks on an image. This is done with the onClick event handler of the img tag or the a tag, depending on the situation.
notes
•
•
In this example, the JavaScript code is executed when the mouse pointer clicks on anything inside the opening and closing a tags; in this case, only the image is inside the a block. The onClick event is available in the a tag on any JavaScript-capable browser but is only available for the img tag in newer browsers (Netscape 6 and above or Internet Explorer 4 and above).
You can specify an onClick attribute of the img tag:
In the case where you are using an image as a link, as in an image serving as a button in a menu, you typically place the onClick attribute in the a tag that encompasses the img tag:
The following shows the use of onClick in both the img and a tags and causes an appropriate message to display in a dialog box when the mouse clicks on an image: 1. In the body of your document, place an img tag to display the first image:
2. Add an onClick attribute to the img tag:
3. As the value for the onClick attribute, use the window.alert method to display a message when the mouse pointer moves over the image:
4. Add a second img tag to display another image:
5. Place opening and closing a tags around the second image; no URL needs to be specified, and you should add an onClick attribute to the a tag. As the value for the onClick attribute, use the window.alert method again to display a message when the mouse pointer moves over the second image. The resulting code should look like this:
Images and Rollovers
6. Save the code to an HTML file, and open the file in a browser. The page will look like Figure 60-1.
Figure 60-1: Displaying two images.
7. Click on the first image, and a dialog box indicating you clicked on the image without the link appears. 8. Click on the second image, and a dialog box like Figure 60-2 appears.
Figure 60-2: Displaying a dialog box when the mouse clicks on an image link.
125
Task
60
126
Task
61
Part 3
Switching an Image Programatically
T
his task illustrates how to combine the JavaScript-based loading of images with the onMouseOver event handler to create a rollover effect. This rollover effect is typically used in the context of image-based buttons, as well as menus containing menu items built out of images.
notes
•
•
In producing these rollover effects, keep in mind that an image and its alternate rollover image should usually have the same width and height in terms of the number of pixels. Otherwise, one of two problems arises. First, if you don’t force images to a specific size using the width and height attributes of the img tag, then the space taken by the image can change as the mouse rolls over the image, causing elements on the page around the image to move. Second, if you force the image to a specific size, one of the two images will need to be distorted to match the size of the other image. The onMouseOver event handler is similar to the onMouseOut event handler. It allows the programmer to specify JavaScript code to execute when the mouse pointer leaves the area occupied by a page element such as an image where onMouseOver specified code to execute when the mouse pointer entered the space occupied by a page element.
Consider Figure 61-1. Here a single image is displayed in a Web page and the mouse pointer is not over the image. When the mouse pointer moves over the image, a rollover image replaces the original image, as in Figure 61-2. When the mouse pointer moves off the image, the image returns to the original illustrated in Figure 61-1.
Figure 61-1: When the mouse pointer is not over an image, the original image is
displayed.
Figure 61-2: When the mouse pointer is over an image, an alternate image is
displayed. The principle of producing rollover effects in JavaScript is straightforward and involves three key pieces: • Specify the default image in your img tag. • Create two Image objects; in one load the default image, and in the other load the rollover image. • Specify onMouseOver and onMouseOut event handlers to manage changing the displayed image as the mouse moves onto the image or off the image.
Images and Rollovers
127
The following steps outline how to create a simple rollover effect for a single image in a page:
Task
61
1. In the header of your page, create a script block with opening and closing script tags. 2. In the script, create an Image object named rollImage, and load the alternate, rollover image into it by assigning the image to the src property of the rollImage object: rollImage = new Image; rollImage.src = “rollImage1.jpg”;
3. In the script, create an Image object named defaultImage, and load the default image to display into it. 4. In the body of your script, place the default image with an img tag. Use attributes of the tag to control the size and border of the image as desired, and use the name attribute to assign the name myImage to the image. 5. Wrap the img tag in opening and closing a tags, and specify the URL where you want users to be directed when they click on the image in the href attribute of the a tag. Add an onMouseOver attribute to the a tag, and use this to display the rollover image to the myImage object. This will cause the rollover image to be displayed when the mouse moves over the image. Also add an onMouseOut attribute to the a tag, and use this to display the default image when the mouse moves off the image. The final script should look like this: <script language=”JavaScript”> rollImage = new Image; rollImage.src = “rollImage1.jpg”; defaultImage = new Image; defaultImage.src = “image1.jpg”;
7. Save the code in an HTML file, and load it in a browser. When the mouse rolls over the image, the rollover effect should replace it with the rollover image and then switch it back to the default image when the mouse pointer leaves the space occupied by the image.
tip
•
The rollover effect is designed to provide context to users, allowing them to know that the image constitutes a clickable element and showing users exactly what they are clicking on (especially in the case of numerous images in close proximity to each other in a complex layout).
128
Task
62
Part 3
Using Multiple Rollovers in One Page
B
uilding on the rollover effect illustrated in Task 61, this task shows how the principle can be extended to support multiple rollovers in a single page. This is useful when you are building a menu out of rollover images. The following steps illustrate the creation of two rollover images on a single page:
notes
•
•
•
In their most basic form, multiple rollover effects require that each image have a unique name, each default image have a uniquely named Image object, and each rollover image have a uniquely named Image object. The onMouseOver event handler is similar to the onMouseOut event handler. It allows the programmer to specify JavaScript code to execute when the mouse pointer leaves the area occupied by a page element such as an image where onMouseOver specified code to execute when the mouse pointer entered the space occupied by a page element (see Step 4). In producing these rollover effects, keep in mind that an image and its alternate rollover image should usually have the same width and height in terms of the number of pixels; otherwise, one of two problems arises. First, if you don’t force images to a specific size using the width and height attributes of the img tag, then the space taken by the image can change as the mouse rolls over the image, causing elements on the page around the image to move. Second, if you force the image to a specific size, one the two images will need to be distorted to match the size of the other image (see Figures).
1. In a script block in the header of a new page, create an Image object named rollImage1, and load the alternate rollover image for the first image into it by assigning the image to the src property of the rollImage1 object. Also create an Image object named defaultImage1, and load the default image for the first image into it by assigning the image to the src property of the defaultImage1 object: rollImage1 = new Image; rollImage1.src = “rollImage1.jpg”; defaultImage1 = new Image; defaultImage1.src = Æ “image1.jpg”;
2. Repeat the process for the second image by creating and loading rollImage2 and defaultImage2 so that the resulting script is as follows: rollImage2 = new Image; rollImage2.src = “rollImage2.jpg”; defaultImage2 = new Image; defaultImage2.src = Æ “image2.jpg”;
3. In the body of your script, place the two default images with img tags; use attributes of the tags to control the size and border of the image as desired, and use the name attribute to assign the names myImage1 and myImage2 to the images:
4. Wrap each img tag in opening and closing a tags, and specify the URL where you want the users to be directed when they click on the image in the href attribute of the a tag. Add an onMouseOver attribute to each a tag, and use this to display the rollover images. This will cause the rollover image to be displayed when the mouse moves over the relevant image. Also add an onMouseOut attribute to each a tag, and use this to display the default image when the mouse moves off the relevant image. The final script should look like this: <script language=”JavaScript”> rollImage1 = new Image; rollImage1.src = Æ “Tellers1.jpg”; defaultImage1 = new Image; defaultImage1.src = Æ “lotus.jpg”; rollImage2 = new Image; rollImage2.src = “hedi.jpg”;
Images and Rollovers defaultImage2 = new Image; defaultImage2.src = Æ “ArcRV1.1.jpg”;
5. Save the code in an HTML file and load it in a browser. Two possible states exist: when the mouse is not over an image (Figure 62-1) and when the mouse is over the first image (Figure 62-2).
Figure 62-1: The mouse is not over any image.
Figure 62-2: The mouse is over the first image.
129
Task
62
130
Task
63
Part 3
Displaying a Random Image
O
ne application of the combination of JavaScript and images is to load a random image in a location on the page rather than the same image every time. One approach to this is to display the image entirely using JavaScript. That is, you need to use JavaScript to specify a list of possible images, select one at random, and then generate the img tag to display that image.
notes
• • •
•
•
Each slot in an array is numbered; numbering starts at zero. This means an array with four entries has entries numbered 0 to 3. The Math object provides a number of useful methods for working with numbers and mathematical operations. The length property of an Array object provides the number of entries in an array. That means if an array has four entries numbered 0 to 3, then the length property of that array has a value of 4. Math.floor performs a
function similar to rounding in that it removes the decimal part of a number. The difference is that the result of rounding can be the next highest or next lowest integer value, depending on the size of the decimal portion of the number. With Math.floor the result is always the next lowest integer. Therefore, rounding 2.999 would result in the integer 3, but applying Math.floor to the same number would result in the integer 2. Notice how the img tag is built out of two strings combined with an array variable; the combining is done with plus signs. When you are working with string values, plus signs perform concatenation of strings, as discussed in Task 15. Concatenation means that “ab” + “cd” results in “abcd”.
The script created in the following steps illustrates this process: 1. Create a script block with opening and closing script tags; the script block should be in the body of your HTML document where you want the image to be displayed: <script language=”JavaScript”>
2. In the script, create an array named imageList: var imageList = new Array;
3. Create an entry in the array for each image you want to make available for random selection. For instance, if you have four images, assign the path and names of those images to the first four entries in the array: imageList[0] imageList[1] imageList[2] imageList[3]
4. Create a variable named imageChoice: var imageChoice;
5. Assign a random number to imageChoice using the Math.random method, which returns a random number from 0 to 1 (that is, the number will be greater than or equal to 0 but less than 1): var imageChoice = Math.random();
6. Extend the expression assigned to imageChoice by multiplying the random number by the number of entries in the imageList array to produce a number greater than or equal to 0 but less than 4: var imageChoice = Math.random() * imageList.length;
7. Extend the expression assigned to imageChoice further by removing any part after the decimal point with the Math.floor method; the result is an integer from 0 to one less than the number of entries in the array—in this case that means an integer from 0 to 3: var imageChoice = Math.floor(Math.random() * Æ imageList.length);
Images and Rollovers 8. Use the document.write method to place an img tag in the HTML data stream sent to the browser. As the value of the src attribute of img tag, the random image is specified as imageList[imageChoice]. The final script looks like this:
131
Task
63
<script language=”JavaScript”> var imageList = new Array; imageList[0] = “image1.jpg”; imageList[1] = “image2.jpg”; imageList[2] = “image3.jpg”; imageList[3] = “image4.jpg”; var imageChoice = Math.floor(Math.random() * Æ imageList.length); document.write(‘’);
9. Save the code in an HTML file, and display the file in a browser. A random image is displayed, as in Figure 63-1. Reloading the file should result in a different image, as illustrated in Figure 63-2 (although there is always a small chance the same random number will be selected twice in a row).
Figure 63-1: Displaying a random image.
cross-references
• •
Figure 63-2: Reloading the page will usually result in a different random image.
An array is a data type that contains multiple, numbered slots into which you can place any value. See Task 20. for a discussion of arrays. The document.write method is introduced in Task 45. It allows JavaScript code to generate output that forms part of the HTML rendered by the browser.
132
Task
64
Part 3
Displaying Multiple Random Images
T
he process of displaying a random image in a Web page can easily be extended to displaying multiple random images out of the same set of random images. The result is a script like the following, which displays three random images:
notes
•
•
Displaying multiple random images requires some rethinking of the script. Two script blocks are now needed: a script block in the document header that defines the array of images available and a function for displaying a single random image, along with a script block in the body of the text wherever a random image needs to be displayed. This separation of scripts, as well as the addition of a function, makes the code much more general-purpose than the code illustrated in Task 63. Math.floor performs a
function similar to rounding in that it removes the decimal part of a number. The difference is that the result of rounding can be the next highest or next lowest integer value, depending on the size of the decimal portion of the number. With Math.floor the result is always the next lowest integer. Therefore, rounding 2.999 would result in the integer 3, but applying Math.floor to the same number would result in the integer 2.
1. In a script block in the header of a new document, create an array named imageList: var imageList = new Array;
2. Create an entry in the array for each image you want to make available for random selection. For instance, the following specifies the path to four images: imageList[0] imageList[1] imageList[2] imageList[3]
3. Create a function called showImage with the function keyword: function showImage() { }
4. In the function, create a variable named imageChoice. Assign a random number to imageChoice using the Math.random method, which returns a random number from 0 to 1 (that is, the number will be greater than or equal to 0 but less than 1). Extend the expression assigned to imageChoice by multiplying the random number by the number of entries in the imageList array to produce a number greater than or equal to zero but less than 4: var imageChoice = Math.random() * imageList.length;
5. Extend the expression assigned to imageChoice further by removing any part after the decimal point with the Math.floor method. The result is an integer from 0 to one less than the number of entries in the array—in this case that means an integer from 0 to 3: var imageChoice = Math.floor(Math.random() * Æ imageList.length);
6. Use the document.write method to place an img tag in the HTML data stream sent to the browser. As the value of the src attribute of img tag, the random image is specified as imageList[imageChoice]. The final function looks like this: function showImage() { var imageChoice = Math.floor(Math.random() * Æ imageList.length); document.write(‘’); }
Images and Rollovers 7. In the body of the document, create a script block wherever you want to place a random image, and then invoke the showImage function there. You can invoke multiple showImage functions in the same script block. The following page shows how to display three random images in a row. Typically, the results will look like Figure 64-1. Depending on how many images are available in your array and how many random images you are displaying, there is always a chance that you will see repeat images as in Figure 64-2.
133
Task
64
<script language=”JavaScript”> var imageList = new Array; imageList[0] = “Tellers1.jpg”; imageList[1] = “lotus.jpg”; imageList[2] = “hedi.jpg”; imageList[3] = “ArcRV1.1.jpg”; function showImage() { var imageChoice = Math.floor(Math.random() * Æ imageList.length); document.write(‘’); } <script language=”JavaScript”> showImage(); showImage(); showImage();
cross-reference
•
Figure 64-1: Displaying three random images.
Figure 64-2: Images may repeat.
An array is a data type that contains multiple, numbered slots into which you can place any value. See Task 20 for a discussion of arrays.
134
Task
65
Part 3
Using a Function to Create a Rollover
T
his task shows how to encapsulate the creation of Image objects for a rollover image into a function. The following steps show how to create the necessary function and use it to create a rollover effect for an image:
notes
•
• •
The task of code creation, code management, and code accuracy becomes increasingly daunting as the number of rollover images in a document increases. At some point the task of ensuring bug-free code and debugging becomes problematic. The approach in this task is aimed at mitigating this to a degree. Tasks 67 and 68 show how to combine these functions into a single system. Array elements can contain simple data types, such as numbers or strings, or complex data types, such as objects. When an array entry contains an object, the properties of that object are referred to with the notation arrayName- [index] .propertyName.
•
•
The basis of the technique used here is to create an array of Image objects for each rollover image; each array will have two entries: one containing the Image object for the default image and the other containing the Image object for the replacement image. This combines related Image objects into a single variable (which contains the array) that can be easily accessed and referred to in a consistent way. When then mouse moves over the image, rollImage1[replacement] contains the appropriate Image object, while rollImage1 [source] contains the Image object for when the
mouse is not over the image.
1. In the header of the document, create a script block with opening and closing script tags: <script language=”JavaScript”>
2. In the script, create two variables: a source and a replacement containing the values 0 and 1, respectively. These variables allow the Image objects of each rollover array to be referred to by name: source for the default image and replacement for the rollover image. var source = 0; var replacement = 1;
3. Create a function named createRollOver with the function keyword. This function should take two parameters—originalImage, containing the path and name of the default image, and replacementImage, containing the path and name of the rollover image: function createRollOver(originalImage,replacementImage) { }
4. In the function, create an array named imageArray: var imageArray = new Array;
5. Create a new Image object in the first element of the array, using source to specify the index, and assign originalImage as the source of that image: imageArray[source] = new Image; imageArray[source].src = originalImage;
6. Create a new Image object in the second element of the array, using replacement to specify the index, and assign replacementImage as the source of that image: imageArray[replacement] = new Image; imageArray[replacement].src = replacementImage;
7. Return the array as the value returned by the function: return imageArray;
Images and Rollovers 8. After the function, invoke the createRollOver function to create the necessary rollover array, and assign the array returned by the function to rollImage1. The final script looks like this:
135
Task
65
<script language=”JavaScript”> var source = 0; var replacement = 1; function createRollOver(originalImage,replacementÆ Image) { var imageArray = new Array; imageArray[source] = new Image; imageArray[source].src = originalImage; imageArray[replacement] = new Image; imageArray[replacement].src = replacementImage; return imageArray; } var rollImage1 = createRollOver(“image1.jpg”,”Æ rollImage1.jpg”);
9. In the body of the HTML, use the img tag to place the image, name the image myImage1 with the name attribute, and place the image in an a block. The a tag must have onMouseOver and onMouseOut attributes that assign the appropriate images based on the mouse movement. The resulting source code for the body of the document looks like this:
10. Save the HTML file and open it in a browser. The default image is displayed as in Figure 65-1. Move the mouse over the image to see the rollover image.
cross-reference
•
Figure 65-1: When the mouse pointer is not over the image, the original image
is displayed.
This task and Task 66 illustrate how to encapsulate two pieces of rollover functionality: the creation of the rollover Image objects and the handling of image switches in event handlers.
136
Task
66
Part 3
Using a Function to Trigger a Rollover
I
n addition to creating a function to handle the creation of rollover Image objects, you can encapsulate the code for handling the actual switching of images in rollovers within an event handler. This task extends the example illustrated in Task 65 and adds a function for this purpose.
notes
•
•
•
The function developed in this task is a general-purpose function: It can be used to perform image switches either when the mouse moves onto or off an image. This task may seem to be more complex and use more source code than was used in Task 61 to create a rollover for a single image. This is an accurate perception; however, the benefit of this module code broken into functions is that it becomes easier to handle multiple rollovers, and code for creating and triggering each rollover becomes noticeably simpler. The task of code creation, code management, and code accuracy becomes increasingly daunting as the number of rollover images in a document increases. At some point, the task of ensuring bugfree code and debugging becomes problematic. The approach in this task is aimed at mitigating this to a degree.
The following steps show how to add the function to the code from Task 65 and build and trigger rollovers using both functions: 1. In a script block in the header of a new document, create two variables—a source and a replacement containing the values 0 and 1, respectively. These variables allow the Image objects of each rollover array to be referred to by name—source for the default image and replacement for the rollover image. var source = 0; var replacement = 1;
2. Create a function named createRollOver in the same way as in Task 65: function createRollOver(originalImage,replacementImage) { var imageArray = new Array; imageArray[source] = new Image; imageArray[source].src = originalImage; imageArray[replacement] = new Image; imageArray[replacement].src = replacementImage; return imageArray; }
3. Create a function named roll with the function keyword. This function takes two parameters—targetImage, which will be the Image object associated with the img tag for the image in question, and displayImage, which will be the Image object for the image to display: function roll(targetImage,displayImage) { }
4. In the function, assign the image from displayImage to the image location associated with targetImage so that the final function looks like this: function roll(targetImage,displayImage) { targetImage.src = displayImage.src; }
5. After the roll function, invoke the createRollOver function to create the necessary rollover array and assign the array returned by the function to rollImage1. The final script looks like this: var rollImage1 = createRollOver(“image1.jpg”,”Æ rollImage1.jpg”);
Images and Rollovers
137
6. In the body of the HTML, create an image with the img tag and name the image myImage1:
7. Surround the image with opening and closing a tags:
8. Specify the onMouseOver and onMouseOut attributes of the a tag. These use the roll function to handle the switching of images.
9. Save the HTML file and open it in a browser. The default image is displayed as in Figure 66-1. Move the mouse over the image to see the rollover image, as in Figure 66-2.
Figure 66-1: When the mouse pointer is not over the image, the original image
is displayed.
Figure 66-2: When the mouse pointer is over the image, the rollover image is displayed.
Task
66
138
Task
67
Part 3
Using Functions to Create Multiple Rollovers in One Page
T note
•
This task may seem to be more complex and use more source code than was used in Task 61 to create a rollover for a single image. This is an accurate perception; however, the benefit of this module code broken into functions is that it becomes easier to handle multiple rollovers, and code for creating and triggering each rollover becomes noticeably simpler.
he real benefits of using functions for rollovers become apparent when you try to create multiple rollover effects in a page. The following example shows how to use the functions created in Tasks 65 and 66 to create two rollover images in the same document: 1. In the script block in the header of a new document, create two variables—a source and a replacement containing the values 0 and 1, respectively. These variables allow the Image objects of each rollover array to be referred to by name: source for the default image and replacement for the rollover image: var source = 0; var replacement = 1;
2. Create a function named createRollOver in the same way as in Task 65: function createRollOver(originalImage,replacementImage) { var imageArray = new Array; imageArray[source] = new Image; imageArray[source].src = originalImage; imageArray[replacement] = new Image; imageArray[replacement].src = replacementImage; return imageArray; }
3. Create a function named roll in the same way as in Task 66: function roll(targetImage,displayImage) { targetImage.src = displayImage.src; }
4. After the roll function, invoke the createRollOver function twice to create the arrays for the two rollovers. The results are returned and stored in rollImage1 and rollImage2: var rollImage1 = createRollOver(“image1.jpg”,”Æ rollImage1.jpg”); var rollImage2 = createRollOver(“image2.jpg”,”Æ rollImage2.jpg”);
5. In the body of the document, create an image with the img tag for the first rollover, and enclose it in opening and closing a tags; use the roll function to specify appropriate image switches for the onMouseOver and onMouseOut event handlers of the a tag, and name the image myImage1 with the name attribute of the img tag:
6. In the body of the document, create an image with the img tag for the second rollover, and enclose it in opening and closing a tags; use the roll function to specify appropriate image switches for the onMouseOver and onMouseOut event handlers of the a tag, and name the image myImage1 with the name attribute of the img tag. The final script should look like this:
139
Task
67
tip
•
7. Save the HTML file and open it in a browser. Two images are displayed. When the mouse pointer is not over either image, the default images are displayed, as in Figure 67-1. Move the mouse pointer over the first image to display the first rollover, as in Figure 67-2, and move over the second image to display the second rollover.
The rollover effect is designed to provide context to users, allowing them to know that the image constitutes a clickable element and showing users exactly what they are clicking on (especially in the case of numerous images in close proximity to each other in a complex layout).
Figure 67-1: The mouse is not over any image.
cross-reference
•
Figure 67-2: The mouse is over the first image.
Tasks 65 and 66 show how to use functions to modularize and simplify the code for creating and triggering rollover effects.
140
Task
68
Part 3
Creating a Simple Rollover Menu System
Y notes
•
•
Moving the functions to an outside file allows you to reuse the code in any page—and it vastly simplifies the pages that do use rollovers by removing the function code from those pages. The .js file extension is the standard extension for JavaScript files; you should use this extension for any files designed to contain JavaScript to be included in other HTML documents.
ou have seen how moving the core rollover logic into functions can facilitate the creation of multiple rollover images. To fully leverage this, you should place the functions in a separate JavaScript file that can then be included in any document you build. The following example illustrates how to take the functions used in Task 67, move them to an external JavaScript file, and then build a page that uses the file to create two rollover images in a page: 1. In a blank text file, create a JavaScript script, but without using script tags to open and close the script. Start the script by creating the source and replacement variables: var source = 0; var replacement = 1;
2. Create a function named createRollOver, as in Task 65: function createRollOver(originalImage,replacementImage) { var imageArray = new Array; imageArray[source] = new Image; imageArray[source].src = originalImage; imageArray[replacement] = new Image; imageArray[replacement].src = replacementImage; return imageArray; }
3. Create a function named roll in the same way as in Task 66: function roll(targetImage,displayImage) { targetImage.src = displayImage.src; }
4. Save the file as rollover.js. 5. In a new text file, include the rollover.js file by using the src attribute of the script tag; place this script tag in the document header: <script language=”JavaScript” src=”rollover.js”>
6. Create a second script block in the document header.
Images and Rollovers 7. In this script, invoke the createRollOver function twice to create the arrays for the two rollovers. Assign the resulting arrays to rollImage1 and rollImage2:
141
Task
68
<script language=”JavaScript”> var rollImage1 = createRollOver(“image1.jpg”,”Æ rollImage1.jpg”); var rollImage2 = createRollOver(“image2.jpg”,”Æ rollImage2.jpg”);
8. In the body of the document, create an image with the img tag for the second rollover, and enclose it in opening and closing a tags. Use the roll function to specify appropriate image switches for the onMouseOver and onMouseOut event handlers of the a tag, and name the image myImage1 with the name attribute of the img tag. The final script should look like this:
9. Save the HTML file and open it in a browser. When the mouse pointer is not over either image, the default images are displayed as in Figure 68-1.
cross-reference
•
Figure 68-1: The mouse is not over any image.
Task 4 discusses the use of the src attribute to include outside JavaScript files in your HTML pages.
142
Task
69
Part 3
Creating a Slide Show in JavaScript
I
n addition to rollover effects for images, another popular use of JavaScript with images is to create slide shows in HTML pages. These slide shows can be automatic or manually controlled by the user.
notes
•
•
The length property of an Array object provides the number of entries in an array. That means if an array has four entries numbered 0 to 3, then the length property of that array has a value of 4 (see Step 6). The window. setTimeout method takes two parameters: a function to call and a time in milliseconds. The function schedules an automatic call to the specified function after the specified number of milliseconds have elapsed. 3000 milliseconds is the same as 3 seconds (see Step 7).
•
The onLoad event handler of the body tag is used to specify JavaScript to execute when an HTML document finishes its initial loading (see Step 8).
This task illustrates the creation of an automatic slide show in which the image transitions happen every three seconds. The result is a slide show that starts on an initial image and then switches every three seconds. The third image is displayed after the slide show has been running for six seconds. The following steps create the specified automatic slide show: 1. In a script block in the header of a new HTML document, create an array named imageList; this array will hold the Image objects for the slide show: var imageList = new Array;
2. Create a new element of the array for each slide show image and assign the path and filename of the image to the src attribute of the object: imageList[0] = new imageList[0].src = imageList[1] = new imageList[1].src = imageList[2] = new imageList[2].src = imageList[3] = new imageList[3].src =
3. Create a function named slideShow that takes a single parameter named imageNumber: the number of the image to display. This number is the index of a given image in the imageList array, and the function will display the image and then schedule the display of the next image to occur three seconds later. function slideShow(imageNumber) { }
4. In the function, display the image specified in imageNumber in the place of the image named slideShow: document.slideShow.src = imageList[imageNumber].src;
5. Increment imageNumber by one: imageNumber += 1;
6. Use an if statement to test if the new image number indicates there is another image to display; that is, imageNumber should be less than the length of the imageList array after being incremented: if (imageNumber < imageList.length) { }
Images and Rollovers
143
7. Inside the if block, use the window.setTimeout method to schedule a call to the slideShow function with the new value of imageNumber passed as a parameter. This will display the next image in three seconds:
8. Add an onLoad event handler to the body tag, and call slideShow with a parameter value of zero (for the first slide) from inside the event handler:
9. In the body of the document, display the first image of the slide show with an img tag, and use the name attribute to name the image slideShow. The final page should look like Listing 69-1. <script language=”JavaScript”> var imageList = new Array; imageList[0] = new Image; imageList[0].src = “image1.jpg”; imageList[1] = new Image; imageList[1].src = “image2.jpg”; imageList[2] = new Image; imageList[2].src = “image3.jpg”; imageList[3] = new Image; imageList[3].src = “image4.jpg”; function slideShow(imageNumber) { document.slideShow.src = Æ imageList[imageNumber].src; imageNumber += 1; if (imageNumber < imageList.length) { window.setTimeout(“slideShow(“ + imageNumber Æ + “)”,3000); } }
Listing 69-1: Creating a slide show.
tip
•
The principle of creating a slide show is simple. First, load all the images into Image objects. Next, display the first image with an img tag. Finally, rotate the images with JavaScript until the slide show is complete.
144
Task
70
Part 3
Randomizing Your Slide Show
A
s an extension to the slide show created in Task 69, this task shows how to produce a randomized slide show. The slide show continues to display random images for the list of available images as long as the page is being displayed in the browser.
note
•
The window. setTimeout method
takes two parameters: a function to call and a time in milliseconds. The function schedules an automatic call to the specified function after the specified number of milliseconds have elapsed. 3000 milliseconds is the same as 3 seconds (see Step 6).
•
The onLoad event handler of the body tag is used to specify JavaScript to execute when an HTML document finishes its initial loading (see Step 7).
The following steps create just such a random slide show: 1. In a script block in the header of a new document, create an array named imageList; this array will hold the Image objects for the slide show: var imageList = new Array;
2. Create a new element of the array for each slide show image, and assign the path and filename of the image to the src attribute of the object: imageList[0] = new imageList[0].src = imageList[1] = new imageList[1].src = imageList[2] = new imageList[2].src = imageList[3] = new imageList[3].src =
3. Create a function named slideShow that takes a single parameter named imageNumber: the number of the image to display. This number is the index of a given image in the imageList array, and the function will display the image and then schedule the display of the next image to occur three seconds later. function slideShow(imageNumber) { }
4. In the function, display the image specified in imageNumber in the place of the image named slideShow: document.slideShow.src = imageList[imageNumber].src;
5. Create a variable named imageChoice, and assign it a random number from 0 to the last index in the imageList array by using Math.floor, Math.random and imageList.length: var imageChoice = Math.floor(Math.random() * Æ imageList.length);
6. Use the window.setTimeout method to schedule a call to the slideShow function with the value of imageChoice passed as a parameter. This will display the next random image in three seconds: window.setTimeout(“slideShow(“ + imageChoice + “)”,3000);
Images and Rollovers 7. Add an onLoad event handler to the body tag, and call slideShow with a parameter value of zero (for the first slide) from inside the event handler:
145
Task
70
8. In the body of the document, display the first image of the slide show with an img tag, and use the name attribute to name the image slideShow. The final page should look like this: <script language=”JavaScript”> var imageList = new Array; imageList[0] = new Image; imageList[0].src = “image1.jpg”; imageList[1] = new Image; imageList[1].src = “image2.jpg”; imageList[2] = new Image; imageList[2].src = “image3.jpg”; imageList[3] = new Image; imageList[3].src = “image4.jpg”; function slideShow(imageNumber) { document.slideShow.src = Æ imageList[imageNumber].src; var imageChoice = Math.floor(Math.random() * Æ imageList.length); window.setTimeout(“slideShow(“ + imageChoice Æ + “)”,3000); }
9. Save the page in an HTML file, and open it in a browser to display a slide show like the one in Figure 70-1.
cross-reference
•
Figure 70-1: A random slide show.
The technique in this task actually produces a simpler script than in Task 69, since it is no longer necessary to check if you have run out of images before displaying a new image. Instead, you simply keep choosing a random image and displaying it.
146
Task
71
Part 3
Triggering Slide Show Transitions from Links
A notes
•
•
Providing slide show control links requires an adjustment of the logic of the previous slide show application. Two functions are used: nextSlide to switch to the next slide and previousSlide to switch to the previous slide. The slide show will also use links in the body of the document to invoke the previousSlide and nextSlide functions. There are two ways to invoke JavaScript code when the user clicks on the link. The first is using javascript: JavaScript Code as the
URL. The second is using the onClick attribute of the a tag. The first method is a good technique when you have a single function call to make and there is no need to follow a real URL when the link is clicked by the user.
nother useful extension of the slide show illustrated in Task 69 is to allow the user to move the slide show forward and backward by clicking on links instead of automating the transition of slides as in Tasks 69 and 70. The result is a slide show presentation that looks something like Figure 71-1.
Figure 71-1: Controlling a slide show with links in the document.
The following example creates a slide show application with these manual links for the user to control the progression of the slides: 1. In a script block in the header of a new document, create an array named imageList; this array will hold the Image objects for the slide show: var imageList = new Array;
2. Create an a variable named currentSlide, and set its default value to 0; this variable will be used to track the slide the user is currently viewing: var currentSlide = 0;
3. Create a new element of the array for each slide show image, and assign the path and filename of the image to the src attribute of the object: imageList[0] = new imageList[0].src = imageList[1] = new imageList[1].src = etc.
Image; “image1.jpg”; Image; “image2.jpg”;
4. Create a function named nextSlide with the function keyword; this function will be invoked when the user wants to move forward to the next slide: function nextSlide() { }
Images and Rollovers 5. In the function, use an if statement to check whether or not the user is already at the last slide. This is done by comparing the value stored in currentSlide plus 1 (for the next slide) to the length of the imageList array. If this is not the last slide, then there is another slide and you increment currentSlide: if (currentSlide + 1 < imageList.length) { currentSlide += 1; document.slideShow.src = imageList[currentSlide].src; }
6. Create a function named previousSlide with the function keyword; this function will be invoked when the user wants to move back to the previous slide: function previousSlide() { }
7. In the function, use an if statement to check whether or not the user is already at the first slide. This is done by comparing the value stored in currentSlide less 1 (for the previous slide) to zero: if (currentSlide - 1 >= 0) { }
8. If the previous slide is greater than or equal to zero, then the user has another slide to see and that slide is displayed and the current Slide value is reduced by one: currentSlide -= 1; document.slideShow.src = imageList[currentSlide].src;
9. In the body of the document, create two links for the previous and next slide, and in the href attribute, use javascript :previousSlide() and javascript:nextSlide() to invoke the appropriate functions when the user clicks on the links. Finally, include an img tag that displays the first image from the slide show with the name slideShow specified with the name attribute.
147
Task
71
148
Task
72
Part 3
Including Captions in a Slide Show
I
n addition to rotating the images when a user clicks on a link, you can also display and rotate captions associated with the images.
note
•
This task builds on the manually controlled slide show from Task 71 and adds a caption so that the slide show looks like Figure 72-1. When the user changes images, the caption will change to match.
This task provides a simple example of one way to rotate captions with images: by displaying the caption in a form’s text field. This technique is universal and works on most browsers where techniques to dynamically replace HTML text directly are harder to perform in a truly browser-agnostic way.
Figure 72-1: Displaying a caption with an image.
The following steps add the caption to the slide show as outlined previously: 1. In a script block in the header of a new document, create an array named imageList; this array will hold the Image objects for the slide show. At the same time, create an array named captionList to hold the corresponding captions: var imageList = new Array; var captionList = new Array;
2. Create an a variable named currentSlide and set its default value to 0; this variable will be used to track the slide the user is viewing: var currentSlide = 0;
3. Create a new element of the imageList array for each slide show image, and assign the path and filename of the image to the src attribute of the object. At the same time, assign a relevant caption to the appropriate entry in the captionList array: imageList[0] = new Image; imageList[0].src = “image1.jpg”; captionList[0] = “Caption 1”; imageList[1] = new Image; imageList[1].src = “image2.jpg”; captionList[1] = “Caption 2”; etc.
Images and Rollovers 4. Create the nextSlide function as outlined in Task 71:
149
Task
function nextSlide() { if (currentSlide + 1 < imageList.length) { currentSlide += 1; document.slideShow.src = imageList[currentSlide].src; } }
72
5. In the if block, assign the appropriate caption to the caption text field to go along with the image: function nextSlide() { if (currentSlide + 1 < imageList.length) { currentSlide += 1; document.slideShow.src = imageList[currentSlide].src; document.captionForm.caption.value = Æ captionList[currentSlide]; } }
6. Create the previousSlide function as outlined in Task 71, and add the same command as in the nextSlide function to handle captions. The final script should be as follows: function previousSlide() { if (currentSlide - 1 >= 0) { currentSlide -= 1; document.slideShow.src = imageList[currentSlide].src; document.captionForm.caption.value = Æ captionList[currentSlide]; } }
7. In the body of the document, add the previous and next links and the image itself as in Task 71: < PREV | NEXT >
8. Add a form to the document and name the form captionForm. In the form, create a multiline text field named caption, and display the caption for the initial image in the text field:
cross-reference
•
Accessing form text fields and changing their values is done by assigning strings to document.formName .textFieldName. Refer to Task 79 for examples of this.
150
Task
73
Part 3
Testing If an Image Is Loaded
S
ometimes when you load an image, either through the img tag or in JavaScript by creating an Image object, the loading of the image can take a long time. In these circumstances, you may want to prevent certain actions from occurring if the appropriate images have not yet loaded.
notes
•
•
It is possible to test if an image has finished loading by checking the value of the complete property of the relevant Image object. If the value is true, then the image has finished loading. You can prevent the slide show from starting too early by adding a function to check if all the images have loaded. If all are loaded, the slide show starts. Otherwise, the function schedules a call to itself one second later to run the check again. This function is then called when the document has loaded to begin checking image loading status until images have loaded and the slide show can begin.
For instance, in a slide show, it might be appropriate to skip an image if it is not fully loaded when the user tries to display it. Similarly, it might be better to disable rollover effects until all relevant images have successfully loaded so that rollovers don’t cause switches to incomplete or unloaded images. This task illustrates the use of the complete property of the Image object by extending the random slide show from Task 70 so that the slide show doesn’t start until all the images have fully loaded. The following steps create this slide show application: 1. In a script block in the header of a new document, create an array named imageList; this array will hold the Image objects for the slide show. Load all the images into the array: var imageList = new Array; imageList[0] = new Image; imageList[0].src = “image1.jpg”; imageList[1] = new Image; imageList[1].src = “image2.jpg”; imageList[2] = new Image; imageList[2].src = “image3.jpg”; imageList[3] = new Image; imageList[3].src = “image4.jpg”; imageList[0] = new imageList[0].src = imageList[1] = new imageList[1].src = imageList[2] = new imageList[2].src = imageList[3] = new imageList[3].src =
2. In the same way as in Task 70, create a function named slideShow that takes a single parameter named imageNumber, displays the specified image, randomly chooses another image, and then schedules a call to slideShow to display that image in three seconds: function slideShow(imageNumber) { document.slideShow.src = imageList[imageNumber].src; var imageChoice = Math.floor(Math.random() * Æ imageList.length);
Images and Rollovers window.setTimeout(“slideShow(“ + imageChoice + Æ “)”,3000); }
3. Create a function named checkImages with the function keyword: function checkImages() { }
4. In the function create a variable called result and set it to false: var result = false;
5. In the function, create a for loop to loop through the imageList array: for (i = 0; Ii < imageList.length; i++) { }
6. In the loop, check if that image has completed loading, and if it has, make sure the result is true. This can be done by combining the current value of result with the value of the complete property of the related Image object using a boolean OR operation: for (i = 0; i < imageList.length; i++) { result = (result || imageList[i].complete); }
7. Test the result in an if statement, and if the result is true, call the slideShow function to start the show; otherwise, use the window. setTimeout method to call the checkImages function in one second to perform the check again: if (result) { slideShow(0); } else { window.setTimeout(“checkImages()”,1000); }
8. In the body of the document, display the initial image with the img tag, and then set the onLoad attribute of the body tag to call the checkImages function:
151
Task
73
152
Task
74
Part 3
Triggering a Rollover in a Different Location with a Link
R note
•
The onMouseOver event handler is similar to the onMouseOut event handler. It allows the programmer to specify JavaScript code to execute when the mouse pointer leaves the area occupied by a page element, such as an image where onMouseOver specified code to execute when the mouse pointer entered the space occupied by a page element (see Step 4).
ollovers are typically triggered when a user moves the mouse over the image itself; all the examples of rollovers seen so far have worked this way. But there is nothing to prevent rollover effects to be displayed in a different place than where the mouse movement is detected. For instance, it is possible to trap the mouse moving over a link but use this event to switch an image in a different location on the page. This example shows how to trigger an image switch when the user moves the mouse pointer over a separate link: 1. In a script block in the header of a new document, create an Image object named originalImage and load the default image for the rollover into the object: var originalImage = new Image; originalImage.src = “image1.jpg”;
2. Create an Image object named replacementImage, and load the rollover image for the rollover into the object. The final script block should look like this: <script language=”JavaScript”> var originalImage = new Image; originalImage.src = “image1.jpg”; var replacementImage = new Image; replacementImage.src = “rollImage1.jpg”;
3. In the body of the document, create a link that will be used for triggering the rollover; it doesn’t matter what URL is specified for the purposes of triggering the rollover: ROLLOVER THIS TEXT
4. Add an onMouseOver attribute to the a tag, and switch the myImage object to the image in the replacementImage object; this will trigger the rollover when the mouse moves over the link: ROLLOVER THIS TEXT
5. Add an onMouseOut attribute to the a tag, and switch the myImage object to the image in the originalImage object; this will return the image to the original state when the mouse moves off the link: ROLLOVER THIS TEXT
Images and Rollovers
153
6. Add an img tag to the body, and display the default image. Name the image myImage with the name attribute. The final page should look like this:
Task
74
<script language=”JavaScript”> var originalImage = new Image; originalImage.src = “image1.jpg”; var replacementImage = new Image; replacementImage.src = “rollimage1.jpg”;
The rollover effect is designed to provide context to users, allowing them to know that the image constitutes a clickable element and showing users exactly what they are clicking on (especially in the case of numerous images in close proximity to each other in a complex layout).
7. Save the page in an HTML file, and open the file in a browser. This displays a page like Figure 74-1. When the mouse moves over the link, the rollover image will be displayed as in Figure 74-2.
Figure 74-1: Initially, the default image is displayed.
cross-reference
•
Figure 74-2: When the mouse moves over the link, the rollover image is displayed.
The basics of creating an image rollover effect is outlined in Task 61.
154
Task
75
Part 3
Using Image Maps and Rollovers Together
R
ollovers can also be used with image maps. For instance, in Figure 75-1, an image is used to create a complex graphical menu. The individual ovals are specified in an image map and, therefore, are clickable links.
notes
•
•
Image maps allow you to specify multiple links for a single image by creating a map block and then using one or more area tags to specify geographic shapes to serve as links.
When rollovers are used with the image map, whenever the user rolls over the first oval, the image map is replaced with an alternate image highlighting that oval and providing descriptive text, as in Figure 75-2.
The combination of rollover effects with image maps allows the creation of complex graphical menus made out of a single image. When the user rolls over part of the image specified in an image map, it is possible to swap the image for an alternate, effectively creating a rollover effect in an image map.
Figure 75-1: The initial image map.
Figure 75-2: The rollover image for when the mouse pointer is over the first oval in the image map.
Images and Rollovers The following steps create a rollover effect on an image map: 1. In a script block in the header of a new document, create an Image object named originalImage, and load the default image for the rollover into the object: var originalImage = new Image; originalImage.src = “image1.jpg”;
2. Create an Image object named replacementImage, and load the rollover image for the rollover into the object. The final script block should look like this: var replacementImage = new Image; replacementImage.src = “rollImage1.jpg”;
3. In the header of the document, create an image map block with opening and closing map tags. Specify the name of the image map as imageMap with the name attribute of the map tag: <map name=”imageMap”>
4. Use an area tag to specify a rectangular block for a link in the image map; use the shape attribute with the value rect and the coords attribute to specify the coordinates of the rectangle: <area shape=”rect” coords=”0,0,100,100”>
5. Add an onMouseOver attribute to the area tag to replace the image named myImage with replacementImage when the mouse rolls over the specified area. Also add an onMouseOut attribute to the area tag to replace the image named myImage with the originalImage image when the mouse rolls over the specified area: <area shape=”rect” coords=”0,0,100,100” onMouseOver=”document.myImage.src = Æ replacementImage.src;” onMouseOut=”document.myImage.src = originalImage.src;”>
6. In the body of the document, display the default image using an img tag and name the image myImage with the name attribute. Use the usemap attribute to associate the image with the imageMap image map:
7. Save the code in an HTML file, and open it in a browser. When the mouse moves over the 100-pixel-wide and 100-pixel-deep square in the top-left corner of the image, the entire image map is replaced by the rollover image. When the mouse moves out of this area, the original image is displayed.
155
Task
75
156
Task
76
Part 3
Generating Animated Banners in JavaScript
M
any of the banner ads you see on the Web are animated. Sometimes these are done with animated GIF files, which provide a simple way to generate an animated image without resorting to any custom code.
note
•
The window. setTimeout method takes two parameters: a function to call and a time in milliseconds. The function schedules an automatic call to the specified function after the specified number of milliseconds have elapsed. 3000 milliseconds is the same as 3 seconds (see Step 7).
•
The onLoad event handler of the body tag is used to specify JavaScript to execute when an HTML document finishes its initial loading (see Step 9).
However, GIFs have their limitations, not least of which they are not well suited to displaying photographic-style images with high color depth. That’s when JPEG images come in handy. The problem is that JPEG images cannot be animated. Using JavaScript you can animate a JPEG-based banner in much the same way that a slide show allows multiple images to be displayed. This is done by creating one JPEG image for each frame of the animation and then rotating them using JavaScript. This task shows how you can create an animated banner with JavaScript and provide control over the amount of time between each frame transition: 1. In a script block in the header of a new document, create two arrays: imageList to hold the individual Image objects for the frames of the banner and transitionList to hold a list of transition times in milliseconds, specifying how long to wait after displaying one frame before displaying the next: var imageList = new Array; var transitionList = new Array;
2. Populate the imageList array with Image objects for the frames, and specify transition times in the transitionList array: imageList[0] = new Image; imageList[0].src = “frame1.jpg”; transitionList[0] = 2000; imageList[1] = new Image; imageList[1].src = “frame2.jpg”; transitionList[1] = 500; imageList[2] = new Image; imageList[2].src = “frame3.jpg”; transitionList[2] = 5000; imageList[3] = new Image; imageList[3].src = “frame4.jpg”; transitionList[3] = 3000;
3. Create a rotateBanner function that takes a single parameter frameNumber to indicate the frame that needs to be displayed: function rotateBanner(frameNumber) { }
Images and Rollovers 4. In the function, display the specified frame in the place of the Image object named banner: document.banner.src = imageList[frameNumber].src;
5. Next, increment the frame number and assign it to a new variable called imageChoice: var imageChoice = frameNumber + 1;
6. Check the value of imageChoice. If it is the same as the length of the imageList array, reset it to 0. This way the banner will rotate when it hits the last frame: if (imageChoice == imageList.length) Æ { imageChoice = 0; }
7. As the last step of the function, schedule the rotateBanner function to run again after the appropriate display specified in the transitionList array: window.setTimeout(“rotateBanner(“ + imageChoice + Æ “)”,transitionList[frameNumber]);
8. In the body of the document, display the first frame of the image with the img tag, and name the image banner:
9. In the body tag, specify the onLoad attribute to invoke rotateBanner when the document loads, passing a value of 0 to the rotateBanner function:
10. Save the code in an HTML, and open the file in a browser to see an animated banner as in Figure 76-1.
Figure 76-1: Displaying rotating JPEG banners with JavaScript.
157
Task
76
158
Task
77
notes
• • •
•
•
Each slot in an array is numbered; numbering starts at zero. This means an array with four entries has entries numbered 0 to 3. The Math object provides a number of useful methods for working with numbers and mathematical operations. The length property of an Array object provides the number of entries in an array. That means if an array has four entries numbered 0 to 3, then the length property of that array has a value of 4. Math.floor performs a
function similar to rounding in that it removes the decimal part of a number. The difference is that the result of rounding can be the next highest or next lowest integer value, depending on the size of the decimal portion of the number. With Math.floor the result is always the next lowest integer. Therefore, rounding 2.999 would result in the integer 3. but applying Math.floor to the same number would result in the integer 2. Notice how the output is built out of multiple strings combined with an array variable; the combining is done with plus signs. When you are working with string values, plus signs perform concatenation of strings, as discussed in Task 15. Concatenation means that “ab” + “cd” results in “abcd”.
Part 3
Displaying a Random Banner Ad
O
ne application of the combination of JavaScript and images is to load a random image in a location on the page rather than the same image every time. You can apply this to presenting random banner ads that link to the appropriate site for the ad. To do this you need to use JavaScript to specify both the location of the images and URLs associated with the images. With this data you can select one at random and display it. The script created in the following steps illustrates this process: 1. Create a script block with opening and closing script tags; the script block should be in the body of your HTML document where you want the image to be displayed: <script language=”JavaScript”>
2. In the script, create an array named imageList: var imageList = new Array;
3. Create an entry in the array for each banner’s image you want to make available for random selection. For instance, if you have four images, assign the path and names of those images to the first four entries in the array: imageList[0] imageList[1] imageList[2] imageList[3]
4. Create another array to hold the URLs for each banner. The indexes in this array should correspond to the imageList array: var urlList = new Array; urlList[0] = “http://some.host/”; urlList[1] = “http://another.host/”; urlList[2] = “http://somewhere.else/”; urlList[3] = “http://right.here/”;
5. Create a variable named imageChoice: var imageChoice;
6. Assign a random number to imageChoice using the Math.random method, which returns a random number from 0 to 1 (that is, the number will be greater than or equal to 0 but less than 1): var imageChoice = Math.random();
7. Extend the expression assigned to imageChoice by multiplying the random number by the number of entries in the imageList array to produce a number greater than or equal to 0 but less than 4: var imageChoice = Math.random() * imageList.length;
Images and Rollovers
159
8. Extend the expression assigned to imageChoice further by removing any part after the decimal point with the Math.floor method; the result is an integer from 0 to one less than the number of entries in the array—in this case that means an integer from 0 to 3:
Task
77
var imageChoice = Math.floor(Math.random() * Æ imageList.length);
9. Use the document.write method to place an img tag surrounded by an a tag in the HTML data stream sent to the browser. As the value of the src attribute of img tag, the random image is specified as imageList[imageChoice], and as the value of the href attribute of the a tag, use urlList[imageChoice]. The final script looks Listing 77-1. <script language=”JavaScript”> var imageList = new Array; imageList[0] = “image1.jpg”; imageList[1] = “image2.jpg”; imageList[2] = “image3.jpg”; imageList[3] = “image4.jpg”; var urlList = new Array; urlList[0] = “http://some.host/”; urlList[1] = “http://another.host/”; urlList[2] = “http://somewhere.else/”; urlList[3] = “http://right.here/”; var imageChoice = Math.floor(Math.random() * Æ imageList.length); document.write(‘’);
Listing 77-1: Displaying a random banner ad.
10. Save the code in an HTML file, and display the file in a browser. A random banner is displayed. Reloading the file should result in a different banner (although there is always a small chance the same random number will be selected twice in a row).
cross-references
• •
An array is a data type that contains multiple, numbered slots into which you can place any value. See Task 20 for a discussion of arrays. The document.write method is introduced in Task 45. It allows JavaScript code to generate output that forms part of the HTML rendered by the browser.
Preparing Your Forms for JavaScript Accessing Text Field Contents Dynamically Updating Text Fields Detecting Changes in Text Fields Accessing Selection Lists Programmatically Populating a Selection List Dynamically Changing Selection List Content Detecting Selections in Selection Lists Updating One Selection List Based on Selection in Another Using Radio Buttons instead of Selection Lists Detecting the Selected Radio Button Detecting Change of Radio Button Selection Updating or Changing Radio Button Selection Creating Check Boxes Detecting Check Box Selections Changing Check Box Selections Detecting Changes in Check Box Selections Verifying Form Fields in JavaScript Using the onSubmit Attribute of the Form Tag to Verify Form Fields Verifying Form Fields Using INPUT TYPE=”button” Instead of TYPE=”submit” Validating E-mail Addresses Validating Zip Codes Validating Phone Numbers Validating Credit Card Numbers Validating Selection List Choices Validating Radio Button Selections Validating Check Box Selections Validating Passwords Validating Phone Numbers with Regular Expressions Creating Multiple Form Submission Buttons using INPUT TYPE=”button” Buttons Reacting to Mouse Clicks on Buttons Using Graphical Buttons in JavaScript Controlling the Form Submission URL Validating a Numeric Text Field with Regular Expressions Encrypting Data before Submitting It Using Forms for Automatic Navigation Jumping
162
Task
78
notes
•
To access a field in a form, you can use the following reference in JavaScript: document.forms[0]. elements[0]
Each form in your document is contained in the forms array in the order it appears in your document. The elements array, similarly, has one entry for each field in a given form in the order the fields appear in the form.
•
If the form is not named, then each form is accessible in the document.forms array, so that the first form in the document is document.forms [0], the second is document.forms[1],
Part 4
Preparing Your Forms for JavaScript
I
n JavaScript, you can access and manipulate the content and state of fields in forms on the page. To do this, you need to give some attention to the minimum requirements needed to make your forms easily accessible in JavaScript. Primarily, you must focus on providing names for your forms and elements. The following steps walk you through the process of naming your forms and elements so you can access them using JavaScript: 1. Create a new document in your preferred editor. 2. Create a form in the body of the document. Add an input text field, a selection list, and a command button to your form:
This form is shown in Figure 78-1.
and so on.
•
If the field is not named, then each field in the form is accessible in the document.formName.e lements array, so that the
first field in the form is document.formName. elements[0], the second is document.formName. elements[1], and so on.
•
Most of the tasks in this part use the name attribute to manipulate the contents of a form.
Figure 78-1: A standard HTML form.
Working with Forms
163
3. Name the form by adding a name attribute. The following code names the form thisform. As shown in bold, the name attribute is added within the form tag:
Task
78
tips
• •
4. Name the elements within the form. Just like naming the form, this is done by adding an attribute called name to each field’s tag. This attribute is then set to the name of the element as shown in Listing 78-1. Once you’ve assigned the name attributes, your form is ready to be easily used with JavaScript.
Naming fields and forms makes them much easier to refer to and ensures you are referring to the correct fields in your code. When naming forms and the elements within your forms, you should use descriptive names.
Listing 78-1: A JavaScript-ready form.
cross-reference
•
Task 79 shows you how to access a text field using the assigned name.
164
Task
79
Part 4
Accessing Text Field Contents
W
hen you create an HTML form, you are creating a series of objects, which can be accessed from within JavaScript. The form itself is an object, and then each of the fields in the form is represented by an object in JavaScript. Using these objects, you can access the values stored in form fields such as text input fields.
notes
•
The following is the minimum HTML required to create a text field:
Notice the use of # as the URL in the example. When using the onClick event handler to trigger the opening of a new window, you don’t want to cause clicking on the link to change the location of the current window; this is a simple way to avoid this.
•
•
If the form is not named, then each form is accessible in the document. forms array, so that the first form in the document is document.forms[0], the second is document. forms[1], and so on. If the field is not named, then each field in the form is accessible in the
You can check the text that is displayed in a text input field—whether it is text that is a part of the form or text that a user has entered. To be able to access a field in JavaScript, use the following steps: 1. Create a new document in your preferred editor. 2. In the body of the document, create the form named myForm that contains a text input field named myText:
3. Create a link in your form. This link is used to display the value of the text input element in a dialog box. Specify # as the URL for the link: Check Text Field
document.formName. elements array, so that
the first field in the form is document.formName. elements[0], the second is document. formName.elements[1],
and so on.
4. Use the onClick event handler in the link element to specify JavaScript code to execute when the user clicks on the link. To access a form field, you use the following syntax: document.formName.fieldName
This references the object associated with the field. The object has several properties, including: • name: The name of the field (as specified in the name attribute) • value: The text displayed in the field • form: A reference to the form object for the form in which the field exists
Working with Forms Therefore, the property document.formName.formField.value would contain a string of text as displayed in the field.
165
Task
In this example, document.myForm.myText.value would represent the text in the text input field, so this is passed as an argument to window.alert. The result is that the text in the myText text input box is displayed in a dialog box. Listing 79-1 shows the complete listing with the JavaScript added.
Naming forms and fields makes it much easier to refer to them and ensures you are referring to the correct fields in your code. In the listing in Step 4, change document. myForm.myText.value to document.myForm. myText.name. You’ll see
the result is that the name of the text input field is displayed instead of the value.
Listing 79-1: Accessing the value of a form text field.
5. Save the file and close it. 6. Open the file in your browser. Enter some text in the text field, and then click the link to see that text displayed in a dialog box, as illustrated in Figure 79-1.
cross-references
• •
Figure 79-1: Displaying the text field’s value.
See Task 200 to learn more about the onClick event handler. For more information on naming elements and forms, see Task 78.
166
Task
80
Part 4
Dynamically Updating Text Fields
U
sing JavaScript, you can change the values in a text input field. The easiest time to make this update is when a user does something on your form. This task shows you how to dynamically update the text that is displayed in a text input field: 1. Create a new document in your preferred editor.
notes
•
•
•
Notice the use of # as the URL in the example. When using the onClick event handler to trigger the opening of a new window, you don’t want to cause clicking on the link to change the location of the current window; this is a simple way to avoid this. If the form is not named, then each form is accessible in the document. forms array, so that the first form in the document is document. forms[0], the second is document.forms[1], and so on. If the field is not named, then each field in the form is accessible in the document.formName. elements array, so that
the first field in the form is document.formName. elements[0], the second is document. formName.elements[1],
and so on.
2. Create a form in the body of your document. Name your form myForm. 3. Add two text input fields to your form. Name one myText, which will be used to enter text. Call the other copyText. It will have its value dynamically changed. The following is the completed form:
4. Create a link that will be used to dynamically change the text. The user can enter text into the myText field and then click on the link to copy that text into the second text field; the copying is done with JavaScript. Although a link is used in this example, you could just as easily use a button click or any other event to dynamically change the text. Specify # as the URL for the link. 5. Add an onClick event handler to the link. This will specify the JavaScript code to execute when the user clicks on the link. The property document.formName.formField.value contains the value of a field in the form of a string of text. If you assign a value to the value property, the new value will be displayed in the text field. In this case, the value from the myText field will be assigned to the copyText field. This is done by assigning document.myForm. myText.value to document.myForm.copyText.value. Listing 80-1 shows the final form with the link and JavaScript added. Figure 80-1 shows the form.
Listing 80-1: Assigning a value to a form text field.
tip
•
Naming forms and fields makes it much easier to refer to them and ensures you are referring to the correct fields in your code.
Figure 80-1: A form with two text fields.
6. Save the file and close it. 7. Open the file in your browser. You should see the form and link as shown in Figure 80-1. Enter some text in the first text field, and then click the link to see the text copied and displayed in the second field, as illustrated in Figure 80-2.
cross-reference
•
Figure 80-2: Assigning text to a text field.
For more information on naming elements and forms, see Task 78.
168
Task
81
Part 4
Detecting Changes in Text Fields
W
hen you create an HTML form, you are creating a series of objects that can be accessed from within JavaScript. Using these objects, you can detect changes in form fields such as text input fields.
notes
•
•
For the detection of the change to occur, most browsers (including all the major ones) don’t actually consider a change to have occurred until the focus leaves the field (such as when the user clicks in another field in the form). If the user didn’t do this, then every time he or she typed a character, the code in the onChange event handler would execute. Instead, the code only executes when a change has occurred and focus has left the field. When working in the event handler of a form field, the this keyword refers to the object associated with the field itself, which allows you to use this.value instead of document. myForm.myText.value
to refer to the text field’s value in the onChange event handler (see Step 4).
This task shows you how to react to a change in a text input field. Text input fields are created with the input tag and by setting the type attribute equal to text. To make the field accessible in JavaScript, it is also best to assign a name to the field with the name attribute:
You can specify code to execute when a change occurs in the field with the onChange event handler:
The following steps create a form with a text field. When a change is detected in the field, a dialog box is displayed telling the user the value in the field. 1. Create a new document in your preferred editor. 2. In the body of the document, create a form named myForm.
3. In the form, create a text input field with the name myText:
4. Assign an onChange event handler to the field. The handler should display this.value in a dialog box with the window.alert method. The final page should look like Listing 81-1. 5. Save the file and close it. 6. Open the file in your browser. You should see the form as in Figure 81-1. 7. Enter some text in the text field and then click outside the field to remove focus from the field. You should see the dialog box shown in Figure 81-2.
Working with Forms
169
Task
81
Listing 81-1: Detecting changes in text fields.
Figure 81-1: A form with a text field.
cross-reference
•
Figure 81-2: Detecting change in the text field.
Learn about naming fields in Task 78.
170
82
Task
Part 4
Accessing Selection Lists
W
hen you create an HTML form, you are creating a series of objects that can be accessed from within JavaScript. The form itself is an object, and then each form field is represented by an object in JavaScript. Using these objects, you can access the values stored in form fields such as selection lists. This task shows you how to check the current selection in a selection list.
notes
•
Selection lists are created with the select tag. You populate the list with the option tag: <select name= ”myField”>
7. Create a radio button for the Yes option in a radio group named myRadio: Yes
8. Create a second radio button for the No option in the same group: Yes No
9. Save the form in an HTML file. 10. Open the file in the form. You now see the same choices presented as a selection list and as a pair of radio buttons, as in Figure 87-2.
cross-reference
•
Figure 87-2: Selection lists and radio buttons can often be used for the same tasks.
See Task 82 for a quick overview of selection lists.
182
Task
88
Part 4
Detecting the Selected Radio Button
W
hen you create an HTML form, you are creating a series of objects that can be accessed from within JavaScript. The form itself is an object, and an object in JavaScript also represents each form field. Using these objects, you can access the selected radio button in a group of radio buttons.
notes
• •
The checked property has a value of true if it is currently selected and false if it is not. Radio button groups are created through a series of input tags with the same name and the type specified as radio:
This task shows you how to check which radio button the user has selected. To access the radio button group, you use this syntax: document.formName.groupName
This references the object associated with the radio button group. This object is actually an array containing an entry for each button in the group, and each of these entries has several properties, including two critical ones for this task: • checked: Indicates if the radio button is currently selected
Option 1
• value: Reflects the value of the value attribute for the radio button Therefore, the property document.formName.formField[0].value would contain the value of the first radio button in a radio button group.
Option 2
•
• •
Arrays have a property called length that returns the number of items in an array, and it is used in this loop. Since arrays are zeroindexed, an array with length 5 (which contains five elements) would contain elements with indexes from 0 to 4. This is why you loop until i is less than, and not less than or equal to, the length of the array. The checked property of a radio button object is either true or false, which makes it sufficient as a condition for an if statement. Remember, the browser will only allow a single radio button in the group to be selected. This means that the if statement will be true only once and buttonValue will only ever be assigned the value of the single, selected radio button.
The following steps create a form with a group of radio buttons. The value of the currently selected radio button is displayed by clicking a link that is provided. 1. In the header of a new HTML document, create a script block with a function named whichButton that takes no arguments: <script language=”JavaScript”> function whichButton() { }
2. In the function, create a variable named buttonValue that is initially an empty string: var buttonValue = “”;
3. Loop through the document.myForm.myRadio array of radio button objects: for (i = 0; i < document.myForm.myRadio.length; i++) { }
4. In the loop, check if the current radio button item is selected: if (document.myForm.myRadio[i].checked) { }
Working with Forms
183
5. If the current button is checked, assign its value to buttonValue:
Task
buttonValue = document.myForm.myRadio[i].value;
88
6. After the loop, return the value of buttonValue. Listing 88-1 presents the completed function. <script language=”JavaScript”> function whichButton() { var buttonValue = “”; for (i = 0; i < document.myForm.myRadio.length; i++) { if (document.myForm.myRadio[i].checked) { buttonValue = document.myForm.myRadio[i].value; } } return buttonValue; }
Listing 88-1: The whichButton function.
7. In the body of the document, create a form named myForm that will call your function. This should have a radio button group named myRadio and a link. The link should use an onClick event handler to display the result of calling whichButton in an alert dialog box. The final form should look like Listing 88-2. Æ Which Radio Button?
cross-reference Listing 88-2: Detecting the selected radio button.
8. Save the file and open the file in your browser. You should see the form and link. 9. Select a radio button, and click the link to see the value displayed.
•
For more information on using radio buttons, see Task 87
184
Task
89
Part 4
Detecting Change of Radio Button Selection
W
hen you create an HTML form, you are creating a series of objects that can be accessed from within JavaScript. The form itself is an object, and then an object in JavaScript represents each form field. Using these objects, you can make changes in the selection of a radio button in a group of radio buttons.
notes
•
Radio button groups are created through a series of input tags with the same name and the type specified as radio: Option 1 Option 2
•
Arrays have a property called length that returns the number of items in an array, and it is used in this loop. Since arrays are zeroindexed, an array with length 5 (which contains five elements) would contain elements with indexes from 0 to 4. This is why you loop until i is less than, and not less than or equal to, the length of the array.
This task shows you how to react to the user selecting a new radio button. To detect selection of a radio button, you can use the onClick event handler in each of the radio buttons in your group:
The following steps create a form with a group of radio buttons and then display an appropriate dialog box when the user selects each radio button. JavaScript is used to display these dialog boxes. 1. Create a new document in your preferred editor. 2. In the body of the document, create a form named myForm:
3. Create a group of radio buttons called myRadio:
4. Add an onClick event handler to each of the first radio buttons. Use the event handlers to display a dialog box when the user selects that radio button. The final page looks like Listing 89-1.
Task
89
Listing 89-1: Responding to Selection of a Radio Button.
5. Save the file and close it. 6. Open the file in a browser, and you should see the form with radio buttons, as in Figure 89-1. Figure 89-1: A form with radio buttons.
7. Click on one of the radio buttons to see the associated dialog box, as in Figure 89-2. Figure 89-2: Reacting to the selection of a radio button.
cross-references
• •
See Task 81 to learn how to detect changes in text fields. Task 94 shows how to detect changes in check boxes. For more information on using radio buttons, see Task 87.
186
Task
90
Part 4
Updating or Changing Radio Button Selection
W notes
•
•
If the form is not named, then each form is accessible in the document. forms array, so that the first form in the document is document.forms[0], the second is document. forms[1], and so on. However, naming forms makes it much easier to refer to them and ensures you are referring to the correct form in your code. If the field is not named, then each field in the form is accessible in the document.formName. elements array, so that
hen you create an HTML form, you are creating a series of objects that can be accessed from within JavaScript. The form itself is an object, and then an object in JavaScript represents each form field. Using these objects, you can dynamically select a radio button in a group of radio buttons. This task shows you how to select a radio button based on another action that occurs. To access the radio button group, you use the following syntax: document.formName.groupName
This references the object associated with the radio button group. This object is actually an array containing an entry for each button in the group, and each of these entries has several properties, including two critical ones for this task: • checked: Indicates if the radio button is currently selected • value: Reflects the value of the value attribute for the radio button Therefore, the property document.formName.formField[0].value would contain the value of the first radio button in a radio button group.
the first field in the form is document.formName. elements[0], the second is document. formName.elements[1],
and so on. However, naming fields makes it much easier to refer to them and ensures you are referring to the correct fields in your code
• •
•
The checked property has a value of true if it is currently selected and false if it is not. Remember, the browser will only allow a single radio button in the group to be selected. When you set the checked property of one radio button to true, all other buttons in the group are automatically deselected. Remember, arrays are zeroindexed, so the first radio button has an index of 0.
The following steps create a form with a pair of radio buttons and then provide two links the user can click to select the radio buttons without actually clicking directly on the radio buttons. Selecting the radio buttons is done with JavaScript. 1. In the header of a new HTML document, create a script block with a function named selectButton that takes a single argument containing the index of a specific radio button in the group. 2. In the function, set the checked property of the radio button to true: <script language=”JavaScript”> function selectButton(button) { document.myForm.myRadio[button].checked = true; }
3. In the body of the document, create a form named myForm with a radio button group named myRadio:
4. After the form, create a link that uses an onClick event handler to call the selectButton function to select the first radio button:
5. Create another link for selecting the second radio button so that the final page looks like Listing 90-1. <script language=”JavaScript”> function selectButton(button) { document.myForm.myRadio(button).checked = true; } Select First Æ Radio Button Select Second Æ Radio Button
Listing 90-1: Selecting Radio Buttons from Links.
6. Save the file and open the file in your browser. You should see the form and links as in Figure 90-1.
cross-reference
•
Figure 90-1: A form with radio buttons.
7. Select either link to select a radio button.
See Task 84 to learn how to update options in a selection list. Task 93 shows how to change a check box’s selection.
188
Task
91
Part 4
Creating Check Boxes
S
imilar to radio buttons, check boxes allow yes/no-type selections: Either the box is checked or it is not. Unlike radio buttons, however, groups of check boxes are not mutually exclusive: None can be selected, all can be selected, or any subset can be selected.
notes
• •
With check boxes, you specify any text to display next to the check box’s input tag. The text to display is not inherent to the input tag.
Check boxes are often used to allow users to make selections in a long list where they can choose any number of options. These lists look like Figure 91-1.
Just as with radio button, each check box has text that is displayed next to the button and a value, specified with the value attribute. It is the value and not the text that is tracked and manipulated from within JavaScript and submitted when you submit the form.
Figure 91-1: Using check boxes for long lists.
Check boxes are created with the input tag using checkbox as the value of the type attribute:
You can set whether a check box is selected (checked) by setting a checked property. Setting this property to true will check the box. The following steps display a form with a series of check boxes in a list: 1. Create a new document in your editor. 2. In the body of the document, create a form:
3. In the form create a series of check boxes:
4. Set the checked property so that the third option is selected by default. The final page looks like Listing 91-1.
Listing 91-1: A series of check boxes.
5. Save the file and close it. 6. Open the file in the form, and check boxes in a list appear, as shown in Figure 91-2.
cross-reference
•
Figure 91-2: The form with a series of check boxes.
Tasks 92, 93, and 94 show you how to use JavaScript to manipulate check boxes.
190
Task
92
Part 4
Detecting Check Box Selections
W
hen you create an HTML form, you are creating a series of objects that can be accessed from within JavaScript. The form itself is an object, and then an object in JavaScript represents each form field. Using these objects, you can access the selection status of check boxes.
notes
• •
•
The checked property has a value of true if it is currently selected and false if it is not. Notice the use of # as the URL in the example. When using the onClick event handler to trigger the opening of a new window, you don’t want to cause clicking on the link to change the location of the current window; this is a simple way to avoid this. The argument to window. alert requires some attention. This argument is actual a short form conditional test of the form condition ? value to return if true : value to return if false. This means if the
checked property is true, then “Yes” is displayed in the dialog box; otherwise, “No” is displayed in the dialog box. The checked property of a radio button object is either true or false, which makes it sufficient as a condition for the short form conditional test used in the window.alert method.
This task shows you how to check selection status of a check box. To access the check box, you use the following syntax: document.formName.fieldName
This references the object associated with the check box, which has several properties, including • checked: Indicates if the check box is currently selected • value: Reflects the value of the value attribute for the check box Therefore, the property document.formName.formField.value would contain the value of a check box. The following steps create a form with a check box and a link. The user can click the link to display the status of the check box selection in a dialog box. JavaScript is used to display this information in the dialog box: 1. Create a new document in your preferred editor. 2. In the body of your document, create a form named myForm: 3. In the form create a check box named myCheck: Check Me
4. After the form create a link with the href attribute set to #. The user will use the link to check the status of the check box: Am I Checked?
5. Set the onClick event handler of the link to display the current selection status by checking the checked property of the checkbox object. The final page will look like Listing 92-1. 6. Save the file and close it. 7. Open the file in your browser, and the form and link appears, as shown in Figure 92-1. 8. Click on the link to see the current selection status in a dialog box, as shown in Figure 92-2.
Listing 92-1: Checking a check box’s selection status.
Figure 92-1: A form with a check box.
cross-reference
•
Figure 92-2: Displaying the check box’s selection status.
See Task 91 for more information on check boxes.
192
Task
93
Part 4
Changing Check Box Selections
W
hen you create an HTML form, you are creating a series of objects that can be accessed from within JavaScript. The form itself is an object and then an object in JavaScript represents each form field. Using these objects you can change the selection status of check box.
notes
• •
•
The checked property has a value of true if it is currently selected and false if it is not. Notice the use of # as the URL in the example. When using the onClick event handler to trigger the opening of a new window, you don’t want to cause clicking on the link to change the location of the current window; this is a simple way to avoid this. If the field is not named, then each field in the form is accessble in the document.formName. elements array, so that
the first field in the form is document.formName. elements[0], the second is document. formName.elements[1],
and so on. However, naming fields makes it much easier to refer to them and ensures you are referring to the correct fields in your code.
•
If the form is not named, then each form is accessible in the document. forms array, so that the first form in the document is document.forms[0], the second is document. forms[1], and so on. However, naming forms makes it much easier to refer to them and ensures you are referring to the correct form in your code.
This task shows you how to control selection status of a check box. To access the check box, you use the following syntax: document.formName.fieldName
This references the object associated with the check box that has several properties including: • checked: Indicates if the check box is currently selected • value: Reflects the value of the value attribute for the check box Therefore, the property document.formName.formField.value would contain the value of a check box. The following steps create a form with a check box. A link is provided that the user can click to check or uncheck the check box. JavaScript is used to change the selection status of the check box. 1. Create a new document in your preferred editor. 2. In the body of your document, create a form named myForm:
3. In the form, create a check box named myCheck: Check Me
4. After the form, create a link with the href attribute set to #. The user will use the link to select the check box: Check the box
5. Set the onClick event handler of the link to assign true to the checked property of the check box: Check the box
Working with Forms
193
6. Create a similar, second link to uncheck the check box but (set checked to false instead of true). The final page will look like Listing 93-1. Check the box Uncheck the box
Listing 93-1: Controlling a check box’s selection status.
7. Save the file and close it. 8. Open the file in your browser, and the form and links appear, as illustrated in Figure 93-1.
Figure 93-1: A form with a check box.
9. Click on the first link to select the check box. Click on the second link to unselect the check box.
Task
93
194
Task
94
Part 4
Detecting Changes in Check Box Selections
W notes
• •
The checked property has a value of true if it is currently selected and false if it is not. The window.alert() method displays a dialog box. The value passed to this method will be displayed in the dialog box.
hen you create an HTML form, you are creating a series of objects that can be accessed from within JavaScript. The form itself is an object, and then an object in JavaScript represents each form field. Using these objects, you can detect changes in the selection of a check box. This task shows you how to react to the user clicking on a check box. Check boxes are created with input tags, with the type specified as checkbox: Check box text
To detect selection of a check box, you can use the onClick event handler: Check box text
The following steps create a form with a checkbox. A dialog box is displayed each time the user clicks on the check box. JavaScript is used to display these dialog boxes. 1. Create a new document in your preferred editor. 2. In the body of the document, create a form named myForm:
3. Create a group of check box named myCheck:
caution
•
Note in Step 4 that the value passed to the window.alert()
method is surrounded by single quotes rather than double quotes. This is because this method is surrounded in double quotes for the onClick event. If you use double quotes, you will not get the expected results.
4. Add an onClick event handler to check box, and use it to display a dialog box when the user clicks the check box:
5. Save the file and close it. 6. Open the file in a browser, and you should see the form with the check box, as in Figure 94-1.
Figure 94-1: A form with a check box.
7. Click on the check box to see the associated dialog box, as in Figure 94-2.
Figure 94-2: Reacting to the user clicking on the check box.
195
Task
94
196
Task
95
Part 4
Verifying Form Fields in JavaScript
O
ne of the main applications of JavaScript is to perform validation of the data entered into a form. One approach to form validation is to check the data entered in a field when the user attempts to move out of the field. Until valid data is entered, you prevent the user from leaving the field. The approach is simple:
notes
• •
•
This process relies on the focus method available for form field objects. This method sets mouse focus into a field that did not have focus before. The field that “has focus” is the field that is currently active. A field is often given focus when the user clicks on it or tabs to it. In this task you see how to force the focus to go to a specific field. Notice that this is passed as the argument to the checkField function. In the event handlers for a form field, this refers to the object for the form field itself.
• In the form field you want to validate, use the onBlur event handler to call a JavaScript function to test your form field. • In the function, check the validity of the data entered. If the data is not valid, then inform the user and force the focus back to the field. The following steps provide an example of this type of validation: 1. Create a script block in the header of a new HTML document that contains a function called checkField. The function takes the form field’s object as an argument: <script language=”JavaScript”> function checkField(field) { }
2. In the function, check if the field is empty: if (field.value == “”) { }
3. If the field doesn’t contain text, alert the user to enter text: window.alert(“You must enter a value in the field”);
4. If the field contains no text, reset the focus to the field: field.focus();
5. In the body of the document, create a form named myForm: 6. In the form, create a text field named myField and a submit button:
caution
•
Field-level validation strategy is fine if there are only one or two fields to validate in a form. This type of validation can quickly get in the way of the user efficiently completing the form if you are using a large form where the user may jump around while filling in the data.
7. In the onBlur event handler of the text field, call the checkField function so that the final page looks like Listing 95-1. 8. Save the file with the name target.html and close it. 9. Open the file in a browser. The form in Figure 95-1 appears.
Working with Forms
197
<script language=”JavaScript”> function checkField(field) { if (field.value == “”) { window.alert(“You must enter a value in the field”); field.focus(); } }
Task
95
Listing 95-1: Validating a form field when the user leaves the field.
Figure 95-1: A form with a text field.
10. Click into the text field and then try to click outside the field without entering any text. An alert appears, warning you to enter text in the field, as shown in Figure 95-2, and then focus is returned to the field.
Figure 95-2: Forcing the user to enter text in a field.
cross-reference
•
In Tasks 98 through 106 you learn how to validate specific types of information such as e-mail addresses (Task 98), phone numbers (Task 100), and passwords (Task 105).
198
Task
96
Part 4
Using the onSubmit Attribute of the Form Tag to Verify Form Fields
O notes
• •
•
• •
•
This process relies on the fact that if the JavaScript code in the onSubmit event handler returns false, the submission itself is canceled. Notice that this is passed as the argument to the checkForm function. In the event handlers for a form tag, this refers to the object for the form itself. The onSubmit event handler used here requires attention. Instead of simply calling checkForm, you return the value returned by checkForm. Since checkForm returns true if the form is OK and false otherwise; this allows you to cancel submission if the form is not OK and allows it to continue if the form is OK. This process relies on the focus method available for form field objects. This method sets mouse focus into a field that did not have focus before. The field that “has focus” is the field that is currently active. A field is often given focus when the user clicks on it or tabs to it. In this task you see how to force the focus to go to a specific field. Setting the formOK field equal to true assumes that the form is OK to submit.
ne of the main applications of JavaScript is to perform validation of the data entered in forms. One approach to form validation is to check the data entered in a form when the user attempts to submit the form. The approach is simple: • In the form you want to validate, use the onSubmit event handler to call a JavaScript function to test your form when it is submitted. • In the function, check the validity of the data entered in the form. If the data is not valid, then inform the user and cancel the form submission.
The following task provides an example of this type of validation. If the user attempts to submit the form without entering text in a single text field, the user will be informed that he or she must enter text or the submission will be canceled. 1. In the header of a new HTML document, create a script block with a function called checkForm that receives the form’s object (formObj): function checkForm(formObj) { }
2. In the function, create a variable named formOK that is set to true: var formOK = true;
3. In the function, check if the field is the empty string: if (formObj.myField.value == “”) { }
4. If the field contains no text, alert the user that he or she must enter text to continue. Return focus to the field and set formOK to false: window.alert(“You must enter a value in the field”); formObj.myField.focus(); formOK = false;
5. Return the value of formOK from the function: return formOK;
6. In the body of the document, create a form named myForm that has a text field named myField: and a submit button: 7. In the onSubmit event handler of the form, call the checkForm function. The final page looks like Listing 96-1.
Working with Forms
199
<script language=”JavaScript”> function checkForm(formObj) { var formOK = true; if (formObj.myField.value == “”) { window.alert(“You must enter a value in the field”); formObj.myField.focus(); formOK = false; } return formOK; }
Task
96
Listing 96-1: Validating a form when the user submits it.
8. Save the file with the name target.html and close it. 9. Open the file in a browser, and the form in Figure 96-1 appears.
cross-reference
•
Figure 96-1: A form with a text field.
10. Try to submit the form without entering any text. You see an alert, and then focus will be returned to the field.
Task 95 shows how to validate a single field when the user moves away from it.
200
Task
97
notes
• • • •
Setting the formOK field equal to true assumes that the form is OK to submit. This process relies on the submit method of form objects, which allows you to trigger submission of a form from JavaScript. The formOK variable will contain true or false; used by itself, it is a perfectly valid condition for an if statement. Notice that this.form is passed as the argument to the checkForm function. In the event handlers for fields in a form, this refers to the object for the fields themselves, and form fields have a form property referring to the form object containing the fields.
Part 4
Verifying Form Fields Using INPUT TYPE=”button” Instead of TYPE=”submit”
O
ne of the main applications of JavaScript is to perform validation of the data entered in forms. One approach is to check the data entered when the user attempts to submit the form, but to not use any actual submit buttons. The approach is simple: • In the form you want to validate, use a regular button instead of a submit button to control form submission. • In the onClick event handler of the button, call a JavaScript function to test your form when it is submitted. • In the function, check the validity of the data entered by the user in the form. If the data isn’t valid, inform the user; otherwise, submit the form.
The following task provides an example of this type of validation. If the user attempts to submit the form without entering text in a text field, an alert will state that text must be entered in the field; otherwise, the form is submitted. 1. In the header of a new HTML document, create a script block with a function called checkForm that receives the form’s object (formObj): function checkForm(formObj) { }
2. In the function, create a variable named formOK that is set to true: var formOK = true;
3. In the function, check to see if the text entered is the empty string: if (formObj.myField.value == “”) { }
4. If the field is empty, alert the user that he or she must enter text to continue and then return mouse focus to the field, and set formOK to false: window.alert(“You must enter a value in the field”); formObj.myField.focus(); formOK = false;
5. Check to see if formOK is true, and if it is, submit the form: if (formOK) { formObj.submit(); };
Working with Forms
201
6. In the body of the document, create a form named myForm with a text field named myField and a regular button—not a submit button:
Task
97
7. In the onClick event handler of the button, call the checkForm function. The final page looks like Listing 97-1. <script language=”JavaScript”> function checkForm(formObj) { var formOK = true; if (formObj.myField.value == “”) { window.alert(“You must enter a value in the field”); formObj.myField.focus(); formOK = false; } if (formOK) { formObj.submit(); } }
Listing 97-1: Validating a form when the user submits it.
8. Save the file with the name target.html and close it. 9. Open the file in a browser. 10. Try to submit the form without entering any text. An alert appears, and then focus is returned to the field.
cross-reference
•
Task 96 shows how to do validation on a submitted form using a submit button.
202
Task
98
Part 4
Validating E-mail Addresses
W
hen validating information on a form, you may want to test if the text in a text field conforms to a format of a valid e-mail address. This task illustrates how to do this. The method of validating an e-mail address that is used applies the following logic:
notes
• • • •
•
•
There are other errors you could also check for, such as two @ symbols or a misplaced dot. Strings have a length property that returns the number of characters in the string. If the string is empty, the length will be zero. The return command can be used anywhere in a function to cease processing the function and return a value. The indexOf method of string objects returns the character position of a specified string within the larger string. If the string does not occur, the index is returned as -1. The validation is divided into two functions so it can be extended to a form with multiple fields. For instance, you could validate multiple e-mail address fields by calling checkEmail multiple times from checkForm or could perform other types of validation by adding other functions and calling them from checkForm. From the form, though, you still only call checkForm. Notice that this is passed as the argument to the checkForm function. In the event handlers for a form tag, this refers to the object for the form itself.
• Check if the e-mail address is empty; if it is, the field is not valid. • Check for illegal characters, and if they occur, the field is not valid. • Check if the @ symbol is missing; if it is, the field is not valid. • Check for the occurrence of a dot; if there is none, the field isn’t valid. • Otherwise, the field is valid. The following steps create a form with a single field for entering an e-mail address. When the user submits the form, the field is validated prior to submission. If validation fails, the user is informed and submission is canceled. 1. In the header of a new HTML document, create a script block containing the function checkEmail that receives a text string. 2. In the function, check if the e-mail address has no length, and if it does, inform the user and return false from the function. 3. Next, check if the following illegal characters exist: /, :, ,, or ;. If any of these characters exist, inform the user and return false. 4. Next, check if the @ symbol exists. If not, inform the user and return false. 5. Now check if a dot exists. If not, inform the user and return false: 6. Finally, return true from the function if the e-mail address passed all the tests so that the complete function looks like Listing 98-1. 7. Create another function named checkForm that takes a form object as an argument. The function should call checkEmail and pass it the value of the field containing the e-mail address and then return the result returned by the checkEmail function: function checkForm(formObj) { return checkEmail(formObj.myField.value); }
8. In the body of the document, create a form that contains a field for entering the e-mail address and uses the onSubmit event handler to call the checkForm function:
Working with Forms
203
function checkEmail(email) {
Task
98
if (email.length == 0) { window.alert(“You must provide an e-mail address.”); return false; } if (email.indexOf(“/”) window.alert(“E-mail return false; } if (email.indexOf(“:”) window.alert(“E-mail return false; } if (email.indexOf(“,”) window.alert(“E-mail return false; } if (email.indexOf(“;”) window.alert(“E-mail return false; }
> -1) { address has invalid character: /”);
> -1) { address has invalid character: :”);
> -1) { address has invalid character: ,”);
> -1) { address has invalid character: ;”);
if (email.indexOf(“@”) < 0) { window.alert(“E-mail address is missing @”); return false; } if (email.indexOf(“\.”) < 0) { window.alert(“E-mail address is missing .”); return false; } return true; }
Listing 98-1: Function for validating an e-mail address.
9. Save the file with the name target.html, and open it in a browser. 10. Try to submit the form without a valid e-mail address and you should see an appropriate error message.
cross-reference
•
Tasks 95, 96, and 97 illustrate how to do a very simplistic form of form validation.
204
Task
99
Part 4
Validating Zip Codes
I
n some cases when validating a form, you may want to test if the text in a text field conforms to a format of a zip code. This task illustrates how to validate a zip code, using the following logic: • Check if the zip code is empty; if it is, the field is not valid.
notes
•
• • •
• •
If your form is going to be used by people from countries other than the United States, you will want to apply different rules. For example, many countries allow for characters in zip codes, as well as for lengths other than 5 and 9 digits. Strings have a length property that returns the number of characters in the string. If the string is empty, the length will be zero. The return command can be used anywhere in a function to cease processing the function and return a value. Strings have a replace method that takes the string, searches for specified text (the first argument) and replaces it with specified text (the second argument), and returns the resulting string. The charAt method returns the character at the specified index location in a string object. The onSubmit event handler used here requires attention. Instead of simply calling checkForm, you return the value returned by checkForm. Since checkForm returns true if the form is OK and false otherwise, this allows you to cancel submission if the form is not OK and allows it to continue if the form is OK.
• Remove any dashes from the zip code. • Check the length of the zip code; if it is not 5 or 9, the field isn’t valid. • Check for any nonnumeric characters; if any occur, the field is not valid. • Otherwise, the field is valid. The following steps create a form with a single field for entering a zip code. When the user submits the form, the field is validated prior to submission, and if validation fails, the user is informed and submission is canceled. 1. In the header of a new HTML document, create a script block with a function called checkZip that takes a text string as an argument. 2. In the function check if the zip code has no length, and if it does, inform the user and return false from the function. 3. Next, remove any dashes from the zip code. 4. Next, check if the length of the zip code is either 5 or 9 characters. If not, inform the user and return false from the function: 5. Now check if any character is not a number. If any character is not a number, inform the user and return false. To test for nonnumeric characters, loop through each character in the string and test it. 6. Finally, return true from the function if the zip code passed all the tests. The complete function should look like Listing 99-1. 7. Create another function named checkForm that receives a form object. The function should call checkZip, and pass it the value of the field containing the zip code, and then return the result returned by the checkZip function: function checkForm(formObj) { return checkZip(formObj.myField.value); }
Working with Forms
205
function checkZip(zip) { if (zip.length == 0) { window.alert(“You must provide a ZIP code.”); return false; }
Task
99
zip = zip.replace(“-”,””);
tip if (zip.length != 5 && zip.length != 9) { window.alert(“ZIP codes must take the form 12345 or Æ 12345-6789”); return false; } for (i=0; i “9”) { window.alert(“ZIP codes must only contain numbers.”); return false; } } return true; }
Listing 99-1: Validating ZIP Codes.
8. In the body of the document, create a form that contains a field for entering the zip code and uses the onSubmit event handler to call the checkForm function:
9. Save the file as target.html and open it in a browser. 10. Try to submit the form without a valid zip code, and you should see an appropriate error message.
•
You could validate multiple zip codes fields by calling checkZip multiple times from checkForm, or you could perform other types of validation by adding other functions and calling them from checkForm. From the form, though, you still only call checkForm.
206
Task
100
Part 4
Validating Phone Numbers
I
n some cases when validating a form, you may want to test if the text in a text field conforms to a format of a valid phone number. This task illustrates how to validate a phone number using the following logic: • Check if the phone number is empty; if it is, the field is not valid.
notes
• • •
• •
Strings have a length property that returns the number of characters in the string. If the string is empty, the length will be zero. The return command can be used anywhere in a function to cease processing the function and return a value. Strings have a replace method that takes the string, searches for specified text (the first argument) and replaces it with specified text (the second argument), and returns the resulting string. The charAt method returns the character at the specified index location in a string object. The onSubmit event handler used here requires attention. Instead of simply calling checkForm, you return the value returned by checkForm. Since checkForm returns true if the form is OK and false otherwise, this allows you to cancel submission if the form is not OK and allows it to continue if the form is OK.
• Remove phone number punctuation (parentheses, dashes, spaces, and dots). • Check the length of the phone number; if it is not 10 digits, the field is not valid. • Check for nonnumeric characters; if any occur, the field is not valid. • Otherwise, the field is valid. The following steps create a form with a single field for entering a phone number. When the user submits the form, the field is validated prior to submission. If validation fails, the user is informed and submission is canceled. 1. In the header of a new HTML document, create a script block containing the function checkPhone that receives a text string. 2. In the function, check if the phone number has no length. If it has no length, inform the user and return false from the function. 3. Next, remove any phone number punctuation from the phone number. Specifically, remove dashes, spaces, parentheses, and dots. 4. Next, check if the length of the phone number is 10 characters. If not, inform the user and return false from the function. 5. Now check if any character is not a number. If any character is not a number, inform the user and return false from the function. To test for nonnumeric characters, loop through each character in the string and test it individually. 6. Finally, return true from the function if the phone number passed all the tests. The complete function looks like Listing 100-1. 7. Create another function named checkForm that takes a form object as an argument. The function should call checkPhone, pass it the value of the field containing the phone number, and then return the result returned by the checkPhone function: function checkForm(formObj) { return checkPhone(formObj.myField.value); }
Working with Forms
207
function checkPhone(phone) {
Task
100
if (phone.length == 0) { window.alert(“You must provide a phone number.”); return false; } phone phone phone phone phone
if (phone.length != 10) { window.alert(“Phone numbers must only include a Æ 3-digit area code and a 7-digit phone number.”); return false; }
You could validate multiple phone number fields by calling checkPhone multiple times from checkForm, or you could perform other types of validation by adding other functions and calling them from checkForm. From the form, though, you still only call checkForm.
for (i=0; i “9”) { window.alert(“Phone numbers must only contain Æ numbers.”); return false; } } return true; }
Listing 100-1: The function to validate a phone number.
8. In the body of the document, create a form that contains a field for entering the phone number and uses the onSubmit event handler to call the checkForm function:
9. Save the file as target.html and open it in a browser. 10. Try to submit the form without a valid phone number, and you should see an appropriate error message.
cross-reference
•
Task 106 shows how to validate a phone number a different way—it uses regular expressions.
208
Task
101
Part 4
Validating Credit Card Numbers
T
his task illustrates how to validate a credit card number by the following logic:
• Check if the credit card number is empty; if it is, the field is not valid. • Remove any spaces.
notes
•
• •
• •
The length of a credit card number is dependent on the type of card. The type of card depends on the starting digits in the number as follows. Visa cards start with the digit 4 and have 13 or 16 digits. MasterCard cards start with 51, 52, 53, 54, or 55 and have 16 digits. American Express cards start with 34 or 37 and have 15 digits. The return command can be used anywhere in a function to cease processing the function and return a value.
• Check the length of the credit card number; valid lengths are discussed in this task. If the length is wrong, the field is not valid. • Check for nonnumeric characters; if any occur, the field is not valid. • Otherwise, the field is valid. The following steps create a form with a single field for entering a credit card number. When the user submits the form, the field is validated prior to submission. If validation fails, the user is informed and submission is canceled. 1. In the header of a new HTML document, create a script block with a function checkCreditCard that takes a text string as an argument. 2. In the function, check if the credit card number has no length. If it has no length, inform the user and return false from the function. 3. Next, remove any spaces from the credit card number.
Strings have a replace method that takes the string, searches for specified text (the first argument) and replaces it with specified text (the second argument), and returns the resulting string.
4. Now check if the length of the credit card number is appropriate for the type of card. If not, inform the user and return false.
The charAt method returns the character at the specified index location in a string object.
6. Finally, return true from the function if the credit card number passed all the tests. The complete function looks like Listing 101-1.
The onSubmit event handler used here requires attention. Instead of simply calling checkForm, you return the value returned by checkForm. Since checkForm returns true if the form is OK and false otherwise, this allows you to cancel submission if the form is not OK and allows it to continue if the form is OK.
5. Next, check if any character is not a number. If any character isn’t, inform the user and return false. To test for nonnumerics, loop through each character in the string and test it individually.
7. Create another function named checkForm that receives a form object. The function should call checkCreditCard, pass it the value of the field containing the credit card number, and then return the result returned by the checkCreditCard function: function checkForm(formObj) { return checkCreditCard(formObj.myField.value); }
8. Create a form that contains a field for entering the credit card number and uses the onSubmit event handler to call the checkForm function:
Working with Forms
209
function checkCreditCard(card) { if (card.length == 0) { window.alert(“You must provide a credit card number.”); return false; }
Task
101
card = card.replace(“ “,””);
tip if (card.substring(0,1) == “4”) { if (card.length != 13 && card.length != 16) { window.alert(“Not enough digits in Visa number.”); return false; } } else if (card.substring(0,1) == “5” && Æ (card.substring(1,2) >= “1” && card.substring(1,2) <= “5”)) { if (card.length != 16) { window.alert(“Not enough digits in MasterCard.”); return false; } } else if (card.substring(0,1) == “3” && Æ (card.substring(1,2) == “4” || card.substring(1,2) == “7”)) { if (card.length != 15) { window.alert(“Not enough digits in American Expr.”); return false; } } else { window.alert(“This is not a valid card number.”); return false; } for (i=0; i “9”) { window.alert(“CCard must only contain numbers.”); return false; } } return true; }
Listing 101-1: The completed credit card validation function.
9. Save the file with the name target.html and open it in a browser. 10. Try to submit the form without a valid credit card number, and you should see an appropriate error message.
•
You could validate multiple phone number fields by calling checkCreditCard multiple times from checkForm, or you could perform other types of validation by adding other functions and calling them from checkForm. From the form, though, you still only call checkForm.
210
Task
102
notes
• • •
•
•
Strings have a length property that returns the number of characters in the string. If the string is empty, the length will be zero. The return command can be used anywhere in a function to cease processing the function and return a value. The validation is divided into two functions so it can be extended to a form with multiple fields. For instance, you could validate multiple selection lists by calling checkList multiple times from checkForm, or you could perform other types of validation by adding other functions and calling them from checkForm. From the form, though, you still only call checkForm. Notice that this is passed as the argument to the checkForm function. In the event handlers for a form tag, this refers to the object for the form itself. Instead of simply calling checkForm, you return the value returned by checkForm. Since checkForm returns true if the form is OK and false otherwise, this allows you to cancel submission if the form is not OK and allows it to continue if the form is OK.
Part 4
Validating Selection List Choices
I
n some cases when validating a form, you may want to test if the user has made a selection in a selection list.
A common approach to selection lists is to have a blank first element so as not to force the user into a default selection and then have the user choose one of the other options. Sometimes you will want to ensure the user has chosen one of those options instead of leaving the blank first choice selected. The following steps create a form with a single selection list. When the user submits the form, the field is validated prior to submission, and if validation fails, the user is informed and submission is canceled. 1. In the header of a new HTML document, create a script block containing the function checkList that receives a text string: function checkList(selection) { }
2. In the function, check if the selected item’s value has no length. If it has no length, inform the user and return false from the function: if (selection.length == 0) { window.alert(“You must select from the list.”); return false; }
3. Finally, return true from the function if the selected item passed the test so that the complete function looks like Listing 102-1. function checkList(selection) { if (selection.length == 0) { window.alert(“You must make a selection from the Æ list.”); return false; } return true; }
Listing 102-1: The completed checkList function.
4. Create another function named checkForm that takes a form object as an argument. The function should call checkList, pass it the value of the selected item in the selection list, and then return the result returned by the checkList function: function checkForm(formObj) { return checkList(formObj.myField.value); }
Working with Forms 5. Create a form that contains a selection list and uses the onSubmit event handler to call the checkForm function:
211
Task
6. Save the file as target.html and open it in a browser. The form in Figure 102-1 appears.
Figure 102-1: A form with a selection list.
7. Try to submit the form without choosing from the selection list. You should see an appropriate error message, as in Figure 102-2.
Figure 102-2: Validating the user’s selection.
cross-reference
•
To see other ways of working with selection lists, see Tasks 82 through 86.
212
Task
103
notes
• •
•
•
The return command can be used anywhere in a function to cease processing the function and return a value. The validation is divided into two functions so it can be extended to a form with multiple fields. For instance, you could validate multiple radio button groups by calling checkRadio multiple times from checkForm, or you could perform other types of validation by adding other functions and calling them from checkForm. From the form, though, you still only call checkForm. Notice that this is passed as the argument to the checkForm function. In the event handlers for a form tag, this refers to the object for the form itself. The onSubmit event handler used here requires attention. Instead of simply calling checkForm, you return the value returned by checkForm. Since checkForm returns true if the form is OK and false otherwise, this allows you to cancel submission if the form is not OK and allows it to continue if the form is OK.
Part 4
Validating Radio Button Selections
I
n some cases when validating a form, you may want to test if the user has made a selection in a radio button group. A common approach to radio button groups is to have a radio button already selected by default. Sometimes you will want to ensure the user has chosen one of the options. The following steps create a form with a radio button group: 1. In the header of a new HTML document, create a script block containing the function checkRadio that takes a radio button: function checkRadio(buttons) { }
2. In the function, create a variable named radioEmpty that is assigned the value true. This assumes the user has not selected a radio button: var radioEmpty = true;
3. Check each radio button to see if it is selected, and adjust the value of radioEmpty accordingly: for (i=0; i
4. Check the value of radioEmpty, and if it is true, inform the user and return false from the function: if (radioEmpty) { window.alert(“You must select from the radio Æ buttons.”); return false; }
5. Finally, return true from the function if the selected item passed the test so that the complete function looks like Listing 103-1. 6. Create another function named checkForm that receives a form object. The function calls checkRadio and passes it the value of the selected radio button. The checkRadio function returns the result: function checkForm(formObj) { return checkRadio(formObj.myField.value); }
7. Create a form that contains a radio button group and that uses the onSubmit event handler to call the checkForm function:
7. Save the file and open it in a browser. The form in Figure 104-1 appears.
Figure 104-1: A form with a check box and text field.
8. Select the check box and try to submit the form without entering any text in the text field. You should see an appropriate error message, as in Figure 104-2.
Figure 104-2: Validating the user’s selection.
cross-reference
•
Tasks 91 through 94 present a number of ways to work with check boxes.
216
Task
105
notes
• • •
• •
The return command can be used anywhere in a function to cease processing the function and return a value. Strings have a length property that returns the number of characters in the string. The validation is divided into two functions so it can be extended to a form with multiple fields. For instance, you could perform other types of validation by adding other functions and calling them from checkForm. From the form, though, you still only call checkForm. Notice that this is passed as the argument to the checkForm function. In the event handlers for a form tag, this refers to the object for the form itself. The onSubmit event handler used here requires attention. Instead of simply calling checkForm, you return the value returned by checkForm. Since checkForm returns true if the form is OK and false otherwise, this allows you to cancel submission if the form is not OK and allows it to continue if the form is OK.
caution
•
Shorter passwords are easier to guess than longer ones.
Part 4
Validating Passwords
I
n some cases when validating a form, you may want to test the password provided by the user. A common approach is to ask the user to specify a password of a certain length twice to ensure he or she has entered it correctly. The following creates a form with two password fields. A check is made when the user submits to see if the two entered fields match and are at least six characters. If the checks fail, the user is informed and submission is canceled. 1. In the header of a new HTML document, create a script block containing the function checkPassword that receives two text strings: function checkPassword(password,confirm) { }
2. In the function, check if the passwords match, and if not, inform the user and return false from the function: if (password != confirm) { window.alert(“Passwords don’t match.”); return false; }
3. Next, check if the length of the string is fewer than six characters; if it is, inform the user and return false from the function: if (password.length < 6) { window.alert(“Passwords must be 6 or more characters); return false; }
4. Finally, return true from the function if the password passed the tests so that the complete function looks like this: function checkPassword(password,confirm) { if (password != confirm) { window.alert(“Passwords don’t match.”); return false; } if (password.length < 6) { window.alert(“Passwords must be 6 or more Æ characters); return false; } }
5. Create another function named checkForm that takes a form object as an argument. The function should call checkPassword and pass it both passwords, and then return the result returned by the checkPassword function:
Working with Forms function checkForm(formObj) { return checkPassword(formObj.myPassword.value, formObj.myConfirm.value); }
217
Task
105
6. Create a form that contains two password fields and uses the onSubmit event handler to call the checkForm function:
7. Save the file and open it in a browser. The form in Figure 105-1 appears.
Figure 105-1: A form with two password fields.
8. Enter two mismatched passwords and submit the form. You should see an appropriate error message, as in Figure 105-2.
cross-reference
•
Figure 105-2: Validating the user’s selection.
Passwords are sometimes stored in cookies on the users’ machines so that they don’t have to enter them every time the come to a site. To learn how to create cookies, see Task 146.
218
Task
106
Part 4
Validating Phone Numbers with Regular Expressions
I notes
•
Regular expressions are powerful but require you to have a lot of experience to become comfortable with them and master them. You can find an introductory tutorial on regular expressions at http://www. linuxpcug.org/lesso ns/regex.htm.
•
•
•
When you assign a regular expression to a variable, you are creating a regular expression object. This object has a test method that allows you to test the expression against a string that is provided as an argument to the method. The method returns true if there is a match and false otherwise. The validation is divided into two functions so it can be extended to a form with multiple fields. For instance, you could validate multiple phone number fields by calling checkPhone multiple times from checkForm or could perform other types of validation by adding other functions and calling them from checkForm. From the form, though, you still only call checkForm. Notice that this is passed as the argument to the checkForm function. In the event handlers for a form tag, this refers to the object for the form itself.
n Task 100 you saw an example of how to validate a phone number in JavaScript. At the core was the checkPhone function. Unfortunately, this function shows a long, complex, and roundabout way to validate a phone number. It does have the benefit of using only a small set of simple, common JavaScript commands and constructs such as if statements and for loops, but it requires too many steps and, therefore, is prone to error: If you get the logic wrong, the validation will be incorrect. Using regular expressions, you can greatly simplify the amount of code needed for this task. Regular expressions provide a powerful extension of the wildcard concept to allow you to specify text patterns and search for matches for those patterns. Unfortunately, regular expressions are an advanced topic beyond the scope of this task, but I will show you how to perform phone number validation using regular expressions. Use of the regular expression is simple once you have created it. You will use it in the following format: var someString =”string to test”; var regularExpression = /pattern to match/modifiers; if (regularExpression.test(someString)) { Code to execute if there is a match; }
The following steps create a form with a field to enter a phone number that is validated with regular expressions: 1. In the header of a new HTML document, create a script block containing the function checkPhone that returns a text string: function checkPhone(phone) { }
2. In the function, create a regular expression for matching against a phone number. Enter the following exactly as it is presented: var check = /^\({0,1}[0-9]{3}\){0,1}[ \-\.]{0,1}[0-9]{3}Æ [ \-\.]{0,1}[0-9]{4}$/;
3. Next, test for a failure to match this pattern against the phone number. Notice that the result returned by the test method is negated. In this way, the if statement is true only when no match is found: if (!check.test(phone)) { }
Working with Forms 4. If no match is found, inform the user and return false from the function:
219
Task
if (!check.test(phone)) { window.alert(“You must provide a valid phone number.”); return false; }
5. Finally, return true from the function if the phone number passed the test so that the complete function looks like this: function checkPhone(phone) { var check = /^\({0,1}[0-9]{3}\){0,1}[ \-\.]Æ {0,1}[0-9]{3}[ \-\.]{0,1}[0-9]{4}$/; if (!check.test(phone)) { window.alert(“Provide a valid phone number.”); return false; } return true; }
106
tip
•
The regular expression for validating a phone number is as follows: /^\({0,1}[0-9] {3}\){0,1}[ \-\.] {0,1}[0-9]{3} [ \-\.]{0,1}[0-9] {4}$/
6. Create another function named checkForm that takes a form object as an argument. The function should call checkPhone and pass it the value of the field containing the phone number and then return the result returned by the checkPhone function: function checkForm(formObj) { return checkPhone(formObj.myField.value); }
7. In the body of the document, create a form that contains a field for entering the phone number and uses the onSubmit event handler to call the checkForm function:
8. Save the file as target.html and open it in a browser.
cross-references
•
9. Try to submit the form without a valid phone number, and you should see an appropriate error message.
•
In Task 100 you saw an example of how to validate a phone number in JavaScript without using regular expressions. Task 111 shows how to use regular expressions to validate numeric values.
220
Task
107
note
•
The onClick method can be used with the different HTML form controls to do something if the user has clicked on it. Here you use it with plain buttons that, without the event handler, would not perform any action.
Part 4
Creating Multiple Form Submission Buttons Using INPUT TYPE= ”button” Buttons
O
n some Web sites you will see a form with multiple buttons that appear to be submission buttons. A common example of this is a login form: One button logs the user in, one button creates a new user account using the username entered by the user, and the third e-mails the user’s password to the user in case he or she has forgotten it. In all cases, the same form is being used, but the form is being submitted to a different URL. By default, submit buttons always submit the form to the URL specified in the
action attribute of the form tag regardless of how many appear in the form.
The way around this is to use regular buttons for the extra buttons and to use the onClick event handlers for these buttons to reset the target URL for the form
and then submit the form. Form objects have an action property that indicates the URL where the form will be submitted. You can change this URL by assigning a new URL to the property: document.formName.action = “new URL”;
Form objects also have the submit method, which submits the form just as if the user had clicked on a submit button.
The following steps use these principles to create a login form with three buttons just like the one described previously: 1. Create a new document in your preferred browser. 2. In the body of the document, create a form; as the action, specify the page where the form should be submitted if the user is logging in:
3. In the form create a username field: Username:
4. In the form create a password field: Password:
Working with Forms
221
5. Create a submit button for the login process:
Task
107
6. Create a regular button for users who want to register new accounts:
7. In the onClick event handler for the button, set the action URL to the register page and then submit the form:
8. Create a regular button for users who want to retrieve their passwords:
9. In the onClick event handler for the button, set the action URL to the page for retrieving passwords and then submit the form. The final page looks like Listing 107-1.
Listing 107-1: Multiple buttons for submitting a form.
10. Save the file and open it in your browser. You should see a form with multiple buttons for submitting to different pages.
cross-references
• •
The onClick method is used with many of the tasks in this section. Task 105 shows you how to validate a password using JavaScript.
222
Task
108
note
•
The onClick method can be used with the different HTML form controls to do something if the user has clicked on it.
Part 4
Reacting to Mouse Clicks on Buttons
A
common use of JavaScript, as evidenced by many of the tasks in this section of the book, is to perform JavaScript tasks when the user clicks on a form button. You do this using the onClick event handler of a form button:
This task illustrates using the onClick event by creating a form with a button. When the user clicks on the button, a dialog box is displayed informing the user that he or she has clicked on the button. 1. Create a new HTML document in your preferred editor. 2. Create a form in the body of the document:
3. In the form, create a regular button:
4. In the button, use an onClick event handler to display an alert dialog box when the user clicks on the button:
Working with Forms 5. Save the file as target.html and close it.
223
Task
6. Open the file in a browser, and a button appears, as shown in Figure 108-1.
108
Figure 108-1: A button in a form.
7. Click on the button, and the dialog box in Figure 108-2 appears.
cross-references
•
Figure 108-2: Reacting when the user clicks on the button.
•
The onClick method is used with many of the tasks in this section. You can alert a user as a response to an onClick event. See Task 25 for more information on alerting a user.
224
Task
109
notes
• •
By default, these image buttons function as submit buttons: They will submit the form just as if you had used instead. While you can use any image format, JPG, GIF, and PNG are the most portable.
Part 4
Using Graphical Buttons in JavaScript
H
TML provides a form element type called image that lets you place images within a form as elements. You can apply event handlers to these images to make them a dynamic, integral part of your forms. To include an image in a form as a form element, use the image value for the type attribute of the input tag:
As with other form buttons, you can specify event handlers in image buttons. For instance, the following button uses an onClick event handler to specify JavaScript code to execute when the user clicks on the image:
To illustrate the user of graphical buttons, the following form uses an image as a submit button. When the user clicks the button, an alert dialog box is displayed before the form is submitted. 1. Create or select an image file you will use for the image button. 2. Create a new HTML document in your preferred editor. 3. In the body of the document, create a form. 4. Place any fields you want in the form; do not include a submit button:
5. Create an image tag that references the image from Step 1 earlier:
6. Use an onClick event handler for the image to display a dialog box when the user clicks on the image:
225
Task
109
7. Save the file as login.html and close it. 8. Open the file in a browser. The form in Figure 109-1 appears, including the image button.
tip
•
You can create images to be used as buttons in any graphical program. This includes Microsoft Paint.
Figure 109-1: A form with an image button for submission.
9. Click on the image and the dialog box in Figure 109-2 appears.
cross-reference
•
Figure 109-2: Reacting to users clicking on the image.
See Task 60 to learn how to detect clicks on an image in a form versus using an image as a button.
226
Task
110
Part 4
Controlling the Form Submission URL
W
hen you create a form in HTML, you specify what page the form should be submitted to with the action property of the form tag:
2. In the form, create any fields you need, as well as a submit button:
caution
•
In the example, the form is directed, or redirected, to either target.html or alternate.html. If these forms don’t exist, you will get an error or a blank screen. You can change these URLs to any other URL (see Figure 110-1).
3. In the submit button, use the onClick event handler to display the action URL in a dialog box before submitting the form:
6. Save the file and close it. 7. Open the file in a browser and you now see the form you created. 8. Submit the form without clicking on the link. It will submit to the original URL, as illustrated in Figure 110-1.
cross-reference Figure 110-1: Submitting the form to the original URL.
9. Reload the file in a browser. Click on the link and then submit the form, and the form will submit to the new URL.
•
Learn more about submitting forms in Task 224.
228
Task
111
Part 4
Validating a Numeric Text Field with Regular Expressions
S notes
•
•
When you assign a regular expression to a variable, you are creating a regular expression object. This object has a test method that allows you to test the expression against a string that is provided as an argument to the method. The method returns true if there is a match and false otherwise. The regular expression for validating a numeric value is as follows: /^[0-9]+\.? [0-9]+$/;
•
•
ometimes you will have a form where you need to limit the text entered into a text field to only particular characters. For instance, you might want to limit the text to numbers. Using regular expressions, you can easily perform this check when the user submits the form. Regular expressions provide a powerful extension of the wildcard concept to allow you to specify text patterns and search for matches for those patterns. Unfortunately, regular expressions are an advanced topic beyond the scope of this book; however, this task shows how to perform number validation using regular expressions. The following steps create a form with a field to enter a phone number that is validated with regular expressions: 1. In the header of a new HTML document, create a script block containing the function checkNumber that receives a text string: <script language=”JavaScript”> function checkNumber(number) { }
Regular expressions are powerful but require you to have a lot of experience to become comfortable with them and master them. You can find an introductory tutorial on regular expressions at http://www.
2. In the function, create a regular expression for matching against a numeric value:
linuxpcug.org/ lessons/regex.htm.
3. Next, test for a failure to match this pattern against the number:
Notice that you negate the result returned by the test method. In this way, the if statement is true only when no match is found.
var check = /^[0-9]+\.?[0-9]+$/;
if (!check.test(number)) { }
4. If no match is found, inform the user and return false from the function: if (!check.test(number)) { window.alert(“You must provide a valid number.”); return false; }
5. Finally, return true from the function if the number passed the test, so that the complete function looks like this: function checkNumber(number) { var check = /^[0-9]+\.?[0-9]+$/; if (!check.test(number)) { window.alert(“You must provide a valid number.”);
Working with Forms return false; } return true;
229
Task
111
}
6. Create another function named checkForm that takes a form object as an argument. The function should call checkNumber and pass it the value of the field containing the number and then return the result returned by the checkNumber function: function checkForm(formObj) { return checkNumber(formObj.myField.value); }
7. Create a form that contains a field for entering the phone number and uses the onSubmit event handler to call the checkForm function:
8. Save the file and open it in a browser. The form in Figure 111-1 appears.
cross-reference
•
Figure 111-1: A form with a text field.
9. Try to submit the form without a valid number, and you should see an appropriate error message.
Task 106 presents the code for using regular expressions to validate a phone number.
230
Task
112
notes
• • •
• •
Strings have a length property that returns the number of characters in the string. If the string is empty, the length will be zero. The charCodeAt method returns the Unicode representation of the character specified by an index in the string. Arrays have a property called length that returns the number of items in an array, and it is used in this loop. Since arrays are zeroindexed, an array with length 5 (which contains five elements) would contain elements with indexes from 0 to 4. This is why you loop until i is less than, and not less than or equal to, the length of the array. The keyword this is used to pass the form to the function. In event handlers of the form itself, this refers to the object for the form itself. An alert has been added to the onSubmit event handler so that you can see the value of the encrypted text field before submitting the form. This allows you to check if the encryption is working. You wouldn’t include this in a live application.
Part 4
Encrypting Data before Submitting It
B
y encrypting the data in a form before submitting it across the Internet, you add a small layer of privacy to the data being transmitted. This can be achieved in JavaScript if desired by passing each form field through an encryption function before submitting the form. The principle is simple: 1. In the form tag, use onSubmit to call the encryption function before submitting the form. 2. The encryption form should work through each field in the form and encrypt the value of each field. The encryption process can use the elements property of the form tag to easily access all the fields in a form without knowing what those fields will be in advance. This property is an array containing one entry for each object in the form. Therefore, the first field in the form can be referenced as: document.formName.elements[0]
The following task creates a form, which is encrypted using a simple algorithm before it is transmitted. The encryption algorithm simply converts each letter in the form’s fields to their numeric Unicode equivalents: 1. In the header of a new HTML document, create a script block with a function named encrypt. This function should take a text string as a single argument. This string will be encrypted: <script language=”JavaScript”> function encrypt(item) { }
2. In the function, create a variable named newItem that will hold the encrypted string. Initially this should be an empty string: var newItem = “”;
3. Loop through each character in the original text string: for (i=0; i < item.length; i++) { }
4. For each character in the string, use the charCodeAt method of the string object to obtain the numerical Unicode representation of the letter and add it to the newItem string. Note that a dot is added after each character. This separates the characters cleanly to make it easier to decrypt later.
Working with Forms 5. Return the encrypted string from the function. The encrypt function should look like the following:
231
Task
function encrypt(item) { var newItem = “”; for (i=0; i < item.length; i++) { newItem += item.charCodeAt(i) + “.”; } return newItem; }
tips
•
6. Create a second function named encryptForm that takes a form object as an argument. 7. In the function, loop through the elements array. For each element, encrypt the value of the field with the encrypt function, and store the result back into the field’s value: function encryptForm(myForm) { for (i=0; i < myForm.elements.length; i++) { myForm.elements[i].value = encrypt(myForm.elements[i].value); } }
8. In the body of the document, create a form with any needed fields. Use the onSubmit event handler to submit the form to the encryptForm function:
112
•
The idea of encrypting data in JavaScript has limited utility in terms of security. Because JavaScript code can be read by the user by viewing the source code in your browser, anyone can determine how you are encrypting the form and can easily decrypt the data. However, this approach does provide a veil of privacy; after the user submits the form, the data that is transmitted across the Internet is not immediately apparent to anyone intercepting data as it flows across the Internet. This can be helpful in some applications. This isn’t real encryption; instead, it is just illustrative of how to tie an encryption function into a form submission process. To implement another encryption algorithm would require you to write your own encryption function and then call that function when needed.
9. Save the file and open it in a browser. 10. Click on the submit button. The form is encrypted, and the encrypted value of the field is displayed in a dialog box before the form is submitted.
cross-reference
•
Notice the short form concatenation operator being used here: +=. Using a += b is the same as a = a + b. For more on doing math in JavaScript, see Task 14
232
Task
113
Part 4
Using Forms for Automatic Navigation Jumping
S notes
•
•
ometimes you will see form selection lists used as a mechanism for providing navigation to different URLs for a page. The drop-down list will include multiple URLs, as shown in Figure 113-1. When the user selects an entry in the list, the browser is automatically sent to that URL.
The value of window. location determines what window will be opened when it is called. Setting this to the value of a URL causes the specified URL to be opened. Setting the value to # causes the current window to be used. An alternative to jumping to a new URL at the time the selection list changes is to use the selection list in combination with a button. When the user clicks the button, the browser would jump to the URL that is currently selected in the list.
Figure 113-1: A selection list for navigating to URLs.
This navigation is achieved using two principles: • The onChange event handler can detect changes in the selected item in a selection list. • Setting window.location to a new URL redirects the browser. The following task shows how to build a simple selection list with URLs. JavaScript code will redirect the user to the selected URL. 1. Create a form in the body of a new document. 2. Create a selection list with the URLs you want to allow the user to navigate to: <select name=”url”>