Paul McFedries' Web Home


The cover of Special Edition Using JavaScript Special Edition Using JavaScript

Table of Contents


Part 1—Getting Started with JavaScript

Chapter 1—An Overview of JavaScript
JavaScript: Controlling the Machine
What Is a Programming Language?
Is JavaScript Hard to Learn?
What Can You Do with JavaScript?
What Can't You Do with JavaScript?
Cross-Browser Concerns

Chapter 2—Creating Your First Scripts
What Do You Need to Get Started?
The Text Editor
The Browser
Basic Script Construction
The <script> tag
Handling Browsers that Don't Support JavaScript
Handling Browsers with JavaScript Turned Off
Where Do You Put the Tag?
Example #1: Displaying a Message to the User
More JavaScript Examples
Example #2: Writing Data to the Page
Example #3: A JavaScript Function
Example #4: Handling a JavaScript Event
Adding Comments to Your Code
Creating External JavaScript Files
Debugging and Troubleshooting Script Problems
Seeing Script Errors
JavaScript is Case-Sensitive
Make Sure JavaScript Is Turned On

Part 2—Programming Fundamentals

Chapter 3—Understanding Variables
What is a Variable?
Declaring a Variable
Storing a Value In a Variable
Using Variables In Statements
Naming Variables: Rules and Best Practices
Rules for Naming Variables
Ideas for Good Variable Names
Understanding Literal Data Types
Working with Numeric Literals
Exponential Notation
Octal and Hexadecimal Integer Values
Working with String Literals
Using Quotation Marks Within Strings
Understanding Escape Sequences
Understand Boolean Literals

Chapter 4—Working with Functions
What Is a Function?
The Structure of a Function
Where Do You Put a Function?
Using a Function
Passing Values to Functions
Returning a Value From a Function
Understanding Local Versus Global Variables
Working with Local Scope
Working with Global Scope
Using Recursive Functions
Debugging and Troubleshooting Script Problems
Avoiding Infinite Recursion

Chapter 5—Building JavaScript Expressions
What Is an Expression?
Understanding Expression Structure
Building Numeric Expressions
A Quick Look at the Arithmetic Operators
Using the Addition (+) Operator
Using the Increment (++) Operator
Using the Subtraction and Negation (-) Operators
Using the Decrement (--) Operator
Using the Multiplication (*) Operator
Using the Division (/) Operator
Using the Modulus (%) Operator
Using the Arithmetic Assignment Operators
Building String Expressions
Building Comparison Expressions
The Comparison Operators
Using the Equal (==) Operator
Using the Not Equal (!=) Operator
Using the Greater Than (>) Operator
Using the Less Than (<) Operator
Using the Greater Than Or Equal (>=) Operator
Using the Less Than Or Equal (<=) Operator
The Comparison Operators and Data Conversion
Using the Identity (===) Operator
Using the Non-Identity (!==) Operator
Using Strings In Comparison Expressions
Using the Conditional (?:) Operator
Building Logical Expressions
The Logical Operators
Using the AND (&&) Operator
Using the OR (||) Operator
Using the NOT (!) Operator
Advanced Notes On the && and || Operators
Understanding Operator Precedence
The Order of Precedence
Controlling the Order of Precedence

Chapter 6—Controlling Your Code I: Testing
Using if() to Make True/False Decisions
Using if()...else to Handle a false Result
Making Multiple Decisions
Using the AND (??) and OR (||) Operators
Nesting Multiple if() Statements
Using the switch() Statement
Debugging and Troubleshooting Script Problems
Giving switch() a Break

Chapter 7—Controlling Your Code II: Looping
What Is Looping and Why Does Your Code Need It?
Using while() Loops
Using for() Loops
Using do...while() Loops
Controlling Loop Execution: break and continue
Exiting a Loop: Using the break Statement
Bypassing Loop Statements: Using the continue Statement
Debugging and Troubleshooting Script Problems
Avoiding Infinite Loops
Using Infinite Loops

Chapter 8—Working with Objects
What Is an Object?
The JavaScript Object Hierarchy
The Window Object and Its Hierarchy
Other Built-In JavaScript Objects
Manipulating Object Properties
Referencing a Property
Some Objects Are Properties
Changing the Value of a Property
Using for()...in to Loop through Object Properties
Working with Object Methods
Activating a Method
Using with() to Shorten Object Expressions

Chapter 9—Handling Events
Understanding Events
Constructing Event Handlers
Step 1: Add the Event Handler Setup Attribute
Step 2: Set the Value of the Attribute
Setting Up Event Handlers as Object Properties
Using this to Refer to an Event's Object
Using the JavaScript Events
Handling When an Object Gets and Loses the Input Focus
Getting the Focus: The Focus Event
Losing Focus: The Blur Event
The Change Event: Handling Modified Form Data
Handling Keyboard Events
Getting Specific Key Values
Handling Mouse Events
The Click Event
The DblClick Event
The MouseDown and MouseUp Events
Determining Which Button Was Used
Debugging and Troubleshooting Script Problems
Avoiding Infinite Loops with the Blur and Focus Events

Chapter 10—Working with Arrays
What is an Array?
Declaring an Array
Populating an Array with Data
Declaring and Populating an Array at the Same Time
Using a Loop to Populate an Array
Using a Loop to Work with Array Data
Creating Multidimensional Arrays
Using the Array Object
The Array Object's Properties
The Number of Elements: length
Adding New Properties and Methods: prototype
The Array Object's Methods
Concatenating to Create a New Array: concat()
Creating a String From an Array's Elements: join()
Removing the Last Element: pop()
Adding Elements: push()
Reversing the Order of an Array's Elements: reverse()
Removing the First Element: shift()
Returning a Subset of an Array: slice()
Ordering Array Elements: sort()
Removing, Replacing, and Inserting Elements: splice()
Inserting Elements at the Beginning of an Array: unShift()
Debugging and Troubleshooting Script Problems
Using prototype to Simulate the Netscape-Only Methods
Simulating the pop() Method
Simulating the push() Method
Simulating the shift() Method
Simulating the splice() Method
Simulating the unshift() Method

Chapter 11—Interacting with the User
Why Interact At All?
Displaying Messages Using the alert() Method
How the Alert Boxes Appear in Different Browsers
Asking Questions Using the confirm() Method
Getting Input Using the prompt() Method
How the Prompt Boxes Appear in Different Browsers
Debugging and Troubleshooting Script Problems
Don't Overdo It

Chapter 12—Debugging Your Code
What Is a Bug?
Understanding the Various Types of Errors
Syntax Errors
Runtime Errors
Logic Errors
A Debugging Strategy
Look for the Top 10 Most Common Errors
Display Expression Values
Running Individual JavaScript Statements
Using Alerts to Display Values
Using a Separate Window to Display Values
Display the Values of Object Properties
More Debugging Strategies
The Top 10 Most Common JavaScript Error Messages

Part 3—Using JavaScript's Basic Objects

Chapter 13—Dealing with Dates and Times: The Date Object
Understanding JavaScript Dates
Arguments Used with the Date Object
Working with the Date Object
Specifying the Current Date and Time
Specifying Any Date and Time
Extracting Information About a Date
Converting getMonth() Into a Month Name
Converting getDay() Into a Day Name
Setting the Date
Determining the Day of the Week for Any Date
Performing Date Calculations
Determining a Person's Age
Performing Complex Date Calculations
Calculating an Age In Weeks, Days, and So On
Calculating the Days Between Two Dates
Other Date Object Methods

Chapter 14—Working with Numbers: The Math Object
How JavaScript Handles Numbers
A Quick Look at the Number Object
Converting Between Strings and Numbers
The parseInt() Function
The parseFloat() Function
The eval() Function
The Math Object
Properties of the Math Object
Methods of the Math Object
Rounding Numbers
The ceil() Method
The floor() Method
The round() Method
Rounding a Number to a Specified Number of Decimals
Performing Financial Calculations
Calculating Loan or Mortgage Payments
Calculating a Loan Balance
Calculating the Future Value of an Investment
Calculating Required Investment Deposits
Taking Inflation Into Account
Generating Random Numbers

Chapter 15—Manipulating Text: The String Object
Strings and the String Object
Determining the Length of a String
String Object Methods
Formatting Strings
Finding Substrings
Methods that Extract Substrings
The charAt() Method
The slice() Method
The split() Method
The substr() Method
The substring() Method
Understanding the Differences Between splice(), substr(), and substring()
A Few More String Object Methods
Programming a Library of Common String Functions
Extracting Characters From the Left: The left() Method
Extracting Characters From the Right: The right() Method
Trimming Extra Spaces: The trim() Method
Converting a String to Title Case: The titleCase() Method
Replacing One Substring With Another
Formatting a Number with Thousands Separators

Chapter 16—Controlling the Browser: The Navigator Object
About the Navigator Object
Determining the User's Browser Information
Determining the Browser Name
Determining the Browser Version
Understanding the userAgent Property
Determining the Browser Name, Part 2
Determining the Operating System
Putting It All Together: The Browser Sniffer

Part 4—Working with Browser Windows

Chapter 17—Understanding the Window Object
Revisiting the Window Object Hierarchy
Referencing the Window Object
Window Dimensions and the Screen Object
Displaying Messages In the Status Bar
Displaying a Custom Link Message
Setting Up a Default Status Bar Message
Working with JavaScript Timeouts and Intervals
Using a Timeout to Perform a Future Action Once
Using an Interval to Perform a Future Action Repeatedly
Emulating setInterval() with setTimeout()
Creating a Scrolling Status Bar Message

Chapter 18—Opening, Moving, and Sizing Windows
Opening a Window
The JavaScript Way: The window.open() Method
The Simplest window.open() Method Syntax
Controlling the Size and Position of the New Window
Displaying Toolbars, Menu Bars and Other Window "Chrome"
Referencing the Page That Opened a Window
Closing a Window
Moving a Window
Moving a Window To a Specific Spot
Moving a Window By a Specified Amount
Resizing a Window
Resizing a Window to a Specific Size
Resizing a Window By a Specified Amount

Chapter 19—JavaScript Surfing: The Location and History Objects
Surfing Under Script Control
Using the Location Property to Change the Displayed Page
Location Object Properties
Surfing Using the Location Object's Properties
Using search to Pass a Parameter to Another Web Page
Methods of the Location Object
Reloading the Page
Replacing the Page In the History List
Programmed Surfing with the History Object
Methods of the History Object
Simulating the Back Button
Simulating the Forward Button
Returning to Any Page In the History List

Chapter 20—Manipulating Frames
Understanding Frame References
Parent-to-Child References
Child-to-Parent References
Child-to-Child References
Referencing Nested Frames
Grandparent-to-Grandchild References
Uncle-to-Nephew References
Grandchild-to-Grandparent References
Nephew-to-Uncle References
The top Property
Programming Frames
Loading a Page Into a Frame
Updating Multiple Frames with One Link
Navigating to the Top and Bottom of a Frame
"Deframing" a Page: Getting Out of Someone Else's Frames
"Reframing" a Page: Putting a Child Page Back Inside a Frameset
Working with Another Frame's Variables and Functions
Synchronizing Frame Loading

Chapter 21—JavaScript Project: Setting Up a Password-Protected Page
Web Page Security Issues
A First Attempt at Password Protection
Prompting for a Password
Converting the Password and Filename Into Codes
The First Real Solution: A Trick for Hiding the Password
Trying Out the Trick
Making the Script a Bit More User-Friendly
Solving the "404 Not Found" Problem
Handling Multiple Users and Passwords
Debugging and Troubleshooting Script Problems
Thwarting CGI Directory Listings
Assessing the Security of JavaScript Passwords

Part 5—Working with the Document Object

Chapter 22—Understanding the Document Object
Structure of the Document Object
Properties of the Document Object
Changing Document Colors
Using Color Names
Using RGB Values
Methods of the Document Object
Writing Data to the Page
Writing to a Document at Startup
Writing Browser-Specific Code
Writing to a Document In Another Window

Chapter 23—Programming Links, Anchors, and Image Maps
Working with the Link Object
Using Functions In Place of URLs In a Link
Referencing a Link Object
Link Object Properties
Link Object Events
The Click Event
The MouseOver and MouseOut Events
Working with the Anchor Object
Referencing an Anchor Object
Anchor Object Properties

Chapter 24—Working with Images and Mouseovers
Working with the Image Object
Referencing an Image Object
Properties of the Image Object
Changing the Image Source
Cycling Through a Series of Images
Creating a "Running" Digital Clock
Preloading Images
Preloading Images for Animation
Loading an Image Into a Custom-Sized Window
Handling Image Object Events
The Abort Event: When an Image Download Is Cancelled
The Error Event: When an Image Fails to Load
The Load Event: When an Image Loads Completely
Creating Mouseover Effects
The Simplest Mouseover
Preloading Mouseover Images
Using a Text Link Mouseover to Change an Image

Chapter 25—Creating and Using Cookies
Saving State: The Need for Truly Global Variables
What is a Cookie?
Advantages of Cookies
Disadvantages of Cookies
Setting Cookie Data
The Simplest Case: Setting the Cookie Name and Value
Getting the Cookie Value
Handling Multiple Cookies
Adding an Expiration Date
Specifying the Path
Setting Other Cookie Data
Handling All the Cookie Parameters
Deleting a Cookie
Advanced Cookie Operations
Storing Multiple Values in a Single Cookie
Encoding Cookie Values
Encrypting Cookie Values
Debugging and Troubleshooting Script Problems
Building a Stronger Key

Chapter 26—JavaScript Project: Creating a Navigation Tree
The Need for Navigation
Stage 1: Designing and Creating the Menu Objects
Stage 2: Writing a Basic Menu
Stage 3: Expanding and Collapsing the Menu Items
Stage 4: Adding Graphics and Other Interface Enhancements

Part 6—Working with Forms

Chapter 27—Understanding the Form Object
Structure of the Form Object
Referencing a Form Object
Form Object Properties
Understanding Form Fields
Referencing a Form Field
Common Form Field Properties
Looping Through Form Fields
Passing Form and Field Objects to a Function
Programming Buttons
Accepting or Rejecting a Submit
First Try: The Submit Object's Click Event
A Better Way: The Form Object's Submit Event
Accepting or Rejecting a Reset
Using a Button to Process Other Code
Forcing a Submit or Reset: The submit() and reset() Methods
Restricting the Number of Form Submissions

Chapter 28—Programming Form Fields
Now For Some Real Form Programming
Programming Text Fields
The Text Object
The Textarea Object
The Password Object
The FileUpload Object
The Hidden Object
Getting a Text Field Value
Setting a Text Field Value
A More Ambitious Example: A Mortgage Calculator
Making a Text Field Read-Only
Programming Checkboxes
Getting the Checkbox State
Setting the Checkbox State
Using a Checkbox to Disable Form Fields
Controlling the Number of Activated Checkboxes
Programming Radio Buttons
Referencing Radio Buttons
Getting a Radio Button State
Setting the Radio Button State
Programming Selection Lists
The Select Object
The Option Object
Referencing an Option In a Selection List
Getting the Currently Selected List Option
Getting Multiple Selected Options
Setting the Selected List Option
Creating a Navigation List
Modifying a List On-the-Fly

Chapter 29—Performing Form Validation
The Need for Browser-Based Validation
Displaying the Form Data for Confirmation
Making Form Fields Mandatory
First, a Trick: Adding Custom Properties to an Object
Checking for Empty Fields
Checking for Fields that Contain Only Whitespace Characters
Validating the Field Data Type
Checking for Alphabetic Data
Checking for Integer Data
Checking for Signed Integer Data
Checking for Floating-Point Data
Checking for Invalid Data
Checking a Numeric Range
Removing Extraneous Characters from a Field
Checking Alphanumeric Data Against a Mask
Checking an Email Address

Chapter 30—JavaScript Project: Creating a Shopping Cart
Making the Move to E-Commerce
Creating the Project Data
Designing the Data
The Database of Items for Sale
The User's Personal Details
Creating the Database Using JavaScript
Creating the Custom database_record Object
Making the Database
Storing the Orders In a Cookie
An Overview of the Project
Customizing this Project For Your Own Use
Setting Up Your Store
Understanding the Shopping Cart
Using the Shopping Cart
Creating the Cart On-the-Fly Using JavaScript
The Shopping Cart's Buttons
The Recalculate Order Button
The Delete All Items Button
The Continue Shopping and Proceed to Checkout Buttons
Understanding the Personal Details Page
Understanding the Personal Details Data
Initializing the Personal Details Page
Validating the Personal Details
Understanding the Credit Card Details Page
Writing the Invoice
Initializing and Validating the Credit Card Details

Part 7—Working with Dynamic HTML

Chapter 31—A Brief Overview of Dynamic HTML
The Need for Truly Dynamic Pages
Dynamic HTML: Scripting for Control Freaks
DHTML Today: A Mess!
The Big DHTML Picture
An Introduction to the Document Object Model
The DOM: A Hierarchy of Nodes

Chapter 32—Version 5 DHTML: The W3C's Document Object Model
Dealing with Nodes in the DOM
Specifying a Node
Specifying a Child Node
Specifying a Parent Node
Specifying a Sibling Node
Getting Node Information
Getting the Name of the Node
Getting the Node Type
Getting the Value of a Node
Determining Whether a Node Has Children
Working with Elements
Specifying an Element ID
Specifying Elements By Tag Name
Returning the Tag Name
Working with Tag Attributes
Getting and Changing Tag Attributes
Adding an Attribute to a Tag
Removing an Attribute from a Tag
Working with Non-Standard Attributes
Working with Styles
Changing Inline Styles
Changing the Style Class
Working with Text Nodes
An Example: A Text Fader
Changing the Structure of the Document Hierarchy
Creating an Element
Creating a Text Node
Appending a Child Node
Inserting a Child Node
Replacing a Child Node
Cloning a Child Node
Removing a Child Node

Chapter 33—Version 4 DHTML: Proprietary Object Models
The Pre-DOM Dark Ages
Internet Explorer 4's DHTML Document Object Model
Specifying Elements
Specifying a Single Element
Shortcuts to the Document Title and Body
Specifying an Element Collection
Getting and Setting Tag Attribute Values
Other DHTML DOM and W3C DOM Equivalents
Working with Text
The Netscape Navigator 4 Object Model
Programming Layers
Specifying an Unnested Layer
Getting to the Layer's Content
Specifying a Nested Layer

Chapter 34—Cross-Browser Solutions: Detection and Generic Functions
Cross-Browser Issues
What Does "Cross-Browser" Mean?
Handling Different Browsers
Using Inline Branching
Using Page Branching
Using a Custom Object Front-End
Detecting the User's Browser
Using Browser Version Detection
Using Object Detection
Creating a Custom Object Front-End
Examining the Object
Cross-Browser Style References
Creating the Custom Objects
Using a Custom Object
Defining the Custom Object Methods
The left() Method
The right() Method
The top() Method
The bottom() Method
The width() Method
The height() Method
The visibility() Method
The zIndex() Method
The move_to() Method
The move_by() Method
The set_left() Method
The set_top() Method
The set_width() Method
The set_height() Method
The set_visibility() Method
The set_zIndex() Method
The move_above() Method
The move_below() Method
The set_backgroundColor() Method
The set_backgroundImage() Method
The set_html() Method
The get_clip_top() Method
The get_clip_right() Method
The get_clip_bottom() Method
The get_clip_left() Method
The get_clip_width() Method
The get_clip_height() Method
The resize_clip_to() Method
The resize_clip_by() Method
Other Cross-Browser Functions
The get_mouse_x() Function
The get_mouse_y() Function
The get_client_width() Function
The get_client_height() Function
The get_client_scroll_left() Function
The get_client_scroll_top() Function

Chapter 35—Cross-Browser DHTML Examples
Some Notes Before We Begin
Cross-Browser DHTML Text Examples
A Cross-Browser Tooltip
Scrolling Text Horizontally
A Basic Horizontal Text Scroller
Understanding Clip-Based Animation
Understanding Clipping Regions
The Scrolling Technique: Move and Clip
Scrolling Text from the Far Right
Adding Loops and "Scroll" Versus "Slide" Behavior
Scrolling Text Vertically
Basic Vertical Text Scrolling
Vertical Scrolling Text with Loops and Behaviors
Vertical Scrolling with Multiple Messages
Cross-Browser DHTML Image Examples
Creating a Logo that Stays In Place As the User Scrolls
Setting Up a Cross-Browser DHTML Slide Show
A Simple Slide Show
Automatically Changing the Slides
Using a Transition to Remove an Image
Adding Random Transitions to the Slide Show
Adding a Wipe Transition to the Incoming Slide

Appendix A—JavaScript Tools for Debugging Scripts
Using the Microsoft Script Debugger
Pausing a Script
Entering Break Mode at the Beginning of a Script
Entering Break Mode from an Error Dialog Box
Setting a Breakpoint
Exiting Break Mode
Stepping Through a Script
Stepping Into a Script or Function
Stepping Over a Function
Stepping Out of a Function
Monitoring Script Values
Executing Statements in the Command Window
Using Netscape's JavaScript Debugger
Pausing a Script
Entering Break Mode at the Beginning of a Script
Entering Break Mode from an Error Dialog Box
Interrupting a Running Script
Setting a Breakpoint
Setting a Conditional Breakpoint
Clearing a Breakpoint
Exiting Break Mode
Stepping Through a Script
Stepping Into a Script or Function
Stepping Over a Function
Stepping Out of a Function
Monitoring Script Values
Monitoring Values Using the Console Pane
Executing Statements in the Console Pane
Adding a Watch Expression
Working with Watch Expressions

Appendix B—JavaScript Reserved Words and Keywords

Appendix C—Working with Regular Expressions
Pattern Matching the String Object Way
Pattern Matching the Regular Expression Way
Building Regular Expressions
Special Symbols Used In Regular Expressions
\d[md]Matching Digits
\D[md]Matching Non-Digits
\w[md]Matching Letters, Digits, and Underscores
\W[md]Matching Everything but Letters, Digits, and Underscores
.[md]Matching Any Character Except Newline
\s[md]Matching a Whitespace Character
\S[md]Matching a Non-Whitespace Character
[][md]Matching a Set of Characters
[^][md]Matching Everything But a Set of Characters
\b[md]Matching On a Word Boundary
\B[md]Matching Not On a Word Boundary
?[md]Matching if a Character Appears Once or Not at All
*[md]Matching if a Character Appears Zero or More Times
+[md]Matching if a Character Appears One or More Times
{n}[md]Matching if a Character Appears n Times
{n,}[md]Matching if a Character Appears n or More Times
{n,m}[md]Matching if a Character Appears Between n and m Times
^[md]Matching at the Beginning of a String
$[md]Matching at the End of a String
|[md]Matching One Pattern or Another
Summarizing the Regular Expression Symbols
Example: Matching an Email Address
Using Regular Expressions In Your JavaScript Code
Checking the Pattern Using the test() Method
The search() Method
The replace() Method
Return to Special Edition Using JavaScript home page
Copyright © 1995-2008 Paul McFedries and Logophilia Limited