Professional Documents
Culture Documents
TM
From
TM
®
&
IDG Books Worldwide, Inc.
An International Data Group Company
IDG
BOOKS Foster City, CA • Indianapolis • Chicago • New York
JavaScript™: Your visual blueprint for building dynamic Web pages Trademark Acknowledgments
IDG is the world’s leading IT media, research and exposition company. Founded in 1964, IDG had 1997 revenues of $2.05 billion and has
more than 9,000 employees worldwide. IDG offers the widest range of media options that reach IT buyers in 75 countries representing 95%
of worldwide IT spending. IDG’s diverse product and services portfolio spans six key areas including print publishing, online publishing,
expositions and conferences, market research, education and training, and global marketing services. More than 90 million people read one
or more of IDG’s 290 magazines and newspapers, including IDG’s leading global brands — Computerworld, PC World, Network World,
Macworld and the Channel World family of publications. IDG Books Worldwide is one of the fastest-growing computer book publishers in
the world, with more than 700 titles in 36 languages. The “...For Dummies®” series alone has more than 50 million copies in print. IDG offers
online users the largest network of technology-specific Web sites around the world through IDG.net (http://www.idg.net), which comprises
more than 225 targeted Web sites in 55 countries worldwide. International Data Corporation (IDC) is the world’s largest provider of information
technology data, analysis and consulting, with research centers in over 41 countries and more than 400 research analysts worldwide. IDG
World Expo is a leading producer of more than 168 globally branded conferences and expositions in 35 countries including E3 (Electronic
Entertainment Expo), Macworld Expo, ComNet, Windows World Expo, ICE (Internet Commerce Expo), Agenda, DEMO, and Spotlight.
IDG’s training subsidiary, ExecuTrain, is the world’s largest computer training company, with more than 230 locations worldwide and 785
training courses. IDG Marketing Services helps industry-leading IT companies build international brand recognition by developing global
integrated marketing programs via IDG’s print, online and exposition products worldwide. Further information about the company can be
found at www.idg.com. 1/24/99
maranGraphics is a family-run business
located near Toronto, Canada.
At maranGraphics, we believe in producing great in their fields, and spend countless hours researching
computer books — one book at a time. and organizing the content for each topic. Our artists
maranGraphics has been producing high-technology rebuild every screen shot to provide the best clarity
products for over 25 years, which enables us to offer the possible, making our screen shots the most precise and
computer book community a unique communication easiest to read in the industry. We strive for perfection,
process. and believe that the time spent handcrafting each element
results in the best computer books money can buy.
Our computer books use an integrated communication
process, which is very different from the approach used Thank you for purchasing this book. We hope you
in other computer books. Each spread is, in essence, a enjoy it!
flow chart — the text and screen shots are totally Sincerely,
incorporated into the layout of the spread. Introductory
Robert Maran
text and helpful tips complete the learning experience.
President
maranGraphics’ approach encourages the left and right maranGraphics
sides of the brain to work together — resulting in faster Rob@maran.com
orientation and greater memory retention. www.maran.com
Above all, we are very proud of the handcrafted nature www.idgbooks.com/visual
of our books. Our carefully-chosen writers are experts
CREDITS
Acquisitions, Editorial, and Production
Media Development Book Design
Project Editor maranGraphics™
Dana Rhodes Lesh Project Coordinator
Acquisitions Editor Cindy Phipps
Martine Edwards Layout
Associate Project Coordinator Barry Offringa, Jill Piscitelli, Kathie
Lindsay Sandman Schutte, Erin Zeltner
Copy Editor Proofreaders
Tim Borek Corey Bowen, Vicki Broyles
Proof Editor Indexer
Dwight Ramsey York Production Services, Inc.
Technical Editor Special Help
Angela Murdock Megan Decraene, Mark Harris,
Permissions Editor Jill Johnson, Beth Parlon,
Carmen Krikorian Marisa E. Pearman,
Associate Media Development Maureen Spears
Specialist
Megan Decraene
Editorial Manager
Rev Mengle
Media Development Manager
Heather Heath Dismore
Editorial Assistant
Candace Nicholson
ACKNOWLEDGMENTS
Author’s Acknowledgments
There are several individuals that I’d like to thank for their support on this project. First of all is my family. Thanks to Angela for
helping me in the most stressful times during the development of this work and for her continual encouragement. Thanks to
Eric and Thomas for being understanding while Dad was so busy.
Thanks to Chris Murdock for his work on the Animabets characters that are feature prominently throughout the book.
Thanks to Martine Edwards for directing me to this project and a big thanks to Dana Lesh for her expert editing and project
guidance. Thanks also to all other IDG employees who were responsible for copy editing, proofreading, indexing, designing the
cover, and producing the CD-ROM.
Thanks also to all the contributors who added value to the book’s CD-ROM.
Dedication
Never underestimate the power of a good game.
To Eric, 2000
TABLE OF CONTENTS
1) INTRODUCING JAVASCRIPT
Understand Scripting ..................................................................................................2
Enter JavaScript Statements in the URL Field ..............................................................4
Embed JavaScript within an HTML Document ............................................................6
Link to an External JavaScript File ................................................................................8
Present Content to Non-JavaScript Browsers ............................................................10
Add Comments to JavaScript ....................................................................................12
viii
JAVASCRIPT:
Your visual blueprint for
building dynamic Web pages
3) CREATING EXPRESSIONS
Using Arithmetic Operators ......................................................................................36
Increment and Decrement Variables ........................................................................38
Create Comparison Expressions ................................................................................40
Create Logical Expressions ........................................................................................42
Use Conditional Operators ........................................................................................44
Understand Precedence ............................................................................................46
Evaluate String Expressions ......................................................................................47
Identify Numbers ......................................................................................................48
ix
TABLE OF CONTENTS
6) HANDLING EVENTS
Using JavaScript Events ............................................................................................74
Detect a Mouse Click ................................................................................................76
Detect a Double-Click ..............................................................................................78
Create Rollover Buttons ............................................................................................80
Detect a Key Press ....................................................................................................82
Set Focus ..................................................................................................................84
Detect a Pull-Down Menu Selection ........................................................................86
Create Page Loading and Unloading Messages ..........................................................88
7) USING OBJECTS
Understand Objects, Properties, and Methods ........................................................90
Using Web Page Element Objects ............................................................................92
Using Subobjects ......................................................................................................94
Using Predefined Objects ..........................................................................................96
Create New Objects ..................................................................................................98
x
JAVASCRIPT:
Your visual blueprint for
building dynamic Web pages
xi
TABLE OF CONTENTS
xii
JAVASCRIPT:
Your visual blueprint for
building dynamic Web pages
xiii
TABLE OF CONTENTS
xiv
JAVASCRIPT:
Your visual blueprint for
building dynamic Web pages
xv
TABLE OF CONTENTS
xvi
JAVASCRIPT:
Your visual blueprint for
building dynamic Web pages
xvii
JAVASCRIPT
UNDERSTAND SCRIPTING
eb page files, written in the Hypertext This interactivity enables the Web page creator
UNDERSTAND SCRIPTING
⁄ Open a Web page that ¤ Click one of the buttons. ■ The text box displays the ‹ Click another button.
includes JavaScript, such as answer result, and a new
www.animabets.com/ image is displayed.
activities/qballs/
balls.html, in a browser. Note: The HTML file for this Web
page includes JavaScript syntax
that defines how the text boxes
and images are updated.
2
INTRODUCING JAVASCRIPT 1
JavaScript is the most popular client-based VBScript is very similar to the Visual Basic
Web scripting language because it is programming language, so the advantage of
supported on both Netscape Navigator and using it if you are familiar with Visual Basic is
Internet Explorer, but you can use other that VBScript may be easier for you to learn
scripting languages to add interactivity to a than JavaScript. The disadvantage is that
Web page. Setting the language attribute VBScript works only in the Microsoft Internet
for the <script> tag to VBScript Explorer browser.
specifies that VBScript is used as the
scripting language. VBScript is similar in
syntax to Visual Basic, but it is only
supported on the Internet Explorer browser.
■ Again the text box displays › Choose View➪Source to ˇ Scroll down until you find ■ Notice that the language
the result, and a new image is view the page’s source code. the <script> tag. attribute is set to javascript.
displayed.
Note: The text box is logically
updated depending on the answer.
3
JAVASCRIPT
4
INTRODUCING JAVASCRIPT 1
If a keyword is entered in the Address box, If you forget to include the javascript:
the browser normally searches for Web pages keyword, the browser will think that the
based on the keyword. If you want the JavaScript statement you type is a Web page
browser to search for JavaScript Web pages address. It will try to locate a Web page with
instead of executing a JavaScript statement, that address, which it won’t be able to find.
just omit the colon after javascript: If you
type the javascript: keyword in the
browser’s Address box without including a
colon (:), the browser searches for Web
pages that match the javascript keyword.
The colon symbol tells the browser that the
following text should be interpreted as
JavaScript statements.
‹ After the javascript: › Also enter the statement ■ The JavaScript statements
keyword, type document.bgColor=“blue”; are executed in the browser.
document.write
ˇ Press the Enter key.
(“<h1>Hesitation
Kills</h1>“);.
5
JAVASCRIPT
⁄ Open the skeleton.html › Set the language attribute Á Within the <script> tags, ° Save the file as
file. equal to javascript. add a JavaScript statement to changebg.html.
change the background color.
¤ Add a set of <script> tags ˇ Save the file as js- Note: JavaScript statements
within the <body> tags. skeleton.html. ‡ Add a semicolon (;) to the placed within the <script> tags
end of the JavaScript are executed when the file is
‹ Add the language attribute Note: This skeleton page can be statement. loaded.
to the <script> tag. used to easily create a Web page
that includes JavaScript.
6
INTRODUCING JAVASCRIPT 1
· Add another JavaScript ‚ Add a semicolon (;) to the ± Open the output.html file ■ Notice how the
statement to output a phrase. end of the JavaScript in a browser. background color has
statement. changed and text is displayed.
■ The output statement can
include HTML tags. — Save the file as
output.html.
7
JAVASCRIPT
LINK TO AN EXTERNAL
JAVASCRIPT FILE
nother attribute that can be used with protocol keyword followed by the Web address
⁄ Open the output.html file ‹ Save the file as CREATING A FILE TO LINK TO ‹ Save the file as
in Notepad. external.html. external.js.
⁄ Open a new file in
¤ Cut the contents of Notepad.
<script> tags out of the file.
¤ Paste the <script> tag
contents you cut from the
output.html file into this
new file.
8
INTRODUCING JAVASCRIPT 1
JavaScript is case-sensitive. If you type a Any JavaScript statements included within the
JavaScript variable with a capital letter, you <head> tags are executed before the remaining
need to include that same capital letter when HTML tags. For example, if there are <script>
you call the variable. So the variables hello, tags within the <head> tags that contain a
Hello, and HELLO are all different. If your JavaScript statement that outputs some text, that
JavaScript statement isn’t being recognized text appears above the rest of the Web page.
correctly, check for a misspelled keyword.
You can execute JavaScript statements
multiple times by placing them within
structures called functions. Functions are
covered in Chapter 5.
LINKING TO AN EXTERNAL FILE ‹ Set the src attribute to ˇ Open the external.html ■ The JavaScript statements
external.js. file in a browser. still work as an external file.
⁄ Open the external.html
file in Notepad. › Save the file as
external.html, saving
¤ Add the src attribute to over the original
the <script> tag. external.html file.
9
JAVASCRIPT
ADDING <noscript> TAGS TO A ‹ Between the <noscript> DISABLING JAVASCRIPT IN ¤ Choose Edit➪Preferences
WEB PAGE tags, add some explanation NETSCAPE NAVIGATOR to open the Preferences
⁄ Open the output.html text. dialog box.
⁄ Open Netscape Navigator.
file. › Save the file as ‹ Select the Advanced
noscript.html. Note: In the Internet Explorer category from the list at the
¤ After the <script> tags, browser, you can’t disable
add a set of <noscript> tags. left.
JavaScript specifically.
10
INTRODUCING JAVASCRIPT 1
You cannot control a user’s browser Many different Web page enhancements can be
configuration, so there is no way to alter enabled or disabled using the browser
someone’s configuration to enable JavaScript preference settings. Using Netscape Navigator’s
support. The best you can do is to tell the Preferences dialog box, you can disable Java,
user how to enable it and encourage him or JavaScript, style sheets, and cookies. Using
her to do so. You can, however, detect Internet Explorer’s Options dialog box, you
whether the Java programming language is can disable Java, ActiveX controls, scripting,
enabled. and cookies.
› Deselect the Enable ˇ Click the OK button. VIEWING YOUR WEB PAGE IN A ■ The text contained within
JavaScript option JAVASCRIPT-DISABLED the <noscript> tag is
( changes to ). BROWSER displayed.
⁄ Open the noscript.html
file in Netscape Navigator.
11
JAVASCRIPT
⁄ Open the noscript.html ‹ Add a multiple-line ˇ Open the comments.html ■ Notice how the comments
file in Notepad. comment in front of the file in a browser. added to the file don’t appear
second JavaScript statement. in the browser.
¤ Add a single-line
comment in front of the first › Save the file as
JavaScript statement. comments.html.
12
INTRODUCING JAVASCRIPT 1
Á Open the comments.html ° Save the file as · Open the ■ Notice that the first
file in Notepad. comments2.html. comments2.html file in a JavaScript statement was
browser. executed, but not the second,
‡ Move the closing because the second
comment block after the statement is now a comment.
second JavaScript statement.
13
JAVASCRIPT
14
USING VARIABLES AND ARRAYS 2
TYPES OF VARIABLES
INTEGER VARIABLES
Integer variables can hold the basic counting
numbers, either positive or negative. These
values can be operated on using arithmetic
operators such as addition, subtraction,
multiplication, and division.
Examples of integer values include 2, 345,
and -34.
FLOATING-POINT VARIABLES
Floating-point variables can hold fractional
numbers that include a decimal point. These
variables can also be used with the standard
arithmetic operators.
Examples of floating-point values include 2.5,
-34.56, and 3.121.
STRING VARIABLES
String variables are simply words and
sentences. These variables can hold single
characters or entire paragraphs. String values
are usually designated with a set of
quotation marks.
Examples of string values include “hello”,
“abc”, and “This is a test”.
BOOLEAN VARIABLES
Boolean variables are a unique variable type
that can hold only the words true or false.
These variables can be used to test the
condition of a statement. The number 0 is
also used to represent the value false, and
1 represents the value true.
15
JAVASCRIPT
DECLARE VARIABLES
J avaScript is a loosely typed language. This
means that you don’t need to explicitly
declare each variable type, and different
variable types can be combined without an
You can also specifically state variable names
using the var keyword. This keyword, when
placed in front of a variable name, identifies it
as a variable. You can declare several variables
error. at once by separating them with commas.
Being a loosely typed language also means that For example, var int1, int2, str1,
you don’t need to specify the variable type str2 declares four variables.
when creating a new variable. All you need to
do is type a variable name, and its type is This example uses the js-skeleton.html
automatically set based on the type of value it file found on the book’s CD-ROM, but you can
holds. apply these steps to any file.
DECLARE VARIABLES
⁄ Open the file js- › Add a semicolon (;) to the Á Add several additional ‡ Save the file as
skeleton.html in Notepad. end of the line. variable names separated var2.html.
with commas.
¤ Add a heading for the ˇ Save the file as
page within the <body> tags. var.html.
‹ Add the var keyword
within the <script> tags
followed by a variable name.
16
USING VARIABLES AND ARRAYS 2
ASSIGNING A VALUE ‹ Save the file as ASSIGNING VALUES TO ‹ Save the file as
TO A VARIABLE MULTIPLE VARIABLES
assign.html. assign2.html.
⁄ Open the file var.html in ⁄ Open the file var2.html
Notepad. in Notepad.
¤ Below the variable ¤ Below the variable
declaration, type the variable declaration, set the value for
name and set it equal to a each variable name.
value.
17
JAVASCRIPT
USING INTEGERS
ntegers are values without a decimal point. being represented with the letters a–f.
USING INTEGERS
⁄ Open the js- › Use document.write Á Open the integer.html ■ The variable values are
skeleton.html file in statements to display the file in a browser. displayed. Notice how each
Notepad. values of each variable. value is displayed as its
¤ Within the <script> tags, decimal equivalent.
ˇ Save the file as
declare three variables with integer.html.
the var keyword.
‹ Set each variable name to
a value.
18
USING VARIABLES AND ARRAYS 2
USING FLOATING-POINT NUMBERS
loating-point values are fractional numbers that
F
It depends on the size of a floating-point
include a decimal point. These numbers can be number whether it is displayed in scientific
either positive or negative. notation. Floating-point numbers that are
smaller than 1.0E-7 are displayed in
Very large or very small numbers can be expressed
scientific notation, but large numbers can
in scientific notation. Scientific notation places the
be as large as 1.0E20 before being
letter E within the number followed by the number
displayed in scientific notation.
of places the decimal point is moved. Positive
values move the decimal to the right, and negative
values move the decimal to the left.
For example, 5.14E6 represents the number
5,140,000, and 6.023E-4 represents the number
0.0006023.
This example uses the js-skeleton.html file
found on the book’s CD-ROM, but you can apply
these steps to any file.
USING FLOATING-POINT NUMBERS
⁄ Open the js- › Use document.write Á Open the floating- ■ The variable values are
skeleton.html file in statements to display the point.html file in a browser. displayed. Notice how some
Notepad. values of each variable. of them are displayed in
¤ Within the <script> tags, scientific notation.
declare four variables with ˇ Save the file as
the var keyword. floating-point.html.
‹ Set each variable name to
floating-point values, two
large and two small.
19
JAVASCRIPT
USING BOOLEANS
oolean values can be either true or == “true”) can be used to control whether
USING BOOLEANS
⁄ Open the var2.html file ‹ Use document.write ˇ Open the boolean.html ■ The variable values are
in Notepad. statements to display the file in a browser. displayed.
values of each variable.
¤ Within the <script> tags,
assign Boolean values to each › Save the file as
variable. boolean.html.
20
USING VARIABLES AND ARRAYS 2
USING STRINGS
tring values are composed of words and For example, if a string is assigned to a variable
⁄ Open the js- › Use document.write Á Open the string.html file ■ The string values are
skeleton.html file in statements to display the in a browser. displayed.
Notepad. values of each variable.
¤ Within the <script> tags, ˇ Save the file as
declare two variables with the string.html.
var keyword.
‹ Set each variable name to
a string value.
21
JAVASCRIPT
⁄ Open the assign2.html ‹ Add the typeof keyword ˇ Open the typeof.html file ■ The variable type for each
file in Notepad. to each document.write in a browser. variable is displayed.
statement followed by the
¤ Use document.write variable name.
statements to display the
values of each variable. › Save the file as
typeof.html.
22
USING VARIABLES AND ARRAYS 2
The typeof keyword can also be used to If the undefined value is returned as a result
identify other types of elements: objects, of the typeof keyword, the variable doesn’t
forms, and functions. Each form, function, exist or hasn’t been defined yet. If you misspell
and object has a name. Using the typeof the variable name, it isn’t recognized and the
keyword with these names returns the undefined value is returned. Another case in
element’s type. which the undefined value is returned is if
you use typeof before the variable gets
assigned a value: If the typeof keyword
appears in the script before the variable or
function is encountered, the typeof keyword
returns undefined.
⁄ Open the var2.html file ‹ Save the file as › Open the file ■ The variable type for each
in Notepad. typeof2.html. typeof2.html in a browser. unassigned variable is
displayed as undefined.
¤ Use document.write
statements to display the type
of each unassigned variable.
23
JAVASCRIPT
⁄ Open the js- ‹ Use the parseInt() Á Open the file ■ The variable type for each
skeleton.html file in function to convert the string parseint.html in a browser. variable is displayed.
Notepad. to a number.
If the variable starts with a character that isn’t A string value can be assigned to a variable and
a number, the parseInt() function returns later an integer value assigned to the same
NaN, which stands for “not a number.” variable without causing an error: Because
JavaScript is loosely scripted, you can assign
JavaScript includes a simple method that can different values to a variable at any time without
determine if a variable is a number. The an error.
isNaN() function returns true if the
variable is “not a number” or false if it is.
■ Open the js- ‹ Use the parseFloat() Á Open parsefloat.html in ■ The variable type for each
skeleton.html file in function to convert the string a browser. variable is displayed.
Notepad. to a number.
¤ Add two new variables › Use document.write
and assign the first one to be statements to display the
a string that starts with a values and type of each
variable.
floating-point number.
ˇ Save the file as
parsefloat.html.
25
JAVASCRIPT
⁄ Open the js- › Use document.write Á Open tostring.html in a ■ The variable type for each
skeleton.html file in statements to display the browser. variable is displayed.
Notepad. values and type of each
¤ Add two new variables variable.
and assign the first one to be
a number. ˇ Save the file as
tostring.html.
‹ Convert the second
variable to a string by adding
it to ““.
26
USING VARIABLES AND ARRAYS 2
⁄ Open the js- › Use document.write Á Open tostring2.html in ■ The variable type for each
skeleton.html file in statements to display the a browser. variable is displayed.
Notepad. values and type of each
¤ Add two new variables variable.
and assign the first one to be
a number. ˇ Save the file as
tostring2.html.
‹ Change the second
variable to a string by using
the toString() method.
27
JAVASCRIPT
DECLARE AN ARRAY
everal variables can be grouped together name followed by the index number in square
⁄ Open the js- ‹ Assign each array element Á Open array.html in a ■ A string made from all the
skeleton.html file in to a string. browser. individual array elements is
Notepad. displayed.
› Use a document.write
¤ Add a new variable name statement to display the value
and assign it to new Array() of each array element.
with the number of elements
in the array within the ˇ Save the file as
parentheses. array.html.
28
USING VARIABLES AND ARRAYS 2
All the elements of a JavaScript array don’t JavaScript supports two-dimensional arrays. You
have to contain the same variable type. The can create a two-dimensional array by creating
elements of an array can hold several an array of an array. The way this works is to
different types of variables. For example, the create a single one-dimensional array and then
first element in an array could be an integer, to create an array of the existing array. It can be
the second element could be a string, and the confusing when you try to refer to an array of an
third element could be a floating-point array, but for the right application, it is worth
number. Each array element is independent of the effort.
the other elements. However, if you try to
multiply array elements of different types, an
error occurs.
⁄ Open the ‹ Assign each array element Á Open array2.html in a ■ The value contained within
js-skeleton.html file in to an integer. browser. each array element is
Notepad. displayed.
› Use a document.write
¤ Add a new variable name statement to display the value
and assign it to new Array() of each array element.
with the number of elements
in the array within the ˇ Save the file as
parentheses. array2.html.
29
JAVASCRIPT
⁄ Open the array.html file ‹ Add a new ˇ Open length.html in a ■ The browser displays the
in Notepad. document.write statement to browser. number of elements in the
“
display the length of the array.
¤ Add + “<br/> array.
document.write statement to
add a line break. › Save the file as
length.html.
30
USING VARIABLES AND ARRAYS 2
What happens if the array elements are filled The length property is a read-only property,
intermittently depends on whether the array which means that it can return information
size is specified. If the array size is specified, about the object, but it cannot be used to set
the length property always returns the the object’s property. The length property,
specified size. This is the number of places of therefore, cannot be used to set an array’s size.
memory that has been set aside for the array.
If the size isn’t specified, the length
property is determined by the array element
with the greatest index value. For example, if
only the second and fourth elements of an
array are filled, the length property will
identify four elements in the array even if the
first and third elements contain no data.
⁄ Open the ‹ Assign several array Á Open length2.html in a ■ The number of array
js-skeleton.html file in elements a value. browser. elements is displayed.
Notepad.
› Use document.write
¤ Add a new variable name statements to display the
and assign it to new Array() array values and the number
without specifying the of array elements.
number of elements in the ˇ Save the file as
array. length2.html.
31
JAVASCRIPT
⁄ Open js-skeleton.html › Convert the array to a ‡ Open join.html in a ■ The converted array is
in Notepad. string with the join() browser. displayed separated by
method and assign the value commas.
¤ Add a new variable name to a string variable.
and assign it to new Array().
ˇ Use a document.write
‹ Assign several array statement to display the
elements a value. string variable.
Á Save the file as join.html.
32
USING VARIABLES AND ARRAYS 2
Large arrays can be difficult to search through These statements declare an array of elements,
to find specific pieces of data. An easier way convert the array of elements into a string called
to search through an array is to convert the str1, and then set the variable beginChar
entire array to a single string and then use the equal to the position in the string where the
indexOf() method to locate the specific value “123” starts. Using these statements, you
data:. can locate specific elements within the array.
After you locate these elements, you can parse
Example: out the data by using other string object
array1 = new Array(“hello”, methods. Chapter 9 covers string object
“123”, “senior”, “blank”, methods in detail.
“fixed”);
str1 = array1.join(“ ”);
beginChar = str1.indexOf(“123”);
⁄ Open the join.html file Note: In Step 2, you are specifying › Open join2.html in a ■ The converted array is
in Notepad. to use a space as a separator browser. displayed separated by
rather than the default comma, so spaces.
¤ Add a string with a space a space will appear in between
as a parameter to the join() each array element.
method.
‹ Save the file as
join2.html.
33
JAVASCRIPT
SORT AN ARRAY
n array full of elements can be converted When the sort() method is used on an array
⁄ Open the join.html file ‹ Save the file as › Open sort.html in a ■ The array is alphabetically
in Notepad. sort.html. browser. sorted.
¤ Change the join()
method to the sort()
method.
34
USING VARIABLES AND ARRAYS 2
The sort() method can accept a function When the sort() method is executed, the
name as a parameter. The function name can function numSort is called. This function
contain an alternative way to sort the array. accepts two parameters and returns the
This parameter can be used to sort an array of difference between them. This difference is used
numbers numerically instead of alphabetically. by the sort() method to sort the numbers in
The statements for this would look like this: numerical order. As the sort() method
traverses the array elements, the numSort
function numSort(var1, var2) { function is called as often as needed to
return var1 – var2; complete the sorting.
}
array1 = new Array(“1”, “2”,
“12”, “34”, “72”);
str1 = array1.sort(numSort);
⁄ Open the sort.html file ‹ Save the file as › Open sort2.html in a ■ The array is sorted, but not
in Notepad. sort2.html. browser. in numerical order.
¤ Change the array elements
from strings to numbers.
35
JAVASCRIPT
⁄ Open the js-skeleton.html › Use several Á Open arithmetic.html ■ The values of each
file in Notepad. document.write in a browser. evaluated arithmetic
statements to display the expression are displayed.
¤ Create two new variables value of each variable.
and assign a number to each.
ˇ Save the file as
‹ Create four new variables arithmetic.html.
and assign each to an
arithmetic expression created
using the first two variables.
36
CREATING EXPRESSIONS 3
The addition operator can be used to You can define a factorial as subtracting one
combine strings, but all other arithmetic from the current value and multiplying it times
operators return a NaN value if they are used the result. For example, 3 factorial would be
on strings. NaN stands for “not a number.” If 3 × 2 × 1 for a result of 6. A function to
the string is a number and it doesn’t include compute factorials would look like this:
any letters, JavaScript automatically converts function factorial(num) {
the string to a number and evaluates the
for (j=num;j>0;j—)
expression. See Chapter 9 for more details
on using strings. result *= num;
return result
}
This function uses several expressions to
evaluate the factorial result. The result is then
returned.
⁄ Open the arithmetic.html ‹ Use a document.write ˇ Open the file modulus.html ■ The value of the modulus
file in Notepad. statement to display the value in a browser. expression is displayed.
of the modulus expression.
¤ Create a new variable
and assign it to a modulus › Save the file as
expression using the first modulus.html.
two variables.
37
JAVASCRIPT
⁄ Open js-skeleton.html › Increment the variable ‡ Open inc.html in a ■ The values of each variable
in Notepad. with the ++ symbols. browser. are displayed before and after
the increment and decrement
¤ Create a new variable and ˇ Add another expressions.
assign it a number. document.write
statement to again display
‹ Use a document.write the value of each variable.
statement to display the value
of the variable. Á Save the file as inc.html.
38
CREATING EXPRESSIONS 3
The increment or decrement operator doesn’t
always have to follow the variable: The
increment or decrement operator can come
before or after the variable, but subtle
differences distinguish the two when used
with an assignment operator (=). If the
increment or decrement operator comes
before the variable, like var1 = ++var2,
var2 gets incremented before the value is
assigned to var1. If, however, the operator
comes after the variable, the value of var2
gets assigned to var1 before it is incremented
or decremented.
You can use the similar expression x = x +
1 instead of the simpler x++. The increment
operator is used often enough, however, to
make it worth having.
DECREMENT VARIABLES
⁄ Open the inc.html file › Decrement the variable ‡ Open dec.html in a ■ The values of each variable
in Notepad. with the -- symbols. browser. are displayed before and after
the increment and decrement
¤ Create another variable ˇ Add another expressions.
and assign it a number. document.write
statement to again display
‹ Add a document.write the value of the variables.
statement to display the value
of each variable. Á Save the file as dec.html.
39
JAVASCRIPT
⁄ Open the js-skeleton.html statement, assign another Á Open the file comp.html ■ The values of each variable
file in Notepad. variable a value. in a browser. are displayed.
¤ Create a new variable and › Use document.write
assign it a number. statements to display the value
of each variable.
‹ Create a comparison
expression as part of an if ˇ Save the file as
statement. Within the if comp.html.
40
CREATING EXPRESSIONS 3
‡ Open comp.html in than operator within an if ¡ Open comp2.html in a ■ The values of each variable
Notepad. statement. Within the if browser. are displayed.
statement, assign another
° Reset the variable’s value. variable a value.
· Create a comparison — Use document.write
expression like Step 3’s. statements to display the
‚ Create another comparison value of each variable.
expression using the greater ± Save the file as comp2.html.
41
JAVASCRIPT
⁄ Open the comp.html file ■ The document.write › Open logical.html in ■ The values of each variable
in Notepad. statements display the value a browser. are displayed.
of each variable.
¤ Add a logical operator to
the comparison statement. ‹ Save the file as
logical.html.
42
CREATING EXPRESSIONS 3
To get a better idea of all the variations of For the not operator, only two possibilities exist:
using the logical operators, consider the
!true = false
following examples. First, the and operator:
!false = true
true && true = true
Logical operators evaluate the expression on
true && false = false
each side of the logical operator first and then
false && true = false evaluate the logical operator. For example, the
false && false = false statement (var1 > 17 && var1 < 25)
combines the two statements in comparing
For the or operator, the following apply: whether the variable is greater than 17 and less
true || true = true than 25. If the value of var1 equals 18, the
true || false = true
result of this expression is true.
false || true = true
false || false = false
ˇ Open the logical.html ‡ Add document.write · Open the file logical2.html ■ The values of each variable
file in Notepad. statements to display the in a browser. are displayed.
value of the variables.
Á Create another logical
expression as part of an if ° Save the file as
statement. logical2.html.
43
JAVASCRIPT
⁄ Open the js-skeleton.html › Use a document.write Á Open the file ■ The browser displays the
file in Notepad. statement to display the value conditional.html values of each variable.
of each variable. in a browser.
¤ Create new variables and
assign them values. ˇ Save the file as
conditional.html.
‹ Use a conditional
expression to determine
the value of a variable.
44
CREATING EXPRESSIONS 3
‡ Open the js-skeleton.html ‚ Use a document.write ± Open the file ■ The values of each variable
file in Notepad again. statement to display the value conditional2.html are displayed.
of each variable. in a browser.
° Create several new
variables and assign each a — Save the file as
value. conditional2.html.
· Use a conditional
expression to determine
which expression to evaluate.
45
JAVASCRIPT
UNDERSTAND PRECEDENCE
J avaScript evaluates operators in a specific
order. This order is known as operator
precedence. The operators with the highest
precedence get evaluated first.
The order of operator precedence after
parentheses is as follows:
1. Unary operators: ++, --, –, !
Parentheses have the highest precedence. If 2. Arithmetic operators: *, /, %, +, –
you are ever in doubt of which expression is to
be evaluated first, include the separate 3. Comparison operators: >, <, >=, <=
expressions within parentheses.
4. Logical operators: &&, ||
If the operators have the same level of
precedence, such as an expression full of 5. Conditional operator: ?:
addition operators, JavaScript evaluates the 6. Assignment operator: =
operators from left to right.
UNDERSTAND PRECEDENCE
⁄ Open the js-skeleton.html ‹ Add pairs of parentheses Á Open precedence.html ■ Notice how the values of
file from the CD-ROM in to the expressions in different in a browser. each expression are different.
Notepad. places.
¤ Create several variables › Use document.write
and assign each an expression statements to display the
with the same type of results of each expression.
operators.
ˇ Save the file as
precedence.html.
46
CREATING EXPRESSIONS 3
⁄ Open the js-skeleton.html › Use another Á Open the file eval.html ■ The string variable is
file in Notepad. document.write in a browser. shown before and after it
statement and the eval() has been evaluated.
¤ Create a new variable and keyword to evaluate and
assign it an expression as a display the result of the
string in quotation marks. string variable.
‹ Use a document.write ˇ Save the file as
statement to display the value
of the string variable. eval.html.
47
JAVASCRIPT
IDENTIFY NUMBERS
J avaScript includes a unique method that can
be used to identify variables as numbers.
This functionality is useful when you accept
input from the user and want to verify that the
For example, if a statement is defined as var1
= 23, the expression isNaN(var1) returns a
false value because the value of var1 is a
number (23).
values entered are actually numbers. Trying to
evaluate a numerical expression with a string This example uses the js-skeleton.html
value causes an error. file found on the book’s CD-ROM, but you can
apply these steps to any file.
The method to verify if a variable is a number
actually checks to see if it is not a number.
This method is isNaN(), which accepts a
single parameter that is checked. If the variable
sent to the method is a number, the method
returns a false value; if the variable is not a
number, a true value is returned.
IDENTIFY NUMBERS
⁄ Open the js-skeleton.html › Include some Á Open the file isNaN.html ■ The browser determines
file in Notepad. document.write in a browser. that the variable is a number.
statements to display the
¤ Create a new variable and results of the conditional
assign it a numeric value. statement.
‹ Add a conditional ˇ Save the file as
expression based on the isNaN.html.
isNaN method.
48
CREATING EXPRESSIONS 3
One of the best ways to use the isNaN() Area: <input type=“text”
method is to validate data entered into a name=“text2”/>
form. For example, if you accept numerical </form>
values in a form field that you are using to
This form includes two text fields. The first text
compute an equation, you can cause an alert
field is where the user enters the radius of a
box to appear if the user enters some input
circle. The onchange event executes the
that is not a number. The code for this looks
conditional statement when a number is entered
like this:
and the focus of the text field is lost. The
<form name=“form1”> conditional statement checks the isNaN()
Enter the circle radius.<input method to see whether the text entered is a
type=“text” name=“text1” number. If it is, the area of the circle is computed.
onchange=”(isNaN(this.value))?window. If not, an alert dialog box is displayed.
alert(‘This is not a number. Please
enter a numerical value.’):document.
form1.text2.value = (document.form1.
text1.value*document.form1.text1.valu
e*Math.PI)”/>
‡ Open the isNaN.html · Save the file as ‚ Open the file isNaN.html ■ The browser detects that
file in Notepad again. isNaN2.html. in a browser. this variable is not a number.
° Change the variable to a
string.
49
JAVASCRIPT
AppleWorks
■ Open › Use a document.write ‡ Open the file if- ■ The displayed text is
js-skeleton.html in statement to display some text else.html in a browser. determined by the
Notepad. if the if statement is true. conditional expression.
¤ Add two variables and ˇ Create an else statement Note: If you had set the variable’s
assign each a value. that uses a document.write
statement if the statement is values to those other than what
false. the if statement tested for, the
‹ Create an if statement with text for the else statement would
a conditional expression that Á Save the file as have been displayed.
checks a variable. if-else.html.
50
CONTROLLING PROGRAM FLOW 4
if loops can be nested one within another. This simple function compares successive
This enables you to drill down from general different attributes of a car. If each criteria is
conditions to more specific ones. Each level met, the cool car! statement is displayed. If
of a nested if-else structure could contain any of the criteria isn’t met, an alternative
some statements. Using this structure, you message is displayed.
can pinpoint the exact criteria for your
statements. For example, look how this code
works:
function coolCar() {
if (car == “Mustang”)
if (year == 1965)
if (parts == “original”)
document.write(“cool car!”);
else
document.write(“at least it
runs.”);
}
⁄ Open if-else.html in › Add statements to be Á Open the file ■ The displayed text is
Notepad. executed under the else if elseif.html in a browser. determined by the
¤ Change the values of the statements. conditional expression.
variables.
Note: The final else statement
‹ In between the if and should not include the if
else statements, add two keyword.
else if statements with
different conditional ˇ Save the file as
expressions. elseif.html.
51
JAVASCRIPT
⁄ Open js- terminating condition as 10; and ˇ Open forloop.html in ■ The value at each step in
skeleton.html in count++ determines that the a browser. the loop is displayed.
Notepad. variable is incremented by 1.
¤ Add a for loop that starts ‹ Use a document.write
at 1 and counts to 10. statement to display the value
of the variable.
Note: The three parts of this
example’s for loop are as follows: › Save the file as
count=1 defines the loop’s forloop.html.
initial condition to be 1;
count<=10 sets the loop’s
52
CONTROLLING PROGRAM FLOW 4
Á Open the Note: This example uses · Open the ■ The value at each step in
forloop.html file in count=count*count, which forloop2.html file in a the loop is displayed.
Notepad. multiplies the current value of the browser.
count variable by itself.
‡ Change the expressions in
the for statement. ° Save the file as
forloop2.html.
53
JAVASCRIPT
⁄ Open the › Add a count variable Á Open while.html in a ■ The values of the loop
forloop.html file in incrementing the statement browser. variable are displayed.
Notepad. within the loop.
¤ Add a count variable and ˇ Save the file as
assign it a value. while.html.
‹ Replace the for loop with
a while loop.
54
CONTROLLING PROGRAM FLOW 4
There are many ways to think about how to To exit a loop that appears to be looping
construct your loops; there will be times indefinitely, besides using the conditional
when you want to use a while loop and statement as part of the while loop, you can
others when you want to use a for loop. The use the break statement. The section “Break
two different ways of looping are similar, but Loops” discusses this in detail.
the for loop requires all the information
about the loop to be part of the for
statement. The while loop can use variables
that have been declared elsewhere.
If a while loop doesn’t include brackets,
only the first statement that follows the
while statement will be executed. If multiple
statements need to be executed, all statements
should be included within brackets.
Open the forloop2.html file ‚ Add a count ± Open while2.html in a ■ The count variable
in Notepad. incrementing statement browser. values are displayed as the
within the loop. loop progresses.
° Add a count variable and
assign it a value. — Save the file as
while2.html.
· Replace the for loop with
a while loop.
55
JAVASCRIPT
BREAK LOOPS
ometimes you can get stuck in a loop. This example uses the while.html file found
BREAK LOOPS
⁄ Open the while.html › Move the document.write Á Open break.html in a ■ When the condition of the
file in Notepad. statement to the bottom of browser. if statement is true, the loop
the loop. is terminated.
¤ Within the while loop,
add an if statement to check ˇ Save the file as
for a variable. break.html.
‹ Add a break statement to
execute if the if condition is
true.
56
CONTROLLING PROGRAM FLOW 4
CONTINUE LOOPS
Another keyword that works with loops is the execution of the number 50 with the statement
continue statement. This statement stops the if (var1 == 50) continue;.
execution of a loop and returns to the top of
the loop as if all the statements had been This example uses the break.html file found
executed. Any statements that follow the on the book’s CD-ROM (or which you may
continue statement will not be executed for have created in the section “Break Loops”), but
this time through the loop. you can apply these steps to any file.
CONTINUE LOOPS
■ Open the break.html ‹ Save the file as › Open continue.html ■ All values in the loop are
file in Notepad. continue.html. in a browser. displayed except for where
the continue statement
¤ Change the break was executed.
statement to a continue
statement.
57
JAVASCRIPT
⁄ Open js-skeleton.html. › Add the function name as ‡ Open the ■ The <body> tags’ heading
the first parameter of timeout.html file in a is displayed in the browser.
¤ Add a function that uses a setTimeout() and a time
document.write() browser.
value, in milliseconds, as the
statement to display a heading second parameter.
and an image.
ˇ Add a single heading to
‹ Add onload to the <body> the <body> tags.
tag and set it equal to
window.setTimeout(). Á Save the file as
timeout.html.
58
CONTROLLING PROGRAM FLOW 4
° Wait for the designated ■ The script function is · Open the timeout.html Note: The timeout can only be
time value. executed after the timeout file again in a browser. cleared using the
value is reached, displaying ‚ Click the Stop button clearTimeout() method,
function’s heading and before the timeout value is which is discussed in the section
image. reached. “Clear Timeouts and Intervals”
later in this chapter.
■ The timeout is not stopped,
and the image is again
displayed.
59
JAVASCRIPT
⁄ Open js- › Set the first parameter of ‡ Open setInterval.html ■ Two text boxes are
skeleton.html in Notepad. setInterval() to update in a browser. displayed.
the second text box with the
¤ Add a contents of the first text box.
window.setInterval()
method. ˇ Set the second parameter of
setInterval() to a time
‹ Add a form with two text value.
boxes. Á Save the file as
setInterval.html.
60
CONTROLLING PROGRAM FLOW 4
Chapter 10 covers the Date object. This The code creates a form with a single text box.
object includes a method called Interval() is then set to respond every
getLocaleString() that gets the current second. At each interval, the time object is
locale’s time. Using this method and the created and the toLocaleString() method is
setInterval() method, you can create a displayed in the text box. The time due to the
clock with the following code: setInterval() method is updated every
second.
<form name=“form1”>
<input type=“text” name=“text1”/>
</form>
<script language=“javascript”>
stop = window.setInterval(“time =
new
Date();document.form1.text1.value =
time.toLocaleString()”,1000);
</script>
° Enter some text in the first ■ The setInterval · Enter some different text ■ The text is again updated
text field. statement is executed after in the first text box. in the second box.
the timeout value is
reached, updating the second
text box.
61
JAVASCRIPT
■ Open the › Set the onclick event to Á Open the ■ The text is updated in the
setInterval.html file in use the clearInterval() clearInterval.html file second text box.
Notepad. method. in a browser.
¤ Add a new variable and ˇ Save the file as ‡ Type some text in the first
assign it to the clearInterval.html. text box.
setInterval() method.
‹ Add a button to the form
with an onclick event.
62
CONTROLLING PROGRAM FLOW 4
The clock example created in the section “Set In this code, a button is added to the form with
Regularly Timed Intervals” can be modified to an onclick event. The onclick event is
include a button that stops the clock. The assigned to clear the interval with the
following code adds the Stop button: clearInterval() method. The parameter to
the clearInterval() method is the variable
<form name=“form1”>
name that was assigned to the setInterval()
<input type=“text” method.
name=”text1”/>
<input type=“button”
name=“button1” value=”Stop”
onclick=“window.clearInterval(stop)”/>
</form>
<script language=“javascript”>
stop = window.setInterval(“time
= new
Date();document.form1.text1.value =
time.toLocaleString()”,1000);
</script>
° Click the button. ■ The setInterval() · Type some text in the first ■ The second text box is no
method has been stopped. text box. longer updated.
63
JAVASCRIPT
DECLARE A FUNCTION
ou can group sections of code together All JavaScript statements within the function
⁄ Open the file js- ‹ Add a JavaScript statement ˇ Open function.html in ■ The function statements
skeleton.html in Notepad. within braces after the your browser. are not executed because
function declaration. they haven’t been called.
¤ Create a new function
definition with the function › Save the file as Note: By grouping statements
keyword and a name. function.html. within a function, you can execute
the statements in the function as
many times as needed.
64
WORKING WITH FUNCTIONS 5
CALL A FUNCTION
fter you declare a function, you can This example uses the function.html file
CALL A FUNCTION
⁄ Open the file ‹ Save the file as › Open function- ■ The function statements
function.html in Notepad. function-call.html. call.html in a browser. are executed, and the results
appear on the screen.
¤ Add a function call after
the function statement. Note: When the function name is
referenced, the statements within
the function are executed.
Functions can be called many
times within a single file.
65
JAVASCRIPT
GLOBAL VARIABLES
⁄ Open the file js- › Add a statement to ‡ Open the global.html file ■ The variables are global
skeleton.html in Notepad. execute the function. in your browser. because they are declared
¤ Create two global ˇ Include another outside of the function and
variables with var. document.write statement can be used anywhere within
outside of the function to and without functions.
‹ Create a function with a display the variable values.
document.write statement
that displays the values of the Á Save the file as
declared variables. global.html.
66
WORKING WITH FUNCTIONS 5
A convenient way to keep track of global and It’s a good idea to use the var keyword outside
local variables is to adopt specific coding of functions. Any variables that are declared
conventions that have a naming standard that without the var keyword are global. Any
helps to keep the scope of a variable straight. variables declared outside of a function are also
For example, if you place a lowercase g on global. Using the var keyword will make it
the front of every global variable, as in gVar1, obvious to anyone looking at your code that you
then you can identify a global variable by just are declaring a variable.
looking at the variable name.
One reason to use local variables is that you
want to build functions that can be easily
reused. By using local variables, you can be
guaranteed that regardless of where the
function is copied, it will not conflict with
a global variable that shares the same variable
name.
LOCAL VARIABLES
⁄ Open the file Note: This makes the variables › Open local.html in your ˇ Click the Show/Hide
global.html in Notepad. local to the function because they browser. Details button to see the
are declared with the var keyword errors.
¤ Move the two variable and are now within the function. ■ A dialog box appears
declarations within the stating that the page has ■ Notice that the local
function. ‹ Save the file as errors. variables are undefined when
local.html. used in the document.write
statement outside of the
function.
67
JAVASCRIPT
⁄ Open the file js- ■ In this example, the ˇ Open parameters.html in ■ The function repeats with
skeleton.html in Notepad. parameter is item. your browser. each call, each with a
separate value.
¤ Create a function with a ‹ Add several calls to the
single parameter that displays function, each with a different
a message and the parameter value.
value.
› Save the file as
parameters.html.
68
WORKING WITH FUNCTIONS 5
Parameters that are passed to a function are When you call a function, the parameter that is
local to the function. If a parameter variable is passed can be a variable or a value. If a variable
used outside of the function, it will generate is passed, then the value of the variable at the
an error. time the function is called is sent to the
function.
If a function call doesn’t include any
parameters, the function name still needs an
empty set of parentheses. These parentheses
help identify the name as a function.
There is no limit to the number of parameters
that can be passed to a function, so you can
pass as many parameters to a function as
you need.
⁄ Open the file js- ‹ Add a call to the ˇ Open the ■ The computed value is
skeleton.html in Notepad. function. parameters2.html file in determined by the values
your browser. passed to the function.
¤ Create a function with › Save the file as
several parameters that parameters2.html.
computes and displays a
value.
69
JAVASCRIPT
⁄ Open the file js- › Add another Á Open the return.html file ■ The returned value is
skeleton.html in Notepad. document.write statement in a browser. displayed.
¤ Create a function with that calls the function and
several parameters that displays the resulting value.
computes a value. ˇ Save the file as
return.html.
‹ Add a return statement to
the function that returns the
resulting value.
70
WORKING WITH FUNCTIONS 5
A good example of a function that returns a If this function is included in a Web page file,
value is one that accepts parameters, you could call the function with the following
computes a result of an equation, and returns statement:
the resulting value. For example, a function
that computes and returns the computed area computeArea(3, 4, 5);
of a box, given width, height, and depth The function result is returned directly to the
parameters, looks like this: function call and can be used within a statement
function computeArea(width, height, such as this:
depth) { document.write(“The area of the box
area = width * height * depth; with the dimensions: “ + width + “, “
+ height + “, “ + depth + “ equals “ +
return area; computeArea(3, 4, 5));
⁄ Open the file js- › Return the modified string ‡ Open the return2.html ■ The string passed to a
skeleton.html in Notepad. with the return keyword. file in your browser. function is returned
formatted.
¤ Add a function that accepts ˇ Use a document.write
a single string parameter. statement to display the Note: Functions that return
returned string. desired results can be included
‹ Surround the string
within statements.
parameter with a set of HTML Á Save the file as
tags and set it equal to a return return2.html.
variable.
71
JAVASCRIPT
⁄ Open the file › Set the first href attribute ‡ Open the href.html file ° Click the first link.
function.html in Notepad. equal to javascript: and in your browser.
¤ Outside of the <script> the function name.
■ Two links are displayed.
tags, add two <a> tags and ˇ Set the second href
include some link text. attribute equal to
‹ Add the href attribute to javascript: and a
each set of <a> tags. JavaScript statement.
Á Save the file as href.html.
72
WORKING WITH FUNCTIONS 5
Another place within an HTML page where a The HTML form displays a submit button
function call can be placed is within the labeled “Display Welcome” in the browser.
action attribute of a <form> tag. For example, Clicking this button executes the hello()
function, which displays a welcome message.
function hello() {
document.write(“Hello and
Welcome”);
}
. . .
<form action=”javascript:hello()”>
<input type=”submit” value=”Display
Welcome”/>
</form>
E:\Temp\Authoring\JSB\examples\Ch05 - Working with Functions\global.html - Micrsoft… E:\Temp\Authoring\JSB\examples\Ch05 - Working with Functions\global.html - Micrsoft…
■ The function executes and · Click the Back button on ‚ Click the second link. ■ Clicking this second link
the quote is displayed. your browser. executes another JavaScript
statement, which displays
Note: Clicking the HTML link calls another quote.
the function that displays a quote.
73
JAVASCRIPT
74
HANDLING EVENTS 6
The onkeypress event can be used to detect Another common event used with form
when a key on the keyboard is pressed. The elements is the onchange event. This event
specific key that was pressed can be found in fires whenever the data of the form element is
the window.event.keycode object. changed.
Similar to the mouse button clicks, the The onload event is used to detect when a
onkeydown event detects after the key is first Web page has completely finished loading.
pressed and held down, and the onkeyup Similarly, the onunload event is fired when a
event fires after the pressed key is released. Web page is unloaded. This happens when you
SELECTION EVENTS
leave the current page or when you click the
browser’s Refresh button.
When an element is highlighted in the browser,
it is said to have focus. The onfocus event is When you cancel a Web page that is loading
used to signal when an element has the focus. into your browser, then the onabort event is
Pressing the Tab key can change this focus. called.
When an element loses the focus, the onblur
event fires. Two form buttons have specific functions —
submit and reset. These same functions can
When you select an element, the onselect be detected using the onsubmit and onreset
event is fired. events.
75
JAVASCRIPT
⁄ Open the file › Add the type, name, and Á Add the onclick ‡ Set the onclick event
skeleton.html in Notepad. value attributes to the JavaScript event to the equal to a JavaScript
<input/> tag. <input/> tag. statement that changes the
¤ Add <form> and button text.
<input/> tags between the ˇ Set the type attribute to
<body> tags. button, the name attribute to ° Save the file as
button1, and the value onclick.html.
‹ Add the name attribute to the attribute to the button face
<form> tag and set it to form1.
text.
76
HANDLING EVENTS 6
The onclick event detects when the mouse The onmousedown and onmouseup events are
button is clicked and released. The action of very similar to the onclick function. They are
clicking and releasing the mouse button can also intrinsic events that you can use with
be detected individually using the almost every HTML tag.
onmousedown and onmouseup events. The
user could press the mouse and not release There is a separate event for detecting double-
it. In this case, the onclick event would not clicks: The onclick event detects a single
detect this action, but the onmousedown click, but the ondblclick event detects
event would. double-clicks. This event is covered in the next
section, “Detect a Double-Click.”
· Open the onclick.html ‚ Click the button. ■ The text on the button face
file in your browser. changes according to the
JavaScript statement in the
■ A single button is onclick event.
displayed.
77
JAVASCRIPT
DETECT A DOUBLE-CLICK
ouble-clicking is very similar to single- You can use double-clicks to add a dual
D
button.
clicking except that the user clicks twice
rapidly instead of once on the mouse
function to a button. If you set the onclick
event to process one set of commands and the
ondblclick event to process a second set of
commands, then you can use single interface
Double-clicks can be detected using the elements, like a button, to accomplish twice as
ondblclick event. You can add this event to much work.
all the same elements as the onclick event,
including the <input/>, <button>, and <a> This example uses the onclick.html file
tags. found on the book’s CD-ROM (or which you
may have created in the section “Detect a
The ondblclick event is also an intrinsic Mouse Click”), but you can apply these steps
event. This means that you can use it with to any file.
almost any Web element.
DETECT A DOUBLE-CLICK
⁄ Open the file ‹ Set the ondblclick event ˇ Open the Á Click the button.
onclick.html in Notepad. equal to a JavaScript ondblclick.html file in your
statement to change the browser.
¤ After the onclick event, button text.
add the ondblclick event. ■ A single button is
› Save the file as displayed.
ondblclick.html.
78
HANDLING EVENTS 6
If the ondblclick event is fired, the Intrinsic events are a set of events that can be
onclick event fires as well, because the added to almost every Web element. The list of
onclick event is fired any time the mouse is intrinsic events includes onclick,
clicked — even when the ondblclick event ondblclick, onmousedown, onmouseup,
is fired. onmouseover, onmousemove, onmouseout,
onkeypress, onkeydown, and onkeyup.
A single tag can include multiple events.
These events are processed in the order that
they are listed. For example, if a tag includes
both onclick and ondblclick events,
then both will be processed any time the
element is clicked twice rapidly.
■ The text on the button ‡ Double-click the button. ■ The text on the button
changes. changes according to the
JavaScript statement in the
ondblclick event.
79
JAVASCRIPT
⁄ Open the file ˇ Set the onmouseover event ° Open the rollover.html ■ A single image is
skeleton.html in Notepad. to load another image. file in your browser. displayed.
¤ Add the <img/> tag. Á Set the onmouseout event
to load the original image.
‹ Add the src attribute and set
it equal to an image filename. ‡ Save the file as
rollover.html.
› Add the onmouseover
and onmouseout events.
80
HANDLING EVENTS 6
Events don’t always need to call a JavaScript The <p> tag can accept the onmouseover and
function. You can set JavaScript events equal onmouseout events. Using this tag, you can
to any valid JavaScript code. This code could execute JavaScript statements when the mouse
be a single line of JavaScript, multiple lines of rolls over normal text.
JavaScript, or a call to a function that is
defined within a set of <script> tags.
Within the event, each line of JavaScript must
end with a semicolon (;) including function
calls.
The onmousemove event triggers whenever
the mouse moves. This means that when the
onmouseover or the onmouseout events
fire, the onmousemove event also fires. This
event can be useful for detecting when a user
is using the computer.
· Move the mouse cursor ■ The image changes to the ‚ Move the mouse cursor ■ The image reverts to its
over the top of the image. image specified in the away from the image. original look.
onmouseover event.
81
JAVASCRIPT
⁄ Open the file › Add the type, name, and Á Add the onkeypress event ° Save the file as
skeleton.html in Notepad. value attributes to the to the <input/> tag. onkeypress.html.
<input/> tag.
¤ Add <form> and <input/> ‡ Set the onkeypress event
tags between the <body> ˇ Set the type attribute to equal to an if statement that
tags. text, the name attribute to checks the
text1, and the value window.event.keyCode value
‹ Add the name attribute to
attribute to the text field text. and displays some text if
the <form> tag and set it to
form1. correct.
82
HANDLING EVENTS 6
The onkeydown and onkeyup events are The onkeydown and onkeyup events will
very similar to the onmousedown and always be fired whenever the onkeypress
onmouseup events. It is possible that the event is fired, but the onkeydown event will be
user could press a keyboard key and not detected before the onkeyup event.
release it. In this case, the onkeydown event
would detect this action, but the If the onkeypress event is added to two or
onkeypress event would not until the more elements, the event will only be detected
keyboard key was finally released. if the element has focus. You can change the
focus of elements by using the Tab key.
· Open the ‚ Click in the text field to — Press the D key on the ■ The text updates to what
onkeypress.html file in your give it the focus. keyboard. you set it to in the
browser. onkeypress event.
■ A single text field is
displayed.
83
JAVASCRIPT
SET FOCUS
ocus determines which form element will event. Using the onblur event, you can set an
SET FOCUS
⁄ Open the file › Change the name attribute ‡ Open the onfocus.html ■ Two text fields appear side-
onkeypress.html in Notepad. of the second <input/> tag. file in your browser. by-side.
¤ Replace the onkeypress ˇ Set the onfocus and ° Click the left text field to
event with the onfocus and onblur events equal to a give it the focus.
onblur events. statement that changes the
text field text.
‹ Copy the <input/> tag
and paste another copy of it Á Save the file as
within the <body> tags. onfocus.html.
84
HANDLING EVENTS 6
You can use the onselect event with text One example of a situation in which you would
fields and textarea elements to detect need to know if an element has focus is when
when a section of text is selected. After you you are trying to detect a keypress, because the
know that text is highlighted, you can work onkeypress event will only work for the
with the selected section and replace, delete, element that has focus.
or change it.
There are two events that can detect when a
form is reset and submitted: onreset and
onsubmit. The onreset event happens
when a reset button is clicked, and the
onsubmit event happens when a submit
button is clicked. Using these events, you can
override the default HTML action that
happens when these buttons are used.
■ The text updates according · Click the right text field. ■ The text updates in both Note: The onblur event for the
to the field’s onfocus event. fields — the first according to second text field will fire when it
its onblur event (because it loses focus.
lost the focus) and the
second according to its
onfocus event (because it
gained the focus).
85
JAVASCRIPT
DETECT A PULL-DOWN
MENU SELECTION
he selection list element is a common When you use the onchange event with the
⁄ Open the file › Add the onchange event to ‡ Open the onchange.html ■ Two text fields appear side-
skeleton.html in Notepad. the opening <select> tag. file in your browser. by-side.
¤ Add a <form> with a text ˇ Set the onchange event to
box and a set of <select> a statement that changes the
tags. text in the text field.
‹ Add four sets of <option> Á Save the file as
tags with text. onchange.html.
86
HANDLING EVENTS 6
° Click the first option in the ■ The text field updates · Click the second option in ■ The text field updates
selection list. according to the onchange the selection list. again.
event.
87
JAVASCRIPT
⁄ Open the file › Add the onload and ‡ Open the file ■ The loading Web page
skeleton.html in Notepad. onunload events. onload.html in a browser. message appears while the
page is loading.
¤ Add <form> and ˇ Set the onload event to
<input/> tags between the display a message in the text
<body> tags. box and the onunload event to
display an alert dialog box.
‹ Add and set the type, name,
size, and value attributes to Á Save the file as
the <input/> tag. onload.html.
88
HANDLING EVENTS 6
Any time a Web page is loading in a browser, It’s not always a good idea to display alert dialog
the user can cancel the page by clicking the boxes before the user leaves a Web page. Many
Stop browser button. This action can be users will not appreciate having to click in an
detected using the onabort event. This alert dialog box before they can leave your Web
provides a useful way to inform the user what page. This technique should be used with
has happened if all the elements haven’t caution.
loaded.
The onerror event lets you detect when an
error loading elements occurs. If the browser
experiences trouble loading an image or a
page, then the onerror event fires. Using
this event, you can present a message to the
user that is easy to understand.
■ After the Web page has — Load a separate Web page ■ An alert box appears with
finished loading, the message in your browser. a message.
updates.
89
JAVASCRIPT
⁄ Open the Notepad file. › Within the parentheses of Á Open the file ■ The document object’s
the document.write() object.html in a browser. method displays the object’s
¤ Add an attribute to the method, add the property value.
<body> tag that sets the document.bgColor property.
background color.
ˇ Save the file as
‹ Within the <script> tags, object.html.
add the document.write()
method to display some text.
90
USING OBJECTS 7
Here’s how you can tell the difference Although several objects have common
between a property and a method: An object properties and methods, most are unique to
property reference ends with a single variable the object. No specific properties or methods
name, but a method always ends with a set of are common for all objects.
parentheses. So any object reference that
includes a set of parentheses is a method.
The parentheses may or may not contain a set
of parameter values. Either way, the
parentheses are required.
Almost all the preset objects include
properties and methods. Objects you create,
however, will not necessarily have properties
and methods. Creating objects is covered
later in this chapter in the section “Create
New Objects.”
‡ Open the object.html file · Save the file as ‚ Open the object2.html ■ The document’s
in Notepad. object2.html. file in a browser. foreground color value is
displayed.
° Change the
document.bgColor property
to document.fgColor.
91
JAVASCRIPT
⁄ Open the Notepad file. ˇ Set the onclick event for ° Open ta_object.html in · Click the first button.
¤ Add a form with a the first button to use a a browser.
textarea element under the method.
■ The textarea element is
<script> tags. Á Set the onclick event for displayed with two buttons.
‹ Add buttons to the form the second button to use a
using <input/> tags. property.
› Add the onclick event to ‡ Save the file as
each <input/> tag. ta_object.html.
92
USING OBJECTS 7
■ The text in the box is — Click the second button. ■ The text you typed in the
selected. textarea box is displayed.
‚ Type some new text in the
box.
93
JAVASCRIPT
USING SUBOBJECTS
bjects can be nested in a hierarchy. can be identified as window.document.
⁄ Open the file js- ‹ Within the <script> tags, ˇ Open sub-object.html in ■ The text within the text
skeleton.html in Notepad. reference a subobject that a browser. field is updated using
alters the value of the text JavaScript.
¤ Add a form with a text field.
field element in front of the
<script> tags. › Save the file as sub-
object.html.
94
USING OBJECTS 7
⁄ Open the file js- ‹ Within the <script> tags, ˇ Open the file sub- ■ One of the radio buttons is
skeleton.html in Notepad. reference a subobject that object2.html in a browser. checked (´) using JavaScript.
displays a check mark in one
¤ Add a form with two radio of the radio buttons.
button elements in front of
the <script> tags. › Save the file as sub-
object2.html.
95
JAVASCRIPT
⁄ Open the file js- › Add another string variable ‡ Open the file ■ The string and its substring
skeleton.html in Notepad. and assign it a substring of string.html in a browser. are displayed.
the first string.
¤ Add a string variable and Note: The substring is simply a
assign it a value (see ˇ Use the portion of the original string. It
Chapter 9). document.write() method to begins at the character index
display the value of the specified by the substr parameter
‹ Use the second string. (in this example, 20).
document.write() method to
display the string value. Á Save the file as string.html.
96
USING OBJECTS 7
Many of JavaScript’s predefined objects, their A predefined object exists for almost every Web
properties, and their methods are covered in page element, including browser history,
Chapters 9–11. These objects include Array, anchors, links, plug-ins, check boxes, and reset
Date, Math, and String. The Array object is buttons. Many are accessible using general
used to create and manipulate an array of browser objects. Chapters 12 and 14 discuss
variables. The Date object is used to create these in detail.
and manipulate dates and times. The Math
object is used to represent mathematical
constants such as logarithms and mathematical
expressions. The String object enables you to
work with strings.
An example of each of these objects is
MyArray = new Array(20);
MyDate = new Date(20);
Area = Math.PI * Math.pow(radius,
2);
MyString = “Welcome to here.”;
⁄ Open the file js- ‹ Use the ˇ Open math.html in a ■ The computed value is
skeleton.html in Notepad. document.write() method to browser. displayed.
display the result of a value
¤ Use the calculated from a Math
document.write() method to property and a Math method.
display some text.
› Save the file as
math.html.
97
JAVASCRIPT
Other objects, such as the Date object, need to This example uses the js-skeleton.html
be created using the new keyword and a file found on the book’s CD-ROM, but you can
function constructor. For example, to create a apply these steps to any file.
new Date object named myDate, you would
⁄ Open the file js- ‹ Use the ˇ Open the new.html file in ■ The current date and
skeleton.html in Notepad. document.write() method to a browser. month are displayed.
¤ Add a variable and assign display the values of the
it a new Date object. current date and month.
Note: This new Date object allows › Save the file as
you to retrieve the current date new.html.
using the toLocaleString()
method (see Chapter 10).
98
USING OBJECTS 7
Á Open the new.html file in ° Save the file as · Open the file new2.html ■ The current time is also
Notepad. new2.html. in a browser. displayed.
‡ Add another
document.write statement to
display the current time.
99
JAVASCRIPT
⁄ Open the file js- › Using the new keyword, ‡ Open this.html in a ■ The values of the object
skeleton.html in Notepad. create another object. browser. instance are displayed.
¤ Create a function with ˇ Using document.write
parameters. statements, display the
object’s property values.
‹ Create a property for each
parameter and assign it the Á Save the file as
parameter’s value. this.html.
100
USING OBJECTS 7
The this keyword can also be used as a This onclick event would pass the value of the
parameter that is passed to a function. For current element to the function. In this case, the
example, suppose you have a function like value of the text field would be passed.
the following:
function makeBold(text1) {
document.write(“<b>“ + text1 +
“</b>“);
}
Then, you could call this function from an
event within an HTML element like so:
<form name=“form1”>
<input type=“text” name=“text1”
onclick=“makeBold(this.value)”
</form>
⁄ Open the js- › Set the onclick event Á Open this2.html in a ‡ Click the text field.
skeleton.html file in equal to the this.select() browser.
Notepad. method. ■ The text in the text field is
selected.
¤ Add a form with a text ˇ Save the file as
field to the page. this2.html.
‹ Add the onclick event to
the text field.
101
JAVASCRIPT
⁄ Open the Notepad file. Note: For predefined objects, a ˇ Open the file ■ The browser displays
new object doesn’t need to be window.html in a browser. properties and values of the
¤ Add a for loop with the in created. window object.
keyword and an object name.
› Save the file as
‹ Use the window.html.
document.write() statement
to display the object
properties and its values.
102
USING OBJECTS 7
Á Open the window.html file ° Save the file as · Open the file ■ The properties for the new
in Notepad. location.html. location.html in a browser. object are displayed.
‡ Change the object in the
for loop.
103
JAVASCRIPT
⁄ Open the file js- › Use a document.write Á Open the array.html file ■ The array length is
skeleton.html in Notepad. statement to display the in a browser. displayed.
length of the array.
¤ Create a new Array
object. ˇ Save the file as
array.html.
‹ Assign several values to
the array.
104
USING OBJECTS 7
‡ Open the array.html file · Add another — Open the array2.html file ■ The join() method lists the
in Notepad. document.write statement in a browser. contents of the array in their
that uses the sort() method original order. The sort()
° Add another to sort and display the array. Note: The array is defined to hold method displays a sorted list of
document.write statement 10 elements, but only 5 of them the array elements.
that uses the join() method ‚ Save the file as are filled, so extra commas show
to display the contents of the array2.html. the empty array slots. ■ The array length is now
array. returned as 10 instead of 5.
105
JAVASCRIPT
⁄ Open the file js- ‹ Add document.write ˇ Open the image.html file ■ The image and its attribute
skeleton.html in Notepad. statements to display the in a browser. values are displayed.
image attribute values.
¤ Add an image to the Web
page and set the alt and › Save the file as
border attributes. image.html.
106
USING OBJECTS 7
PRELOAD IMAGES
sing a new image object, you can After creating a new image object, you can set
PRELOAD IMAGES
⁄ Open the file js- › Assign the image object’s src ‡ Load the image2.html file ■ The image defined in the
skeleton.html in Notepad. property an image filename. into a browser. image object is displayed.
¤ Add an <img/> tag to the Web ˇ Add an onload event to the Note: By preloading the image, the
page. <body> tag that loads a new browser caches a copy of it so
source image into the image that it can load quickly with the
‹ Within the <script> tags, object. rest of the page.
create a new image object.
Á Save the file as image2.html.
107
JAVASCRIPT
CHANGE IMAGES
any of the image object properties Web page. Before changing images, you should
CHANGE IMAGES
⁄ Open the file js- › Add the onclick event to ‡ Open the ■ An image and a button
skeleton.html in Notepad. the button. changeImage.html file in a appear.
browser.
¤ Add an image to the Web ˇ Within the onclick event,
page. set the image’s source
property to another image
‹ Add a simple form with a file.
single button.
Á Save the file as
changeImage.html.
108
USING OBJECTS 7
109
JAVASCRIPT
⁄ Open the file js- ‹ Within the <script> tags, ˇ Open the links.html file ■ The links and number of
skeleton.html in Notepad. add document.write in a browser. links are displayed.
statements to display the
¤ Add several links and length of the links and
anchors above the <script> anchors arrays.
tags.
› Save the file as
links.html.
110
USING OBJECTS 7
Links can be decomposed into their various The anchor object doesn’t include all the same
components by using the properties of the properties as the link object: The anchor
link object. The protocol property lists the object includes only a single property — name.
protocol for the URL, which can be something
like http: or ftp:. The hostname property
includes the domain name, and the pathname
property includes the path to the Web file. The
port property lists the port value for the Web
page, and the host property includes the
hostname and port values together. The final
piece of a URL is the anchor name, which can
be obtained from the hash property. A
complete URL can be generated from the
following:
myLink.protocol + myLink.hostname +
myLink.pathname + myLink.port +
myLink.hash
Á Open the links.html file ° Save the file as · Open the links2.html file ■ The link information is
in Notepad. links2.html. in a browser. displayed.
‡ Add several
document.write statements
to display information about
one of the links.
111
JAVASCRIPT
CHANGE LINKS
any objects contain all the various The link object shares many of the same
CHANGE LINKS
⁄ Open the js- › Add onclick to the button Á Open the ■ A single link and a button
skeleton.html file. and set the event to change the changeLink.html file in a are displayed.
href property of the link. browser.
¤ Add a link to a Web page.
Note: Changing the href property
‹ Add a form with a single in Step 4 is what actually changes
button. the link.
ˇ Save the file as
changeLink.html.
112
USING OBJECTS 7
‡ Move the mouse cursor ° Click the button on the · Move the mouse cursor ■ Notice that the link URL
over the top of the link. Web page. over the top of the link again. displayed in the status bar
has changed.
■ Notice the link URL
displayed in the status bar at Note: A good place to use this
the bottom of the window. would be to send the user off to a
random URL.
113
JAVASCRIPT
⁄ Open the file js- › Set the onclick event to Á Open the history.html ‡ Click the arrow ( ) to
skeleton.html in Notepad. move back two pages in the file in a browser. the right of the Back button
history list. to view the history list.
¤ Add a form with a single
button. ˇ Save the file as
history.html.
‹ Add the onclick event to
the button.
114
USING OBJECTS 7
The history.go() method can be used to You can prevent a user from going back with the
reload the current page. If the index is set to 0, Back button by using the
then the current page is the one in the history window.location.replace() method. This
list that is loaded. This has the same effect as a method enables you to replace the current
page refresh. The code looks like this: history list entry with a URL that is passed as a
parameter.
document.history(0);
You can set the number of places to go back
in the history list using a user-inputted value
from a form element such as a selection list
or a text field. The code to do this would look
like this:
document.history(document.form1.text1
.
value);
■ The history list is displayed · Click the button. ■ The Web page back two
in a drop-down list. places is loaded in the
browser.
° Click anywhere in the
browser window to make the
list disappear.
115
JAVASCRIPT
⁄ Open the CD file js- statements, add HTML code ˇ Open the write.html ■ The HTML code is
skeleton.html in Notepad. within single quote marks. file in a browser. displayed within the browser.
¤ Add several Note: You can find specifics on
document.write() HTML in Appendix A, or for more
statements. comprehensive coverage try Teach
Yourself Visually HTML.
‹ Within the parentheses of
the document.write() › Save the file as write.html.
116
WORKING WITH WINDOWS 8
ADD A VARIABLE ° Beneath the variable ‚ Open the write2.html ■ The text along with the
Á Open the write.html definition, add another file in a browser. variable value is displayed.
file in Notepad. document.write()
statement to display the
‡ Add a variable definition variable value.
and set it equal to a value.
· Save the file as
write2.html.
117
JAVASCRIPT
⁄ Open the ‹ Set the onload event ˇ Open the status.html ■ The line of text is displayed
skeleton.html file. equal to window.status= file in a browser. on the status bar.
and the text to display.
¤ Add the onload event to
the opening <body> tag. › Save the file as
status.html.
118
WORKING WITH WINDOWS 8
Á Open the status.html ° Save the file as · Open the status2.html Note: Link addresses are
file in Notepad. status2.html. file in a browser. displayed by the browser by
default and cannot be overwritten
‡ Add a link to a Web page. ‚ Move the mouse cursor with other text.
over the top of the link text.
■ The status bar text is
replaced with the link
reference.
119
JAVASCRIPT
⁄ Open the js- ‹ Save the file as › Open the bgColor.html ■ The Web page background
skeleton.html file. bgColor.html. file in a browser. color is set.
¤ Add the
document.bgColor
property and set it to a
color name.
120
WORKING WITH WINDOWS 8
JavaScript is case-sensitive. That means that sets the background color when this statement
the exact capitalization needs to be used, is executed, but you can change the background
including the C in bgColor. If you were to color at any time using an event. For example,
use the document.bgcolor property with a
onclick = “document.bgColor =
lowercase c, the browser would return an document.form1.text1.value”
object not recognized error. This can be
a tricky error to debug, especially because dynamically sets the background color to the
HTML is not case-sensitive. value taken from a text field whenever the event
is triggered.
A statement like
document.bgColor = “#80FFCC”
⁄ Open the js- ‹ Add a document.write ˇ Open the ■ The background color
skeleton.html file. statement within the bgColor2.html file in a value is displayed.
<script> tags that displays browser.
¤ Add the bgcolor the document.bgColor
attribute to the <body> tag property value.
and set it equal to a color.
› Save the file as
bgColor2.html.
121
JAVASCRIPT
⁄ Open the ‹ Add some text to the ˇ Open the ■ The background and
bgColor.html file. page. fgColor.html foreground colors are
¤ Add the file in a browser. displayed.
› Save the file as
document.fgColor object fgColor.html.
property and set it to a
different color than the
background color.
122
WORKING WITH WINDOWS 8
The document.fgColor property holds the A color management function could be written
value of the text color. This property can be like this:
used to display the current text color or to set
function colors(background, textCol,
the current text color with a statement like linkCol, vlinkCol) {
document.fgColor = “#80FFCC” document.bgColor = background;
You can also dynamically set the text and link document.fgColor = textCol;
colors using the value from a form text field. document.linkColor = linkCol;
For example,
document.vlinkColor = vlinkCol;
onclick = “document.fgColor = }
document.form1.text1.value”
Calling this function with specified colors sets
dynamically sets the text color to the value
the color scheme for the Web page. For
taken from a text field. Because this statement
example, the statement colors(“black”,
is executed as part of an event, the user could
“red”, “orange”, “purple”) sets the colors.
input a different color value in the text field
and trigger the onclick event to update the
text color.
⁄ Open the fgColor.html ‹ Add a link to the page. ˇ Open the ■ The link is displayed using
file in Notepad. linkColor.html the specified color.
› Save the file as file in a browser.
¤ Add the linkColor.html.
document.linkColor
object property and set it
to a different color than the
background and foreground
colors.
123
JAVASCRIPT
⁄ Open the js- › Use a document.write Á Open the title.html ■ The document title
skeleton.html file. statement to display the title file in a browser. appearing in the title bar
value. is displayed as specified.
¤ Add a variable and assign
it a string. ˇ Save the file as
title.html.
‹ Set the document’s title
using the document.title
property.
124
WORKING WITH WINDOWS 8
⁄ Open the js- ‹ Save the file as › Open the ■ The date of the last
skeleton.html file. lastModified.html. lastModified.html modification is displayed.
file in a browser.
¤ Use a document.write
statement to display the
modification date using the
document.lastModified
property.
125
JAVASCRIPT
The property that holds the Web page address When the URL is displayed in the browser
is part of the document object. This property using the document.URL statement, it is URL
is URL. Adding this property to the bottom of a encoded. This is done so that any spaces or
Web page can be accomplished with the special symbols won’t cause a problem. URL
statement document.URL. This property is a encoding can be undone with the unescape()
statement covered in Chapter 14.
VIEW THE CURRENT URL
⁄ Open the file js- ‹ Save the file as › Open the URL.html file ■ The URL for the current
skeleton.html in Notepad. URL.html. in a browser. Web page is displayed.
¤ Add a document.write()
statement to display the
current URL.
126
WORKING WITH WINDOWS 8
⁄ Open the file js- › Open another HTML file. ‡ Open the ■ The referrer.html
skeleton.html in Notepad. reflink.html file in a page loads.
ˇ Add a link to the browser.
¤ Add a document.write() referrer.html page. ■ The referring Web page
statement to display the ° Click on the link. (reflink.html) is
referring URL. Á Save the Web page as displayed.
reflink.html.
‹ Save the file as
referrer.html.
127
JAVASCRIPT
⁄ Open the Notepad file. › Also within the Á Open the open.html file ■ The Web page is displayed.
parentheses, add and set the in a browser.
¤ Within the <script> tags, width, height, and
add the window.open() resizable attributes.
statement.
ˇ Save the file as open.html.
‹ Within the parentheses,
add in quotation marks the
URL of the page to open and a
name for the new window.
128
WORKING WITH WINDOWS 8
129
JAVASCRIPT
⁄ Open the file write.html › Add the onclick event to Á Open the open.html file ° Save the file as
in Notepad. the <input/> tag and set it in Notepad. open2.html.
to window.close().
¤ Add a set of <form> tags ‡ Change the URL for the
under the <script> tags. ˇ Save the file as new window to close.html.
close.html.
‹ Create a button within the
form using an <input/> tag.
130
WORKING WITH WINDOWS 8
With several windows open, you can switch In the example in this section, you add a Close
the focus between the different windows button to the remote window. If you add a
using the window.focus() method. You can Close button to the original window, the
also force a window to lose focus with the difference is that closing the original window
window.blur() method. You can tell which will end your session and a dialog box asking
window has focus by looking at the title bar. you to confirm the command will appear.
The title bar of the window that has focus
appears a different color than the other
windows. You can change the window that
has focus by clicking in the window with the
mouse. You can also switch the focus
between the different windows using the
Alt+Tab keys.
· Open the open2.html ‚ Click the Close button in ■ The remote window
file in a browser. the remote window. closes, but the window that
opened it originally remains.
■ The Web page and a new
window are opened and
displayed.
131
JAVASCRIPT
PRINT A WINDOW
eb browsers include a button on the When a new window is opened using the
PRINT A WINDOW
⁄ Open the close.html ‹ Change the button ˇ Open the print.html Á Click the Print button on
file. value to Print and the file in a browser. the Web page.
event statement to
¤ Copy the <input/> tag window.print(). ■ A button that enables
to create another button for printing appears on the Web
the Web page. › Save the file as page.
print.html.
132
WORKING WITH WINDOWS 8
The window.print() button produces the If you create a button using window.print()
same results as the browser’s Print button and click the button, if a printer isn’t connected
included on the toolbar. In addition to this to your computer, then a dialog box will appear
method, JavaScript includes several other stating that you need to add a printer before you
methods that match toolbar features. These can print.
methods include the window.back() and
window.forward() methods, which do the
same thing as the toolbar’s Back and Forward
buttons. JavaScript also includes a window.
home() method that loads the browser’s home
page just like the Home button on the toolbar.
The function of the Stop button can also be
included within a Web page by using the
window.stop() method.
■ The Print dialog box ° Click the OK button. ■ The page is printed.
appears.
‡ Select a printer and the
print options.
133
JAVASCRIPT
MOVE A WINDOW
he window object includes a couple horizontal and vertical number of pixels the
⁄ Open the file js- › Set the parameters of the Á Open the moveTo.html ■ The entire window moves
skeleton.html in Notepad. window.moveTo() method file in a browser. to the specified coordinates.
to the value of the text fields.
¤ Add a form with two text ‡ Click the form button.
fields and a button. ˇ Save the file as
moveTo.html.
‹ Add the onclick event
to the button and set it equal
to window.moveTo().
134
WORKING WITH WINDOWS 8
One of the benefits of using JavaScript to This function causes the window to move to the
move a window is control. With several right and down 1 pixel for each time through
windows open, the window.moveTo and the loop until the 100-pixel limit is reached.
window.moveBy methods enable you to
position the newly opened window exactly
where you want it. For example, if you open a
remote window with links, you can move it to
the side of the main window.
Another useful technique that you can use is
to dynamically update the x and y values of
the window.moveBy() method to animate the
movement of the window — for example:
function moveDiag() {
for (i=1;I<100;I++)
window.moveBy(i,i)
}
USING WINDOW.MOVEBY()
⁄ Open the moveTo.html ‹ Change the name of the ˇ Open the moveBy.html ■ The window moves the
file in Notepad. button. file in a browser. amount specified.
¤ Change the › Save the file as Á Click the form button.
window.moveTo() method moveBy.html.
to the window.moveBy()
method.
135
JAVASCRIPT
RESIZE A WINDOW
he window object also includes a couple increases the width of the window by 10 pixels
USING WINDOW.RESIZETO()
⁄ Open the file moveTo.html ‹ Change the value of the ˇ Open the resizeTo.html ■ The window is resized to
in Notepad. text in the text boxes and the file in a browser. the specified coordinates.
name of the button.
¤ Change the Á Click the form button.
window.moveTo() method › Save the file as
to window.resizeTo(). resizeTo.html.
136
WORKING WITH WINDOWS 8
USING WINDOW.RESIZEBY()
⁄ Open the resizeTo.html ‹ Change the name of the ˇ Open the resizeBy.html ■ The window is increased by
file. button. file in a browser. the amount specified.
¤ Change the › Save the file as Á Click the form button.
window.resizeTo() method resizeBy.html.
to the window.resizeBy()
method.
137
JAVASCRIPT
⁄ Open the file js- ‹ Save the file as › Open the alert.html ˇ Click the OK button.
skeleton.html in Notepad. alert.html. file in a browser.
¤ Within the <script> tags, ■ An alert dialog box appears
add the window.alert() with the message in it.
method to display a message.
138
WORKING WITH WINDOWS 8
Á Open the file js- ° Set the onload event ‚ Open the alert2.html Note: Alert dialog boxes can
skeleton.html in Notepad. equal to the window.alert() file in a browser. be opened by placing the
method to display a message. window.alert statement
‡ Within the <body> tags, ■ An alert dialog box appears within the <script> tags or
add an onload event. · Save the file as with the message in it. within an event.
alert2.html.
— Click the OK button.
139
JAVASCRIPT
⁄ Open the CD file js- ‹ Add several ˇ Open the prompt.html ■ A prompt dialog box
skeleton.html in Notepad. document.write() file in a browser. appears with a message in it.
methods to display the
¤ Within the <script> tags, variable’s value.
declare a variable and set it
equal to the results of the › Save the file as
window.prompt() method. prompt.html.
140
WORKING WITH WINDOWS 8
Á Type a name in the text ‡ Click the OK button. ■ The personalized page is
field. displayed.
141
JAVASCRIPT
⁄ Open the file js- ‹ Add an if-else ˇ Open the confirm.html Á Click the OK button.
skeleton.html in Notepad. statement that checks the file in a browser.
value of the confirm dialog
¤ Declare a variable and set box and displays appropriate ■ A confirm dialog box
it equal to the results of the text. appears with a question in it.
window.confirm() method.
› Save the file as
confirm.html.
142
WORKING WITH WINDOWS 8
One place that the confirm dialog box can be When this reset button is clicked, the
used is to double-check with the user before confirmReset() function is called and a
an action is taken. For instance, Web page confirm dialog box is displayed. If the user clicks
forms typically have a Reset button that resets OK, the page form is reset. If the Cancel button
all the form elements to their default values. is clicked, the form is not reset.
A function can be created that enables the
user to confirm the Reset action:
function confirmReset() {
check = window.confirm(“Are you
sure you want to reset this form?”);
if (check)
document.form1.reset1.click();
}
<form name=”form1”>
<input type=”reset” name=”reset1”
onclick=”confirmReset()”>
</form>
■ A positive message is ‡ Click Refresh to reload the ° Click the Cancel button. ■ A different message is
displayed. Web page. displayed.
143
JAVASCRIPT
⁄ Open the file js- › Add a document.write() Á Open the string.html ■ The string is displayed
skeleton.html in Notepad. statement to display the string file in a browser. normally and in bold.
formatted with the bold()
¤ Create a string variable and method.
assign it a value.
ˇ Save the file as
‹ Use a document.write() string.html.
statement to display the value
of the string.
144
WORKING WITH STRINGS 9
string objects by default are created Single-quote marks can be used in place of
whenever a string variable is declared. double-quote marks. In some places, you
Strings are assigned to any variable that has may want to use a set of each. For example,
a pair of quotes in the definition. You can if you specify a document.write
also create string objects using the new statement within an event, the quotes for the
keyword, but it is not necessary. To do this, document.write statement need to be
you need to list a name for the string and set different from the event quotes.
it equal to new String(). For example,
the JavaScript statement string1 = new
String(); creates a new string object, and
string1.bold(); calls the bold()
method for that string.
⁄ Open the string.html ‹ Save the file as › Open the string2.html ■ The string is displayed in
file in Notepad. string2.html. file in a browser. uppercase.
¤ Add a document.write()
statement to display the string
converted to uppercase.
145
JAVASCRIPT
⁄ Open the file js- › Add a document.write() Á Open the substring.html Note: The substring started at the
skeleton.html in Notepad. statement to display the file in a browser. first position, as specified by the
substring created with the first parameter, 0, and ended at
¤ Create a string variable and substring() method. ■ The string and its substring string index 13 (a space), as
assign it a value. are displayed. specified by the second
ˇ Save the file as parameter.
‹ Use a document.write() substring.html.
statement to display the value
of the string.
146
WORKING WITH STRINGS 9
‡ Open the file · Save the file as ‚ Open the Note: The substring started at the
substring.html in substring2.html. substring2.html position specified by the first
Notepad. file in a browser. parameter, string index 20, and
continued for the length specified
° Add a document.write() ■ The string and two by the second parameter — 11
statement to display another substrings are displayed. characters.
substring created with the
substr() method.
147
JAVASCRIPT
CONCATENATE STRINGS
he substring() and substr() Another easy way to combine strings is with
CONCATENATE STRINGS
⁄ Open the file js- › Add a document.write() Á Open the concat.html ■ The strings are displayed
skeleton.html in Notepad. statement to display the file in a browser. separate and combined.
strings combined with the
¤ Create two string variables concat() method.
and assign them values.
ˇ Save the file as
‹ Use document.write() concat.html.
statements to display the
values of both strings.
148
WORKING WITH STRINGS 9
Strings are enclosed within quote marks, so This statement displays the quote marks around
how do you display a quote mark? Any the quoted word. Other escape characters
character that cannot be printed by including include the single quote (\’), the backslash
it within the string quotes is called an escaped (\\), the backspace (\b), the tab (\t), the new
character. When working with strings, you line (\n), the carriage return (\r), and a form
can include special escape characters such as feed (\f).
the quote mark if it is preceded by a
backslash (\). For example, to include quotes For example, str2 = “The file is
around a word in a string, use the backslash located in the C:\\temp\\test
character like this: directory.”; correctly displays the
backspace characters.
str1 = “He responded, \”Hooray\”
when he was finished.”
⁄ Open the file ‹ Save the file as › Open the concat2.html Note: There isn’t an advantage to
concat.html in Notepad. concat2.html. file in a browser. using the concat() method
over the addition assignment
¤ Add a document.write() ■ The second combined operator.
statement to display the string string is now displayed.
combined with the + operator.
149
JAVASCRIPT
⁄ Open the file js- › Add several Á Open the file ■ The string is displayed
skeleton.html in Notepad. document.write() format.html in a browser. normally and with formatting.
statements to display the
¤ Create a string variable and string with different formats,
give it a value. using some of the string-
‹ Use a document.write() formatting methods.
statement to display the value ˇ Save the file as
of the string. format.html.
150
WORKING WITH STRINGS 9
‡ Open the file · Save the file as ‚ Open the format2.html ■ The string is displayed with
format.html in Notepad. format2.html. file in a browser. a different font size and color.
° Add a document.write()
statement to display the string
with a different font size and
color.
151
JAVASCRIPT
⁄ Open the file js- › Create a couple Á Open the link.html file ■ The anchors and links are
skeleton.html in Notepad. anchors and links by using in a browser. displayed.
the anchor() and link()
¤ Create string variables and methods. Set the links to point
assign each a value. to the anchors, including the
‹ Use for and number symbol (#) in front
document.write() statements of them.
to display the strings’ values. ˇ Save the file as link.html.
152
WORKING WITH STRINGS 9
The anchor() method can accept any string If you use an anchor name within the link()
or variable value to be used as the anchor method, a link will be established to the anchor.
name. The parameters to the link() The anchor needs to include a number symbol
method must be a valid URL or location. (#) in front of the anchor name. The href
Using the link() method with an invalid parameter that is passed to the link() method
URL does not cause the script to error, but can be either a relative URL or an absolute URL.
the link will not be available when clicked. Absolute URLs must include a protocol such as
http.
‡ Move the mouse over the ■ Notice how the status bar ° Move the mouse over the ■ Notice how the status bar
first link. reveals that the link points to second link. reveals that the link points to
the anchor name. the other anchor name.
153
JAVASCRIPT
⁄ Open the file js- ‹ Use document.write() ˇ Open the length.html ■ The string and its length
skeleton.html in Notepad. statements to display the file in a browser. are displayed.
string and the value of the
¤ Within the <script> length of the string.
tags, create a string variable
and assign it a value. › Save the file as
length.html.
154
WORKING WITH STRINGS 9
CHANGE CASE
f a string is inputted to your script in all lowercase (or all
CHANGE CASE
⁄ Open the file js- ‹ Add document.write() ˇ Open the case.html file ■ The string is displayed in
skeleton.html in Notepad. statements to display the in a browser. all lower- and uppercase.
string as it appears initially
¤ Within the <script> tags, and then converted to
create a string variable and uppercase and lowercase.
assign it a value.
› Save the file as
case.html.
155
JAVASCRIPT
⁄ Open the file js- › Add another Á Open the search.html ■ The string and its index are
skeleton.html in Notepad. document.write() file in a browser. displayed.
statement to display the
¤ Create a string variable and index of a word in the string.
assign it a value.
ˇ Save the file as
‹ Use a document.write() search.html.
statement to display the value
of the string.
156
WORKING WITH STRINGS 9
‡ Open the search.html · Save the file as ‚ Open the ■ The string index is
file in Notepad. search2.html. search2.html file in a returned as -1.
browser.
° Change the parameter of
the search() method to
search for a string that
doesn’t exist.
157
JAVASCRIPT
⁄ Open the file js- ‹ Use document.write() ˇ Open the indexOf.html ■ The string and the index of
skeleton.html from the statements to display the file in a browser. the second and are displayed.
CD-ROM in Notepad. value of the string and the
index of the second ‘and’.
¤ Within the <script> tags,
create a string variable and › Save the file as
assign it a value. indexOf.html.
158
WORKING WITH STRINGS 9
⁄ Open the file ‹ Save the file as › Open the ■ The string and the index of
indexOf.html in Notepad. lastIndexOf.html. lastIndexOf.html the second and are displayed.
file in a browser.
¤ Use the lastIndexOf()
method to display the index
of the second and.
159
JAVASCRIPT
⁄ Open the file js- › Use the replace() Á Open the replace.html Note: Only the first and was
skeleton.html in Notepad. method within another file in a browser. replaced because the replace()
document.write() method was used only once.
¤ Create a string variable and statement to replace the ■ The string is displayed
assign it a value. word and with a comma. normally and with the
replacement.
‹ Use a document.write() ˇ Save the file as
statement to display the value replace.html.
of the string.
160
WORKING WITH STRINGS 9
All the search strings within a string can be This code checks for the existence of the search
replaced at once using a while loop such as string, and if found, it uses the replace() method
the following: to replace it. If the search string isn’t found
within the string, the loop condition fails and the
str1 = “standard string”; program continues.
searchStr = “str”;
repStr = “tr”;
while (str1.search(searchStr) !=
-1) {
str1.replace(searchStr,
repStr);
}
⁄ Open the file ‹ Save the file as › Open the ■ The string and the index of
indexOf.html in Notepad. lastIndexOf.html. lastIndexOf.html the second and are displayed.
file in a browser.
¤ Use the lastIndexOf()
method to display the index
of the second and.
161
JAVASCRIPT
SPLIT A STRING
sing JavaScript, you can split a string the split() method with the space as a
SPLIT A STRING
⁄ Open the file js- › Use the replace() Á Open the replace.html Note: Only the first and was
skeleton.html in Notepad. method within another file in a browser. replaced because the replace()
document.write() method was used only once.
¤ Create a string variable and statement to replace the ■ The string is displayed
assign it a value. word and with a comma. normally and with the
replacement.
‹ Use a document.write() ˇ Save the file as
statement to display the value replace.html.
of the string.
162
WORKING WITH STRINGS 9
You can use a textarea to obtain a list of This simple function separates list items using
items. If you have the user place a symbol the split() method and places each item as
such as an asterisk (*) in front of each list an element in an array. You can view the list
item in the textarea box, you can use the using this code:
split() method to separate the list items
into an array. A function to do this would look for (j=0;j<listArray.length;j++) {
like this: document.write(“List item “ + j
function textList(text) { + “: “ + listArray[j]);
listArray = text.split(“*”); }
‡ Open the file · Save the file as ‚ Open the replace2.html ■ The updated string is
replace.html in Notepad. replace2.html. file in a browser. displayed.
° Add another
document.write()
statement to display the string
with another replacement.
163
JAVASCRIPT
⁄ Open the file js- ‹ Use a document.write ˇ Open the new.html file in ■ The time and date are
skeleton.html in Notepad. statement to display the date. a browser. displayed.
¤ Create a new date object › Save the file as
including a format within the new.html.
Date() parentheses.
Note: In this example, I’ve used
the first date format.
164
WORKING WITH DATES AND TIMES 10
Á Open the new.html file in ° Save the file as · Open the new2.html file ■ The new time and date are
Notepad. new2.html. in a browser. displayed.
‡ Change the format in the Note: The index for months starts
Date() object. with 0, so 0 is January, 1 is
February, and so on, which is why
Note: In this example, I’ve used
February is returned in this
the third date format.
example.
165
JAVASCRIPT
⁄ Open the file js- ‹ Use a document.write ˇ Open the date.html file ■ The time and date for
skeleton.html in Notepad. statement to display the in a browser. Greenwich mean time is
Greenwich mean time. displayed.
¤ Create a new date object.
› Save the file as
date.html.
166
WORKING WITH DATES AND TIMES 10
The format of the date object remains the symbols (/) are placed between the date
same displaying the day, date, time, and time numbers. For example, the format for this
zone if you use the toGMTString() method is 04/14/2000 13:05:13. You can
method. This method displays the day and also use the toString() method to display
month using three characters, such as Fri for the date object. This format looks different still
Friday and Apr for April. For example, this with the year at the end of the string. For
format looks like this: Fri, 14 Apr 2000 example, this format looks like Fri Apr 14
19:01:54 UTC. The date format for the 13:06:23 MDT 2000. If you want to use a
toLocaleString() method is a little custom format, you can use the get methods to
different. This method displays only numbers format the date, as shown in the next section,
with the date first and then the time. Slash “Get Time and Date Values.”
⁄ Open the date.html file ‹ Save the file as › Open the date2.html file ■ The local time and date are
in Notepad. date2.html. in a browser. displayed.
¤ Change the
toGMTString() method to
toLocaleString() and
update the displayed text.
167
JAVASCRIPT
⁄ Open the file js- ‹ Use document.write ˇ Open the getDate.html ■ The values for the current
skeleton.html in Notepad. statements to display the get file in a browser. date are displayed.
methods for the current date.
¤ Create a new date object.
› Save the file as
getDate.html.
168
WORKING WITH DATES AND TIMES 10
⁄ Open the getDate.html ‹ Save the file as › Open the getDate2.html ■ The values for the current
file in Notepad. getDate2.html. file in a browser. time are displayed.
¤ Add several additional
document.write statements
to display the values of the
get methods for the current
time.
169
JAVASCRIPT
⁄ Open the file js- › Change the month, date, Á Open the setDate.html ■ The date before and after
skeleton.html in Notepad. and year values using the set file in a browser. the changes is shown.
methods and display the
¤ Create a new date object results.
and set the initial date within
the parentheses. ˇ Save the file as
setDate.html.
‹ Use a document.write
statement to display the
initial date.
170
WORKING WITH DATES AND TIMES 10
If you enable a user to enter a date such as function birthday() {
their birthday using a Web page form, you
can create and save the entire date object. myBirthday = new Date();
The date object can then be manipulated myBirthday.setMonth(document.form1.
and used as needed. For example, you could text1.value);.
compute how many days until their next myBirthday.setDate(document.form1.
birthday or display a unique page on their text2.value);.
birthday. A function to create such a date myBirthday.setYear(document.form1.
would look like this: text3.value);
document.write(“Your birthday is
“ + myBirthday);
}
This function creates a new date object and
sets the date’s month, date, and year based on
the values of three text fields found on a Web
page form named form1.
SET TIME VALUES
⁄ Open the setDate.html ‹ Save the file as › Open the setDate2.html ■ The initial time and
file in Notepad. setDate2.html. file in a browser. changed time are displayed.
¤ Change the hours,
minutes, and seconds using
the set methods and display
the results.
171
JAVASCRIPT
⁄ Open the file js- ‹ Use a document.write ˇ Open the getTime.html ■ The results of the
skeleton.html in Notepad. statement to display the file in a browser. getTime() method are
results of the getTime() displayed.
¤ Create a new date object. method.
› Save the file as
getTime.html.
172
WORKING WITH DATES AND TIMES 10
Á Open the file ° Use a document.write ‚ Open the parse.html file ■ The number of
getTime.html in Notepad. and a Date.parse() in a browser. milliseconds since January 1,
statement to display the 1970 for this date are
‡ Create another date number of milliseconds since displayed.
object and set its date. January 1, 1970 for this date.
· Save the file as
parse.html.
173
JAVASCRIPT
⁄ Open the file js- › Add another Á Open the file ■ The local time and date
skeleton.html in Notepad. document.write statement to getTimezoneOffset.html in and the time zone offset are
display the time zone offset. a browser. displayed.
¤ Create a new date object.
ˇ Save the file as
‹ Use a document.write getTimezoneOffset.html.
statement to display the
current local time and date.
174
WORKING WITH DATES AND TIMES 10
The time zone offset value that is returned by The getTimezoneOffset() method doesn’t
the getTimezoneOffset() method is need to directly handle daylight saving time
based on the user’s internal computer because DST is computed and controlled by the
system. For a Windows-based system, this operating system. Because JavaScript queries the
value is retrieved from the system setting that system for this information, it automatically
is configured using the Control Panel Date converts your date and time settings to
application. If the date and time specified in accommodate for the changes caused by
this system application is incorrect, the date daylight saving time.
object methods will return incorrect values
for the date object.
‡ Open the Note: To display the time in a ‚ Open the ■ The local and neighboring
getTimezoneOffset.html file neighboring time zone, you getTimezoneOffset2.html time zone times are
in Notepad. typically only need to add or file in a browser. displayed.
subtract an hour from the time.
° Add another
document.write statement to · Save the file as
display the time in the getTimezoneOffset2.html.
neighboring time zone.
175
JAVASCRIPT
⁄ Open the file js- › Add a statement for the Á Open the math.html file ■ A form with two text boxes
skeleton.html in Notepad. onclick event that computes in a browser. and a button is displayed.
the area of a circle based on
¤ Add a form with two text the text box value.
boxes and a button.
ˇ Save the file as math.html.
‹ Add the onclick event to
the button.
176
USING THE MATH OBJECT 11
Each Math object method returns a value The Math object keyword that appears in
based on the number that is passed as a front of the properties and methods always
parameter. The number passed in as a needs to be capitalized. JavaScript is case-
parameter could be an actual number or sensitive and does not work if capitalized
another object. For example, incorrectly.
Math.pow(2,3) returns a value of 8,
which is the value of 2 raised to the power
of 3. The JavaScript statement
Math.cos(document.form1.text1.
value) returns the cosine of the value
found in the text box named text1 on the
form named form1.
‡ Enter a number in the first ° Click the form button. ■ The computed answer is
text box. displayed in the second text
box.
177
JAVASCRIPT
⁄ Open the file js- › Create a variable using the ‡ Open the random.html file ° Click the Refresh button
skeleton.html in Math.floor() and
Notepad. Math.random() methods in a browser. on the browser.
and multiply
¤ Within the <script> Math.random() by the ■ A quote is displayed in the
tags, create a new array using array’s length. browser.
the Array keyword.
ˇ Display a quote using
‹ Add several quotes to the document.write().
array enclosed in quotation
marks and separated with Á Save the file as
commas. random.html.
178
USING THE MATH OBJECT 11
To select options based on random numbers, The first statement generates a random number
you can use a series of if and else if between 1 and 3. Statements can be placed in
statements. For example, consider the the braced sections for each option.
following function:
function threeOptions() {
rand =
Math.floor(Math.random() * 3);
if (rand == 1) {
document.write(“option 1”);
}
else if (rand == 2) {
document.write(“option 2”);
}
else {
document.write(“option 3”);
}
}
■ The page is reloaded and · Click the Refresh button ■ The page is again reloaded
another quote is displayed. again. and another quote is
displayed.
179
JAVASCRIPT
⁄ Open the file js- ‹ Save the file as › Open the file ■ All the Math object
skeleton.html in Notepad. constants.html. constants.html in a constants are displayed.
browser.
¤ Use document.write
statements to display the
values of all the mathematical
constants and a heading.
180
USING THE MATH OBJECT 11
Many different mathematical equations rely If the Math object doesn’t include a specific
on these constants. Some of these constants constant that you need, you can create a global
can be computed using the other Math object variable and assign it the needed variable. This
methods. For example, the Math.LN10 variable could then be used throughout the
constant can be computed using the script.
Math.log() method that is used to
compute the natural logarithm of a number.
The reason this number is defined as a
constant is that it appears in many useful
equations and, as a constant, it can be quickly
included and computed as part of a JavaScript
statement.
⁄ Open the file js- › Add a statement for the Á Open the file ° Click the form button.
skeleton.html in Notepad. onclick event that computes sphere.html in a browser.
the area of a sphere based on ■ The computed answer is
¤ Add a form with two text the text box value. ‡ Enter a number in the first displayed in the second text
boxes and a button. text box. box.
ˇ Save the file as
‹ Add the onclick event to sphere.html.
the button.
181
JAVASCRIPT
⁄ Open the file js- ‹ Add the onchange event to Á Open the trig.html file in a ■ A form with six text boxes
skeleton.html in Notepad. each text box for the side browser. is displayed.
lengths.
¤ Add a heading and a form
with six text boxes. Make › Set each onchange event
three text boxes to hold the equal to the trigonometric
values of the sides of a equation for computing the
triangle and three to hold the angle values.
trigonometric angle values.
ˇ Save the file as trig.html.
182
USING THE MATH OBJECT 11
To convert the angles measured in radians to The function takes a radian value and returns an
degrees, you can use a function like this one: equivalent value in degrees. A similar function
can be created to convert degrees back to
function radiansToDegrees(rads) { radians. Such a function looks like this:
degrees = (360 * rads / (2 * function degreesToRadians(degrees)
Math.PI)); {
return degrees; radians = (2 * Math.PI *
} degrees) / 360);
return radians;
}
This function takes a value in degrees as a
parameter and returns the same value measured
in radians.
‡ Enter a number into each ■ The computed angle ° Change the values in the ■ The computed angle
of the side text boxes, making values are displayed. side text boxes, again making values are updated and
sure that the sides are those sure that the sides are those displayed.
of a right triangle. of a right triangle.
183
JAVASCRIPT
⁄ Open the file js- › Add a statement for the Á Open the log.html file in ° Click the form button.
skeleton.html in Notepad. onclick event that computes a browser.
the log and the exp of the ■ The computed answers are
¤ Add a form with three text value. ‡ Enter a number in the first displayed in the other text
boxes and a button. text box. boxes.
ˇ Save the file as log.html.
‹ Add the onclick event to
the button.
184
USING THE MATH OBJECT 11
J
avaScript also includes a method for computing the
square root of a number. This computation is The Math.SQRT1_2 and
accomplished with the sqrt() method. Math.SQRT2 properties are
The sqrt() method receives a number as a parameter and constants for values returned
returns its square root. by Math.sqrt(1/2) and
Math.sqrt(2). The
An example of where the sqrt() method is used is in Math.sqrt() method can be
computing the Pythagorean theorem (the square of two used to return the square root
sides of a right triangle equals the square of the of any number.
hypotenuse).
This example uses the js-skeleton.html file found on
the book’s CD-ROM, but you can apply these steps to any
file.
⁄ Open the file js- › Add a statement for the Á Open the sqrt.html file ° Click the form button.
skeleton.html in Notepad. onclick event that computes in a browser.
the square root of the value ■ The computed value is
¤ Add a form with two text in the first text box. ‡ Enter a number in the first displayed in the second text
boxes and a button. text box. box.
ˇ Save the file as sqrt.html.
‹ Add the onclick event to
the button.
185
JAVASCRIPT
ROUND NUMBERS
I
f you’re dealing with floating-point numbers
JavaScript also includes a couple of
that include a decimal point, you can
methods that enable you to round
eliminate the numbers after the decimal
numbers up to the next nearest
point by using the round() method.
integer or down to the nearest integer.
This method changes any floating-point These methods are ceil() and
number to the closest integer. Any decimal floor(). For example, the following
value less than 0.5 converts the number to the statements are both rounded to a
lower integer value. Any decimal value equal to value of 5:
or greater than 0.5 rounds up to the next
ceil(4.65);
greatest integer.
floor(5.76);
For example, the number 4.45 rounds down to
the integer 4, and a value of 4.50 rounds up to
the integer 5.
ROUND NUMBERS
⁄ Open the file js- › Add a statement for the Á Open the round.html file ° Click the form button.
skeleton.html from the CD- onclick event that rounds in a browser.
ROM in Notepad. the value. ■ The rounded value is
‡ Enter a number in the first displayed in the second text
¤ Add a form with two text ˇ Save the file as text box. box.
boxes and a button. round.html.
‹ Add the onclick event to
the button.
186
USING THE MATH OBJECT 11
⁄ Open the file js- › Add a statement for the Á Open the pow.html file in ° Click the form button.
skeleton.html in Notepad. onclick event that computes a browser.
the value of the first text box ■ The resulting value is
¤ Add a form with three text raised to the power of the ‡ Enter numbers in the first displayed in the third text
boxes and a button. second text box. two text boxes. box.
‹ Add the onclick event to ˇ Save the file as pow.html.
the button.
187
JAVASCRIPT
⁄ Open the file js- › Add a statement for the Á Open the min-max.html ° Click the form button.
skeleton.html from the CD- onclick event that file in a browser.
ROM in Notepad. determines the maximum ■ The minimum and
and minimum values in the ‡ Enter numbers in the first maximum values are
¤ Add a form with four text first two text boxes. two text boxes. displayed.
boxes and a button.
ˇ Save the file as min-
‹ Add the onclick event to max.html.
the button.
188
USING THE MATH OBJECT 11
⁄ Open the file js- › Add a statement for the Á Open the abs.html file in ° Click the form button.
skeleton.html in Notepad. onclick event that computes a browser.
the absolute value of the ■ The absolute value of the
¤ Add a form with two text value in the first text box. ‡ Enter a number in the first number is displayed.
boxes and a button. text box.
ˇ Save the file as abs.html.
‹ Add the onclick event to
the button.
189
JAVASCRIPT
⁄ Open the file js- ‹ Add several ˇ Open the text.html file ■ A text box is displayed with
skeleton.html in Notepad. document.write statements in a browser. its property values.
to display some of the text
¤ Before the <script> tags, box object properties.
add a form with a single text
box. › Save the file as text.html.
190
WORKING WITH FORMS 12
⁄ Open the file js- ‹ Add the onfocus event to ˇ Open the text2.html file Á Click in the text box.
skeleton.html in Notepad. the text box and assign it the in a browser.
select() method. ■ The text within the text box
¤ Add a form with a text box is selected.
to the Web page. › Save the file as
text2.html.
191
JAVASCRIPT
⁄ Open the file js- ‹ Add several ˇ Open the password.html ■ A password box is
skeleton.html in Notepad. document.write statements file in a browser. displayed with its property
to display some of the values.
¤ Before the <script> tags, password object properties.
add a form with a single
password box. › Save the file as
password.html.
192
WORKING WITH FORMS 12
⁄ Open the file js- ‹ Add several ˇ Open the hidden.html file ■ The hidden object
skeleton.html in Notepad. document.write statements in a browser. properties are displayed.
to display some of the hidden
¤ Before the <script> tags, object properties.
add a form with a hidden
field. › Save the file as
hidden.html.
193
JAVASCRIPT
⁄ Open the file js- ‹ Add several ˇ Open the textarea.html ■ A textarea box is
skeleton.html in Notepad. document.write statements file in a browser. displayed with its property
to display some of the values.
¤ Before the <script> tags, textarea object properties.
add a form with a textarea
box. › Save the file as
textarea.html.
194
WORKING WITH FORMS 12
The textarea properties can be combined This form presents a textarea box with the riddle
with an event to update the text within a question displayed within it. When the user
textarea box. For example, imagine listing a clicks in the textarea box or when it gets focus,
riddle and showing the answer when the user the onfocus event is fired and the JavaScript
clicks in the box. The code looks like this: statement is executed, which replaces the
question with the appropriate answer.
<form name=“form1”>
<textarea name=“ta1” rows=“4”
onfocus=“document.form1.ta1.value=‘I
have you covered.’”>What did the rug
say to the floor?</textarea>
</form>
⁄ Open the file js- ‹ Add the onfocus event to ˇ Open the textarea2.html Á Click in the textarea box.
skeleton.html in Notepad. the textarea box and assign it file in a browser.
the select() method. ■ The text within the text box
¤ Add a form with a textarea is selected.
box to the Web page. › Save the file as
textarea2.html.
195
JAVASCRIPT
USING BUTTONS
sing HTML, you may make form buttons button properties include enabled, form,
⁄ Open the file js- ‹ Add several ˇ Open the button.html file ■ A button is displayed with
skeleton.html in Notepad. document.write statements in a browser. its property values.
to display some of the
¤ Before the <script> tags, button object properties.
add a form with a button.
› Save the file as
button.html.
196
WORKING WITH FORMS 12
⁄ Open the file js- ‹ Add the onclick event to ˇ Open the button2.html Á Click the button.
skeleton.html in Notepad. the button and assign it a file in a browser.
statement to update the text ■ The text specified by the
¤ Add a form with a text box box. onclick event is displayed in
and a button to the Web the text box.
page. › Save the file as
button2.html.
197
JAVASCRIPT
⁄ Open the file js- ‹ Add several ˇ Open the reset.html file ■ A Reset button is displayed
skeleton.html in Notepad. document.write statements in a browser. with its property values.
to display some of the reset
¤ Before the <script> tags, object properties.
add a form with a Reset
button. › Save the file as
reset.html.
198
WORKING WITH FORMS 12
The submit object includes properties for The form object also includes the submit()
enabled, form, name, and value, as well as method. This method can be used to simulate
the click() and focus() methods. the results of a Submit button, which submits
a form.
This example uses the js-skeleton.html
file found on the book’s CD-ROM, but you can
apply these steps to any file.
⁄ Open the file js- ‹ Add several ˇ Open the submit.html file ■ A Submit button is
skeleton.html in Notepad. document.write statements in a browser. displayed with its property
to display some of the values.
¤ Before the <script> tags, submit object properties.
add a form with a Submit
button. › Save the file as
submit.html.
199
JAVASCRIPT
⁄ Open the file js- ‹ Add several ˇ Open the checkbox.html ■ The check box is displayed
skeleton.html in Notepad. document.write statements file in a browser. with its property values.
to display some of the
¤ Before the <script> tags, checkbox object properties.
add a form with a check box.
› Save the file as
checkbox.html.
200
WORKING WITH FORMS 12
You can set up a function that executes This function runs the statements associated
statements based on which check boxes are with each checked check box. If all three are
selected. Such a function looks like this: selected, the browser displays all three
statements.
function check() {
if (document.form1.check1.checked
== true)
document.write(“Checkbox 1 is
selected”);
if (document.form1.check2.checked
== true)
document.write(“Checkbox 2 is
selected”);
if (document.form1.check3.checked
== true)
document.write(“Checkbox 3 is
selected”);
}
⁄ Open the file js- ‹ Add the onclick event to ˇ Open the checkbox2.html Á Click the button.
skeleton.html in Notepad. the button and assign it a file in a browser.
statement for each check box ■ All check boxes are
¤ Add a form with several that checks the check box. checked ( ).
check boxes and a button to
the Web page. › Save the file as
checkbox2.html.
201
JAVASCRIPT
⁄ Open the file js- ‹ Add several ˇ Open the radio.html file ■ The radio buttons are
skeleton.html in Notepad. document.write statements in a browser. displayed with their property
to display some of the radio values.
¤ Before the <script> tags, object properties.
add a form with a set of
radio buttons. › Save the file as
radio.html.
202
WORKING WITH FORMS 12
You can set up a function that executes This function is a little different than the
statements based on which radio button is example for check boxes because radio buttons
selected. Such a function looks like this: are mutually exclusive. This means that only one
radio button at a time can be selected.
function radio() {
if (document.form1.radio1.checked
== true)
document.write(“Radio button 1
is selected”);
else if (document.form1.
radio2.checked == true)
document.write(“Radio button 2
is selected”);
else
document.write(“Radio button 3
is selected”);
}
⁄ Open the file js- ‹ Add the onclick event to ˇ Open the radio2.html file ■ The text in the text box is
skeleton.html in Notepad. each radio button and assign in a browser. updated.
it a statement that updates
¤ Add a form with several the text box text. Á Click a radio button.
radio buttons and a text box
to the Web page. › Save the file as
radio2.html.
203
JAVASCRIPT
⁄ Open the file js- ‹ Add several ˇ Open the select.html file ‡ Click your browser’s
skeleton.html in Notepad. document.write statements in a browser. Refresh button.
to display some of the
¤ Before the <script> tags, select object properties. ■ The selection list is ■ The selected list item’s
add a form with a selection displayed with its property property value updates.
list. › Save the file as values.
select.html.
Á Click an item in the list.
204
WORKING WITH FORMS 12
⁄ Open the file js- › Add a function that Á Open the select2.html ‡ Click one of the list items.
skeleton.html in Notepad. updates the text box based on file in a browser.
the list item that is selected. ■ The text in the text box is
¤ Add a form with a updated.
selection list and a text box to ˇ Save the file as
the Web page. select2.html.
‹ Add the onchange event to
the selection list and assign it
a function.
205
JAVASCRIPT
⁄ Open the file js- ‹ Add several ˇ Open the option.html file ■ The selection list is
skeleton.html from the CD- document.write statements in a browser. displayed with the properties
ROM in Notepad. to display some of the for a single list item, as
option object properties. specified by the
¤ Before the <script> tags, document.write statements
add a form with a selection › Save the file as in this example.
list. option.html.
206
WORKING WITH FORMS 12
Selection lists can accept only a single The option object includes other properties,
selection. If you add the multiple attribute such as index, length, name, and value.
to the <select> tag, the selection list allows
The option object doesn’t include any methods.
multiple list items to be selected. If the
multiple attribute is included, then the user
can select multiple list items by holding down
the Ctrl or Shift keys. The multiple attribute
is covered in the next section, “Work with a
Multiple-Selection List.”
If the size attribute isn’t specified, then only
a single list item is initially displayed. The list
will include an arrow to its right that will
reveal the rest of the list items if it is clicked
on. Because the selection list doesn’t include
any way to scroll horizontally, the width of
the entire list is determined by the width of
the longest list item element.
⁄ Open the file js- ‹ Add the onclick event to Á Open the option2.html ‡ Click the form button.
skeleton.html in Notepad. the button and assign it a file in a browser.
function. ■ The list item text is
¤ Add a form with a updated.
selection list and a button to › Add a function that
the Web page. updates the selection list
items.
ˇ Save the file as
option2.html.
207
JAVASCRIPT
⁄ Open the file js- ‹ Add several ˇ Open the multiple.html ■ The selection list is
skeleton.html in Notepad. document.write statements file in a browser. displayed with none of the
to display the selected list items selected.
¤ Before the <script> tags, property for each of the list
add a form with a multiple items.
selection list.
› Save the file as
multiple.html.
208
WORKING WITH FORMS 12
Á Select several list items ‡ Click your browser’s ° Select all the list items · Click your browser’s
while holding down the Ctrl reload button. while holding down the Ctrl reload button.
key. key.
■ The selected property for ■ The selected property for
the selected list items is true. all the list items is true.
209
JAVASCRIPT
⁄ Open the file js- › Add several Á Open the disabled.html ■ The form elements are all
skeleton.html in Notepad. document.write statements file in a browser. disabled.
to display the disabled
¤ Before the <script> tags,
add a form with a selection property.
list, a text box, and a check ˇ Save the file as
box. disabled.html.
‹ Add the disabled
attribute to all form elements.
210
WORKING WITH FORMS 12
‡ Open the file · Save the file as ‚ Open the disabled2.html ■ Several previously disabled
disabled.html in Notepad. disabled2.html. file in a browser. form elements are now
enabled.
° Remove some of the
disabled attributes from the
form elements.
211
JAVASCRIPT
⁄ Open the file js- ‹ Add several ˇ Open the form.html file ■ The form is displayed with
skeleton.html in Notepad. document.write statements in a browser. its properties.
to display some of the form
¤ Before the <script> tags, object properties.
add a form with a text box.
› Save the file as
form.html.
212
WORKING WITH FORMS 12
⁄ Open the file js- ‹ Add several ˇ Open the form2.html file ■ The property values of the
skeleton.html in Notepad. document.write statements in a browser. first form element are
to display the properties of displayed.
¤ Add a form with a text box the first form element.
to the Web page.
› Save the file as
form2.html.
213
JAVASCRIPT
VALIDATE FORMS
ne of the useful ways that JavaScript For example, you can validate a phone number
CGI scripts on the server can be used to This example uses the js-skeleton.html
validate form data, but using JavaScript to file found on the book’s CD-ROM, but you can
validate forms saves an extra trip or two to the apply these steps to any file.
server and ensures the type of data the server
will be receiving.
VALIDATE FORMS
⁄ Open the file js- › Add an onchange event Á Open the validate.html ■ A single text box along
skeleton.html in Notepad. to the text box and assign it file in a browser. with some text is displayed in
the function name. the browser.
¤ Add a form with a text box.
ˇ Save the file as
‹ Create a function within validate.html.
the <script> tags that
displays an alert dialog box if
the value of the text box is
unacceptable.
214
WORKING WITH FORMS 12
‡ Type an invalid value in ° Press the Enter key. ■ An alert dialog box appears
the text box. with a message for the user.
215
JAVASCRIPT
CHANGE FOCUS
⁄ Open the file js- › Set the onclick event to Á Open the focus.html file ° Type some text.
skeleton.html in Notepad. change the focus to one of in a browser.
the text boxes. ■ The text appears in the text
¤ Add a form with a several ‡ Click one of the buttons. box that has the focus.
text boxes and buttons. ˇ Save the file as
focus.html.
‹ Add the onclick event to
each button.
216
WORKING WITH FORMS 12
Radio buttons and check box buttons don’t The focus() method can be used to set the
include the blur() method because each focus to a specific form element. This can be
individual radio button or check box button useful to automatically set the focus to the first
belongs to a group and the browser cannot form element where the user needs to enter
determine when a single item loses the focus. information.
Radio buttons and check box buttons both
have the focus() method, though, and
pressing the Enter key when a radio button or
check box button has the focus selects or
deselects the item.
USING BLUR
⁄ Open the file focus.html ‹ Save the file as › Open the blur.html file Á Type some text.
in Notepad. blur.html. in a browser.
■ No text appears in any of
¤ Change the focus() ˇ Click one of the buttons. the text boxes because they
methods to blur(). have lost the focus.
217
JAVASCRIPT
DETECT FOCUS
⁄ Open the file js- › Set the onFocus event to Á Open the onFocus.html ‡ Click in one of the text
skeleton.html in Notepad. change the text in the text file in a browser. boxes.
box.
¤ Add a form with several ■ Some text is displayed in
text boxes. ˇ Save the file as the text box that has the
onFocus.html. focus.
‹ Add the onFocus event to
each text box.
218
WORKING WITH FORMS 12
DETECT BLUR
° Open the file ‚ Save the file as — Open the onBlur.html file ¡ Click in another text box.
onFocus.html in Notepad. onBlur.html. in a browser.
■ The text box that lost the
· Change the onfocus ± Click on one of the text focus displays a message.
events to onblur events and boxes.
change the displayed text.
219
JAVASCRIPT
⁄ Open the file ‹ Save the file as › Open the file js- Á Within the <script> tags,
skeleton.html in Notepad. frameset.html. skeleton.html in Notepad. add a document.write
statement to display the
¤ Replace the <body> tags ˇ Add a heading. frame’s name.
with a frameset page with
two frames. ‡ Save the file as left.html.
220
WORKING WITH FRAMES 13
If you create a frameset and cannot see the Because individual frames are simply one of
frames, then you need to make sure that the several windows that appear in the browser,
Web pages that you specify in the src frame objects can use all the properties and
attributes for each frame are available. You methods used by the document and
should also check to make sure that the window objects. For example, you can
<frameset> tags replace the <body> tags access document properties for a frame for
for the frameset file. If the <body> tags exist the first frame on the page using the
in the file, then the frames will not be statement
visible. parent.frame[0].document.title.
° Open the file js- ‚ Within the <script> tags, ± Open the frameset.html ■ Two frames appear with
skeleton.html in Notepad. add a document.write file in your browser. the frame name inside each.
statement to display the
· Add a heading. frame’s name. Note: The left frame displays the
file left.html, and the right
— Save the file as frame displays the file
right.html. right.html.
221
JAVASCRIPT
⁄ Open the file ‹ Save the file as › Open the file js- ‡ Within the <script> tags,
skeleton.html in Notepad. frameset2.html. skeleton.html in Notepad. add a document.write
statement to display the
¤ Replace the <body> tags ˇ Specify a background frame’s background color.
with a frameset page with color in the <body> tag.
two frames. ° Save the file as
Á Add a heading. left2.html.
222
WORKING WITH FRAMES 13
· Open the file js- ± Within the <script> tags, ™ Open the frameset2.html ■ Two frames appear with
skeleton.html in Notepad. add a document.write file in your browser. the frame’s background color
statement to display the in each.
‚ Specify a background frame’s background color.
color in the <body> tag. Note: The left frame displays the
¡ Save the file as file left2.html, and the right
— Add a heading. right2.html. frame displays the file
right2.html.
223
JAVASCRIPT
⁄ Open the file › Open the right2.html file ‡ Open the file ■ Two frames and the value
frameset2.html in Notepad. in Notepad. frameset3.html in your of the number of frames
browser. appear.
¤ Change right2.html to ˇ Change the
right3.html. document.write statement to
display the number of frames.
‹ Save the file as
frameset3.html. Á Save the file as
right3.html.
224
WORKING WITH FRAMES 13
⁄ Open the file › Open the left2.html file ‡ Open the frameset4.html ■ Two frames and the value
frameset2.html in Notepad. in Notepad. in your browser. of the background color
ˇ Change the appear.
¤ Change left2.html to
left4.html. document.write statement to
display the background color
‹ Save the file as using the self object.
frameset4.html.
Á Save the file as
left4.html.
225
JAVASCRIPT
⁄ Open the file ‹ Save the file as › Open the file js- Á Save the file as
skeleton.html in Notepad. crossref.html. skeleton.html in Notepad. topform.html.
¤ Replace the <body> tags ˇ Add a form with a text
with a frameset page with
two frames. box.
Note: In this example, the rows
attribute is used within the
<frameset> tag to place the
frames on top of one another.
226
WORKING WITH FRAMES 13
After you open a new window, you can name The only real difference between frames that are
it. You can then use this name to access the side by side and frames that are above one
properties and methods of the new window. another is the attribute that is included in the
For example, if you open a new window <frameset> tag. The first frame will always be
named window1, then you can get its title on top for the rows attribute and to the left for
using the window1.document.title the cols attribute.
statement. Frames, on the other hand, are
contained within framesets. Therefore, you
need to access frames using their parent
frameset, which is accomplished using a
statement like
parent.frame1.document.title.
‡ Open the file js- · Add the onclick event to — Open the crossref.html ± Add some text to the text
skeleton.html in Notepad. the button and assign it to file in your browser. box in the top frame.
retrieve the text from the top
° Add a form with a text box frame. ¡ Click the button in the
and a button. bottom frame.
‚ Save the file as
bottomform.html. ■ The text in the bottom text
box appears in the bottom
frame.
227
JAVASCRIPT
⁄ Open the file › Open the left2.html file ‡ Open the write.html file ■ Two frames appear, and
frameset2.html in Notepad. in Notepad. in your browser. the code for the left frame
displays text in the right
¤ Change left2.html to ˇ Change the frame.
writeframe.html. document.write statement to
reference the other frame.
‹ Save the file as
write.html. Á Save the file as
writeframe.html.
228
WORKING WITH FRAMES 13
⁄ Open the file ‹ Save the file as › Open the onresize.html ˇ Resize the frames by
frameset2.html in Notepad. onresize.html. file in your browser. dragging the bar that
separates them.
¤ Add the onResize event to
the first frame and assign it to ■ Text appears in the left
display some text in the left frame.
frame.
229
JAVASCRIPT
⁄ Open the file Á Add the target attribute · Open the target.html file ■ Two frames and the target
crossref.html in Notepad. to the form. in your browser. name appear.
¤ Change topform.html to ‡ Add a document.write
targetframe.html. statement to display the target Note: The target name identifies
‹ Save the file as target.html. value. where the linked Web page will
load.
› Open the topform.html ° Save the file as
file in Notepad. targetframe.html.
ˇ Move the form above the
<script> tags.
230
WORKING WITH FRAMES 13
PRINT A FRAME
nother useful method of the frame object is the
PRINT A FRAME
⁄ Open the file ˇ Change the button’s text. ° Open the file print.html · Click the button.
crossref.html in Notepad. in your browser.
¤ Change bottomform.html Á Add a statement to the ■ The Print dialog box opens.
to printframe.html. onclick event to print the
frame.
‹ Save the file as print.html.
› Open the ‡ Save the file as
bottomform.html file in printframe.html.
Notepad.
231
JAVASCRIPT
⁄ Open the file js- ‹ Save the file as › Open the file ■ All the properties of the
skeleton.html in Notepad. navigator.html. navigator.html in a navigator object are
browser. displayed.
¤ Add several
document.write statements Note: Internet Explorer version 5
to display the values of the will still return a version number
navigator object properties. of 4.0 because this is the version
number for the last major engine
release by Microsoft.
232
DETERMINING ENVIRONMENT PROPERTIES 14
Many different pieces make up the user’s Some navigator object properties are read-
environment, including the computer, the only properties, such as the language
operating system, the browser, and the Web property. If the language property were not
page. Each of these pieces can be controlled a read-only property, then you would be able
to an extent using JavaScript objects. The to change the scripting language at any time,
computer, operating system, and browser which would confuse the browser.
can all be detected using the navigator
object, and the Web page URL can be
detected using the location object. These
objects are covered in the sections “Using
the navigator Object” and “Using the
location Object.”
ˇ Open the file ‡ Save the file as ° Open navigator2.html in ■ The value of each
navigator.html in Notepad. navigator2.html. a browser. navigator object method is
displayed.
Á Replace the property
definition with the navigator
method.
233
JAVASCRIPT
⁄ Open the file js- ‹ Include an else if ˇ Open the file ■ The browser type is
skeleton.html from the CD- statement that, if Microsoft is appName.html in a browser. detected and displayed.
ROM in Notepad. not found, checks to see if
Netscape can be found.
¤ Add an if statement to Note: If the browser is neither a
check for the word Microsoft Microsoft nor a Netscape product,
within the then nothing will be displayed.
navigator.appName value.
› Save the file as
appName.html.
234
DETERMINING ENVIRONMENT PROPERTIES 14
⁄ Open the file js- ‹ Include an else statement ˇ Open appVersion.html in ■ The browser version is
skeleton.html in Notepad. that executes if the specified a browser. detected, and a message is
version number isn’t found displayed.
¤ Add an if statement to (including versions that have
check for a specific version a higher version number).
number.
› Save the file as
appVersion.html.
235
JAVASCRIPT
⁄ Open the file js- ‹ Include an else statement ˇ Open the file ■ The user’s operating
skeleton.html in Notepad. that executes if the specified platform.html in a browser. system platform is detected
platform isn’t found. and displayed.
¤ Add an if statement to
check for the platform to › Save the file as
determine the operating platform.html.
system.
236
DETERMINING ENVIRONMENT PROPERTIES 14
⁄ Open the file js- ‹ Include an else statement ˇ Open the file ■ The browser type and
skeleton.html in Notepad. that executes if the specified userAgent.html in a operating system are
properties aren’t found. browser. detected and displayed.
¤ Add an if statement to
check for specific › Save the file as
environment properties. userAgent.html.
237
JAVASCRIPT
⁄ Open the file js- ‹ Include an else statement ˇ Open the file ■ The script detects whether
skeleton.html in Notepad. that executes if Java isn’t javaEnabled.html in a Java is enabled on the
enabled. browser. browser and displays the
¤ Add an if statement to results.
check whether Java is › Save the file as
enabled. javaEnabled.html.
238
DETERMINING ENVIRONMENT PROPERTIES 14
⁄ Open the file js- ‹ Include an else statement ˇ Open appCodeName.html ■ The script detects and
skeleton.html in Notepad. that executes if the specified in a browser. displays the code name.
code name isn’t found.
¤ Add an if statement to
check the code name. › Save the file as
appCodeName.html.
239
JAVASCRIPT
⁄ Open the file js- ‹ Save the file as › Open the file ■ All the properties of the
skeleton.html in Notepad. location.html. location.html in a browser. location object are
displayed.
¤ Add several
document.write statements
to display the values of the
location object properties.
240
DETERMINING ENVIRONMENT PROPERTIES 14
prot = location.protocol; }
domain = location.hostname; This function splits the URL into its separate
components. Each separate component can be
prt = location.port; replaced as needed.
RELOAD A PAGE
⁄ Open the file js- ‹ Add the onclick event to ˇ Open the location2.html Á Click the button.
skeleton.html in Notepad. the button and set it equal to file in a browser.
the reload() method. ■ The page is reloaded.
¤ Add a form with a button.
› Save the file as
location2.html.
241
JAVASCRIPT
USING COOKIES
ookies are small pieces of data that help To write a cookie using JavaScript, you use the
USING COOKIES
⁄ Open the file js- › Also within the function, ˇ Create two variables to ‡ Add the onload event to
skeleton.html in Notepad. add a JavaScript statement locate the start and end the <body> tag and set it
that creates a prompt dialog positions of the cookie value. equal to the function name.
¤ Add a function within the box and sets the value to
<script> tags. document.cookie. Á Add a JavaScript statement ° Save the file as
to write the cookie value to cookie.html.
‹ Within the function the browser.
brackets, add an if statement
to check if a cookie exists.
242
DETERMINING ENVIRONMENT PROPERTIES 14
Browsers include settings for disabling Any string can be included within a cookie, but
cookies if you don’t want them stored on all cookies need to include a name and a value.
your computer. For Internet Explorer, you can The cookie file has a size limitation of 4KB. If
disable cookies by selecting the the string saved to a cookie is larger than this,
Tools➪Internet Options command. This then a portion of the cookie data will be lost.
command opens the Internet Options dialog
box. Select the Security tab and click the
Custom Level button. Then select the Disable
radio button under the Cookies heading
(❍ changes to ●).
· Open the file ‚ Type a name in the text ■ The name is displayed in
cookie.html in a browser. box. the browser.
■ A dialog box appears. — Click the OK button.
243
JAVASCRIPT
ENCODE CHARACTERS
hen some characters such as spaces The text is encoded by converting it to a
ENCODE TEXT
⁄ Open the file js- ‹ Add document.write() ˇ Open the file ■ A string and its escaped
skeleton.html in Notepad. statements to display the escape.html in a browser. equivalent are displayed.
initial value of the string and
¤ Assign a string to a the value of the string
variable. encoded.
› Save the file as
escape.html.
244
DETERMINING ENVIRONMENT PROPERTIES 14
If your Web page filename includes any The escape() and unescape() statements
spaces, then links to the Web page will not be can be used on single characters, full lines of
able to locate the Web page name. If you text, or even paragraphs.
encode the URL by using the escape()
statement, then you will be able to use the Because the type of encoding used by
name with spaces. escape() is based on the ASCII character set,
it cannot be used with Unicode characters.
The escape() and unescape() statements
are not a part of any object, but are JavaScript
keywords. They do not need any parent
object in order to work correctly.
DECODE TEXT
⁄ Open the file ‹ Add a document.write() ˇ Open the file ■ An encoded string and its
escape.html in Notepad. statement to display the value unescape.html in a browser. unescaped equivalent are
of the string decoded. displayed.
¤ Assign the escaped string
to a variable. › Save the file as
unescape.html.
245
JAVASCRIPT
⁄ Open the file js- ‹ Misspell the word ˇ Open the file error.html ■ The page loads, but the
skeleton.html in Notepad. document in one statement in a browser. status bar displays an error.
to cause a syntax error.
¤ Add a couple of Note: The error dialog box
document.write statements › Save the file as includes an Always Display This
within the <script> tags. error.html. Message When a Page Contains
Errors check box. If you checked
this at some earlier time, then the
error dialog box appears
automatically.
246
DEBUGGING JAVASCRIPT 15
In the error dialog box is a check box that The error dialog box has two buttons used to
you can check to cause the error dialog box cycle through the errors. Click the Previous
to appear automatically every time the button to see the previous error or the Next
browsers detects an error on the current button to the see the next error.
page.
If you view the details in the error dialog
box, it includes the line and character where
the syntax error appears. Using this
information, you can locate exactly where
the syntax error is.
Á Double-click the warning ‡ Click the Show Details ■ The details of the error are
icon in the status bar. button. (The button label then displayed.
changes to Hide Details.)
■ The JavaScript error dialog
box appears.
247
JAVASCRIPT
⁄ Open the file js- ‹ Misspell the word Á Open the file ■ The page loads, but the
skeleton.html in Notepad. document to cause a syntax comment.html in a browser. statement with an error has
error. been removed with a
¤ Add a couple of comment, so no error
document.write statements › Comment out the appears in the Status bar.
within the <script> tags. statement with an error.
ˇ Save the file as
comment.html.
248
DEBUGGING JAVASCRIPT 15
If only one bracket of a function statement is The copy and paste functions can be used to
included in a commented statement, the temporarily remove and replace lines of code,
script produces an error. The same problem but if you use Notepad to write scripts, the copy
happens if you include only one end of a set buffer remembers only a single line of code.
of quotes or parentheses in a commented Also, if you remove a large section of code, you
statement. run the risk of losing the code.
⁄ Open the file ‹ Comment out the ˇ Open the file ■ The page loads, but the
comment.html in Notepad. document.write statements comment2.html in a browser. statement with an error has
with multiple-line comment been removed with a
¤ Add another marks instead of the slashes. comment, so no error
document.write() statement. appears in the Status bar.
› Save the file as
comment2.html.
249
JAVASCRIPT
⁄ Open the file js- ‹ Within the <script> tag, ˇ Open the file Á Click the button.
skeleton.html in Notepad. add a variable and a function output.html in a browser.
to count the number of
¤ Add a form with a button clicks and display the ■ The page displays a
temporary text box and a number in the temporary text temporary text box and a
button. box. button.
■ The count variable is ‡ Continue to click the ■ For each click, the text box
displayed in the text box. button. is updated.
251
JAVASCRIPT
⁄ Open the file js- › Incorrectly include only a Á Open the file ■ The error dialog box
skeleton.html in Notepad. single equal sign in the if error2.html in a browser. appears.
statement.
¤ Add a document.write
statement. ˇ Save the file as
error2.html.
‹ Add an if statement to
check and display the
browser type.
252
DEBUGGING JAVASCRIPT 15
Certain text editors such as Allaire HomeSite and locate its partner. These editors also check
and Macromedia Dreamweaver can check for the spelling of keywords to prevent spelling
some common errors such as misplaced errors. Good scripting habits like aligning your
brackets. These editors keep track of every brackets and indenting code help to make your
quote and bracket that you type, and when an code easier to debug and follow.
ending bracket or quote is missing, the text
appears red until it is entered. You can also
select a single bracket or quote, press a key,
‡ Open the error2.html file · Incorrectly add a single — Open error3.html in a ■ The error dialog box
in Notepad. bracket at the end of the if browser. appears.
statement.
° Fix the if statement by
adding another equal sign. ‚ Save the file as
error3.html.
253
JAVASCRIPT
This reference is based on the HTML 4.01 include the deprecated (or discontinued)
specification published online at elements. It also does not include frame
www.w3c.org. This reference does not definitions.
COMMON ATTRIBUTES
These common attributes are used across many different elements as indicated. They are divided into three
groupings — core, language, and events.
Attribute Description Acceptable Values
Core Attributes
id Element ID.
class Defines a style sheet class.
style Defines inline style sheets.
title Provides a title to the element.
Language Attributes
lang Indicates primary language.
dir Defines text direction. ltr and rtl
Event Attributes
onclick Element was clicked.
ondblclick Element was double clicked.
onmousedown Mouse button was pressed.
onmouseup Mouse button was released.
onmouseover Cursor was moved over an element.
onmousemove Cursor was moved.
onmouseout Cursor was moved off an element.
onkeypress Keyboard key was pressed.
onkeydown Keyboard key was pressed down.
onkeyup Keyboard key was released.
254
HTML 4.01 REFERENCE A
DOCUMENT STRUCTURE ELEMENTS
These elements compose the major sections of a Web page, including the root <html> tags, the head,
and the body.
Attribute Description
<HTML> . . . </HTML> (supports common language attributes)
version Specifies a DTD.
<HEAD> . . . </HEAD> (supports common language attributes)
profile Locates separate meta data file.
<BODY> . . . </BODY> (supports common core, language, and event attributes)
onload Document was loaded.
onunload Document was unloaded.
HEAD ELEMENTS
The following tags can be included within the head section of a Web page. These tags can appear multiple
times within the head section.
Attribute Description Acceptable Values
<TITLE> . . . </TITLE> (supports common language attributes)
<BASE/>
href Location of base.
<META/> (supports common language attributes)
http-equiv Response header.
name Meta information name.
content Information for name.
scheme Meta data interpretation scheme.
<LINK/> (supports common core, language, and event attributes)
charset The browser’s character set.
href Location of the link.
hreflang Language of the link.
type Content type of the link.
rel Forward link type.
rev Reverse link type.
media Specifies media type.
255
JAVASCRIPT
256
HTML 4.01 REFERENCE A
BLOCK ELEMENTS PHRASE ELEMENTS
These elements support common core, language, These elements mark text as emphasis, strong,
and event attributes. definition, code, sample, keyboard, variable, cite,
Tag abbreviation, and acronym styles. These elements
<P> . . . </P> support common core, language, and event
<DIV> . . . </DIV> attributes.
<ADDRESS> . . . </ADDRESS> Tag
<EM> . . . </EM>
257
JAVASCRIPT
These elements format text as teletype, These elements mark text as subscripts or
italics, bold, big, or small. These elements superscripts. These elements support common core,
support common core, language, and event language, and event attributes.
attributes.
Tag
Tag <SUB> . . . </SUB>
<TT> . . . </TT> <SUP> . . . </SUP>
<I> . . . </I>
INLINE ELEMENT
<B> . . . </B> This element supports common core, language,
<BIG> . . . </BIG> and event attributes.
LIST ELEMENTS
These elements are used to create lists including definition, ordered, and unordered lists.
Attribute Description Acceptable Values
<DL> . . . </DL>
<(DT)> . . . </DT>
<(DD)> . . . </DD> (supports common core, language, and event attributes)
<OL> . . . </OL> (supports common core, language, and event attributes)
type Sets the numbering style. 1, a, A, i, and I
start Sets the list start value.
<UL> . . . </UL> (supports common core, language, and event attributes)
type Sets the bullet style. disc, square, and circle
<LI> . . . </LI> (supports common core, language, and event attributes)
type Sets the numbering or bullet style. 1, a, A, i, I, disc, square, and
circle
value Sets the current list value.
258
HTML 4.01 REFERENCE A
This element supports common core attributes. This element supports common
core, language, and event
Tag
attributes.
<BR/>
Tag
<HR/>
THE ANCHOR ELEMENT
IMAGE ELEMENT
259
JAVASCRIPT
FORM ELEMENTS
260
HTML 4.01 REFERENCE A
261
JAVASCRIPT
TABLE ELEMENTS
Attribute Description Acceptable Values
<TABLE> . . . </TABLE> (supports common core, language, and event attributes)
summary Brief table summary.
width Table width.
border Defines border width.
frame Defines render frame.
rules Places rules between rows and columns.
cellspacing Spacing between cells.
262
HTML 4.01 REFERENCE A
263
JAVASCRIPT
264
WHAT'S ON THE CD-ROM B
CoffeeCup HTML Editor, from CoffeeCup Software GIF Animator, from Ulead Systems
For Windows 95/98 and NT 4 or later. Shareware. The For Windows 95/98 and NT 4 or later. Trial version. GIF
CoffeeCup tools are a suite of tools that let you work Animator is a package that can be used to create
with all aspects of HTML, Web images, and Java. These animated GIF images. This demo allows you to use the
tools are shareware and need to be registered after a full version for an evaluation period.
given amount of time.
GraphicConverter, from Lemke Software
CSE HTML Validator Lite, from Windows-Al Internet For Macintosh. Shareware. GraphicConverter is a
Solutions graphic conversion program that can be used to convert
For Windows 95/98 and NT 4 or later. Lite version. CSE images between different formats.
HTML Validator Lite doesn’t include all the features of
the professional version, but it will not expire. HomeSite, from Allaire Corporation
For Windows 95/98 and NT 4 or later. 30-day evaluation
CSE HTML Validator Professional, from Windows-Al version. HomeSite is a Visual HTML editor. It can be
Internet Solutions used to create Web pages. The evaluation version will
For Windows 95/98 and NT 4 or later. Demo version. expire after 30 days.
CSE HTML Validator Professional can be used to
validate your Web pages. This demo allows you to use HotDog Express, from Sausage Software
the full version for an evaluation period. For Windows 95/98 and NT 4 or later. Demo version.
HotDog Express is the easier-to-use version of Sausage
CuteFTP, from GlobalSCAPE Software’s Web page creation program (see “HotDog
For Windows 95/98 and NT 4 or later. Shareware. Professional”).
CuteFTP is an FTP client that can be used to transfer
files to a Web server. HotDog Professional, from Sausage Software
For Windows 95/98 and NT 4 or later. Trial version.
CuteMAP, from GlobalSCAPE HotDog Professional is Sausage Software’s professional-
For Windows 95/98 and NT 4 or later. Shareware. level Web page creation program.
CuteMAP is an image map editor. It can be used to
create and save image maps. HTML Pro, from Niklas Frykholm
For Windows 95/98 and NT 4 or later. Shareware. HTML
Dot Planet ISP, from DotPlanet.com Pro is a Web page editing package that can be used to
For Windows 95/98/NT. Evaluation version. In case you create Web pages.
don’t have a connection to the information
superhighway, the CD includes sign-on software for Internet Explorer, from Microsoft
DotPlanet Internet Access, an Internet service provider. For Windows 95/98 and NT 4 or later and Macintosh.
Commercial version. Internet Explorer is a robust
During the sign-up process, you will need to enter the browser that can be used to display Web pages.
registration number: 5 0 2 C Y.
Mapedit, from Boutell Communications
After you are signed on, you can access the world wide For Windows 95/98 and NT 4 or later. Shareware.
Web from DotPlanet’s home page. You need a credit Mapedit is an image map editor. It can be used to create
card to sign up with DotPlanet Internet Access. and save image maps.
Dreamweaver, from Macromedia Netscape Communicator, from Netscape
For Windows 95/98 and NT 4.0 or later. Trial Version. For Windows 95/98 and NT 4 or later and Macintosh.
Dreamweaver is a robust Web page creation tool. It Commercial version. Netscape Communicator is a
allows you to dynamically edit HTML and JavaScript popular Web browser that can be used to display Web
pages. This demo allows you to use the full version for pages.
an evaluation period.
265
JAVASCRIPT
Paint Shop Pro, from JASC Stuffit Expander, from Aladdin Systems
For Windows 95/98 and NT 4 or later. Shareware. Paint For Macintosh. Commercial version. Stuffit Expander
Shop Pro is a powerful image editing package. This can create expandable archive files that can be
demo allows you to use the full version for an expanded as needed.
evaluation period. Paint Shop Pro includes many tools
for creating, editing, and working with Web images. Stuffit Lite, from Aladdin Systems
For Windows 95/98 and NT 4 or later and Macintosh.
PowWow, from Tribal Voice Software Freeware. Stuffit Lite can be used to compress and
For Windows 95/98 and NT 4 or later. Freeware. archive files. The lite version is freeware and will not
PowWow Professional is an instant messaging expire.
communication package that includes voice chat
capabilities. Web Razor Pro, from Ulead Systems
For Windows 95/98 and NT 4.0 or later. Evaluation
RealPlayer, from RealNetworks, Inc. Copy. Web Razor Pro is a Web image-editing package
For Windows 95/98 and NT 4 or later and Macintosh. that includes features for creating GIF animations and
Commercial version. RealPlayer is a browser plug-in optimizing Web images. This demo allows you to use
that can be used to view audio and video files. the full version for an evaluation period.
Reptile, from Sausage Software WinZip, from Nico Mak Computing
For Windows 95/98 and NT 4 or later. Demo version. For Windows 95/98 and NT 4 or later. Evaluation
Reptile is a seamless tile creation package. version. WinZip is a file compression and archiving
package.
Shockwave and Flash Players, from Macromedia, Inc.
For Windows 95/98 and NT 4 or later and Macintosh. TROUBLESHOOTING
Commercial version. The Shockwave and Flash Players I tried my best to compile programs that work on
are plug-ins that can be used to display Flash and most computers with the minimum system
Shockwave content within a browser. requirements. Your computer, however, may differ,
SiteCheck, from Pacific Coast Software
and some programs may not work properly for some
For Windows 95/98 and NT 4 or later. Shareware. reason.
SiteCheck is a set of utilities that can be used to check The two most likely problems are that you don’t have
the links on your site’s Web pages. enough memory (RAM) for the programs you want to
SmartSaver Pro, from Ulead Systems use, or you have other programs running that are
For Windows 95/98 and NT 4 or later. 15-day trial affecting installation or running of a program. If you
version. SmartSaver Pro is a Web image-optimization get error messages like Not enough memory or
package that allows you to visually select the file Setup cannot continue, try one or more of
settings for creating optimized images. This demo these methods and then try using the software again:
allows you to use the full version for an evaluation • Turn off any anti-virus software.
period.
• Close all running programs.
Spider, from InContext Systems
For Windows 95/98 and NT 4 or later. Evaluation
version. Spider is a Web-authoring package for
creating Web pages.
266
WHAT'S ON THE CD-ROM B
267
JAVASCRIPT
FLIP THROUGH PAGES First page ZOOM IN ¤ Click the area of the
⁄ Click one of these ⁄ Click to magnify page you want to magnify.
Previous page
options to flip through an area of the page. ■ Click one of these
the pages of a section. Next page
options to display the page
Last page at 100% magnification ( )
or to fit the entire page
inside the window ( ).
268
USING THE E-VERSION OF THE BOOK B
B
To install Acrobat Reader, insert the CD- Acrobat Reader is a popular and useful
ROM disc into a drive. In the screen that program. There are many files available on the
appears, click Software. Click Acrobat Web that are designed to be viewed using
Reader and then click Install at the bottom Acrobat Reader. Look for files with the .pdf
of the screen. Then follow the instructions extension. For more information about Acrobat
on your screen to install the program. Reader, visit the Web site at www.adobe.com/
products/acrobat/readermain.html.
You can make searching the book more
convenient by copying the .pdf files to
your own computer. Display the contents
of the CD-ROM disc and then copy the
PDFs folder from the CD to your hard
drive. This allows you to easily access the
FIND TEXT ¤ Type the text you ■ The first instance of ■ Repeat Steps 1
⁄ Click to search want to find. the text is highlighted. and 3 to find the next
for text in the section. instance of the text.
‹ Click Find to start
■ The Find dialog box the search.
appears.
269
INDEX
270
JAVASCRIPT:
Your visual blueprint for
building dynamic Web pages
271
INDEX
date values, getting, 168–169 multiple-line comments, 249
Date.parse ( ) method, 172 runtime errors, 246
getDate ( ) method, 168–169 single-line comments, 248
getHours ( ) method, 168–169 syntax errors, 246
getMonth ( ) method, 168–169 text boxes, output value of variables to, 250–251
getTime ( ) method, 172 decimal integer variables, 18
getTimezoneOffset ( ) method, 174–175 declaring functions, 64
getYear ( ) method, 168–169 decrement operator, 38–39
Greenwich mean time, 166, 174 disabling form elements, 210–211
local date, displaying, 166–167 document object, 92–93
local time, displaying, 166–167 document title, changing, 124
overview, 164–165 modification date, displaying, 125
set date values, 170 overview, 116–117
set time values, 171 referring page, viewing, 127
setDate( ) method, 170 URL, viewing current, 126
setHours( ) method, 170 Document Object Model. See DOM
setMinutes( ) method, 170 document structure, 255
setMonth( ) method, 170 document.writeIn( ) method, 117
setSeconds( ) method, 170 DOM (Document Object Model), 92–93
setTime( ) method, 172 Dot Planet ISP, 265
setTimeout( ) method, 169 double-clicks, detecting, 78–79
setYear( ) method, 170 Dreamweaver, 253, 265
time values, getting, 168–169
time zones, 174–175 E
Universal Time Coordinated, 174 encoding characters, 244–245
date values, getting, 168–169 error dialog box, 247
Date.parse( ) method, 172 escape( ) statement, 244–245
debugging escape characters, 149
alert boxes, 251 Euler’s constant, 184
Allaire HomeSite, 253 eval( ) function, 47
comments, 248–249 events
common errors, 252–253 double-clicks, detecting, 78–79
detecting JavaScript errors, 246–247 focus, setting, 84–85
error dialog box, 247 key press, detecting, 82–83
Macromedia Dreamweaver, 253
272
JAVASCRIPT:
Your visual blueprint for
building dynamic Web pages
273
INDEX
forms radio button object properties, displaying, 202
blur, using, 217 radio button selection, responding to, 203
blur( ) method, 216–217 radio buttons, 202–203
button object, 196 reset button, 198
button object properties, displaying, 196 reset object, 198
buttons, using, 196–197 resetting, 212–213
check box buttons, 200–201 select object, 204–205
check box object properties, displaying, 200 selectedIndex property, 205, 208
checkbox object, 200 selection lists, 204–207
click event, reacting to, 197 selection object properties, displaying, 204
detecting blur, 219 submit button, 199
detecting focus, 218 submit object, 199
disabling form elements, 210–211 submitting, 212–213
focus, changing, 216 text box object methods, using, 191
focus, controlling, 216–217 text box object properties, displaying, 190
focus( ) method, 216–217 text boxes, 190–191
focus events, using, 218–219 textarea box object methods, using, 195
form element properties, displaying, 213 textarea box properties, displaying, 194
form elements, disabling, 210–211 textarea boxes, 194–195
form object properties, displaying, 212 validating, 214–215
hidden fields, 193 frame object
hidden object, 193 acessing frames by name, 222–223
list item text, changing, 207 child frame object, 223
list selection, responding to, 205 current frame, referencing, 225
mathematical operations, 215 frame resizing, detecting, 229
multiple check boxes, 201 frames property, 220
multiple selection lists, 208–209 length property, 224
onBlur events, 218–219 nested framesets, 226
onFocus events, 218–219 number of frames, finding, 224
option object, 206–207 overview, 220–221
option object properties, displaying, 206 parent frame, 222–223
password box object, 192 print( ) method, 231
password boxes, 192 printing frames, 231
radio button object, 202–203 referencing across frames, 226–227
274
JAVASCRIPT:
Your visual blueprint for
building dynamic Web pages
275
INDEX
HTML document, JavaScript embedded within, 6–7 noscript tags, 10–11
HTML link, calling functions from, 72–73 overview, 2–3
HTML Pro, 265 personalizing Web pages with, 7
Hypertext Markup Language. See HTML script tags, 6–9
statements, 4–5
I JavaScript timers, 58–59
identifying numbers, 48–49
if loops, 51 K
if-else statements, 50–51 key press, detecting, 82–83
image element, 259 keyboard events, 75
image object, 106–109
increment operator, 38–39 L
indexOf( ) method, 158–159 length property, 154, 224
infinite loops, 57 line break element, 259
inline element, 258 link( ) method, 152–153
inserted/deleted text elements, 257 link color, changing, 122–123
integer variables, 15, 18 link object, 110–113
Internet Explorer, 265 links, changing, 112–113
intervals list elements, 258
clearing, 62–63 list item text, changing, 207
setting regularly timed, 60–61 list selection, responding to, 205
isNaN( ) method, 49 local date, displaying, 166–167
local time, displaying, 166–167
J local variables, 66–67
Java, determining if enabled, 238 location object, 240–241
javaEnabled( ) method, 238 location object properties, displaying, 240
JavaScript log ( ) method, 184
browser configuration, JavaScript disabled in, 10–11 logarithmic methods, 184
case-sensitivity, 9 logical expressions, creating, 42–43
comments, adding, 12–13 logical operators, 42–43
explanatory headers, 13
external JavaScript file, linking to, 8–9 M
head tags, 9 Mapedit, 265
HTML document, embedded within, 6–7 Math object, 59
abs( ) method, 189
absolute values, 189
276
JAVASCRIPT:
Your visual blueprint for
building dynamic Web pages
277
INDEX
Java, determining if enabled, 238 image object, 106–109
javaEnabled( ) method, 238 link object, 110–113
location object, 240–241 Math object, using, 97
location object properties, displaying, 240 methods, 90–91
operating system, detecting user’s, 236 new objects, creating, 98–99
overview, 232–233 overview, 90–91
platform property, 236 predefined objects, 96–97
reloading pages, 241 preloading images, 107
unescape( ) statement, 244–245 properties. See object properties
user agent, understanding, 237 radio button, checking, 95
userAgent property, 237 string object, using, 96
negative integer variables, 18 subobjects, 94–95
nested framesets, 226 text field, changing, 94
Netscape Communicator, 265 this keyword, 100–101
Netscape Navigator, JavaScript support disabled in, 11 Web page element objects, 92–93
noscript tags, 10–11 window. See window object
not operator, 43 onabort event, 89
onBlur events, 84–85, 218–219
O onchange event, 86–87
object methods, 90–91 onclick event, 76–77
object properties ondblclick event, 78–79
complete property, 109 onerror event, 89
described, 90–91 onFocus events, 84–85, 218–219
identifying, 100 onkeydown event, 83
for loop, 102 onkeypress event, 82–83
viewing, 102–103 onkeyup event, 83
objects onload event, 88–89
anchor object, 110–111 onmouseout events, 80–81
Array object, 104–105 onmouseover events, 80–81
changing images, 108–109 onunload event, 88–89
creating, 98–99 operating system, detecting user’s, 236
current object, referring to, 100–101 operator precedence, 46
current Web page element, referring to, 101 option object, 206–207
document object, 92–93 option object properties, displaying, 206
DOM (Document Object Model), 92–93 or operator, 43
history object, 92–93, 114–115
278
JAVASCRIPT:
Your visual blueprint for
building dynamic Web pages
279
INDEX
search( ) method, 156–157 string object
searches within a string, 156–157 addition assignment operator, 149
select object, 204–205 anchor( ) method, 152–153
selectedIndex property, 205, 208 array, separating items into, 162–163
selection events, 75 case, changing, 155
selection lists, 204–205, 206–207 concat( ) method, 148–149
selection object properties, displaying, 204 concatenating strings, 148–149
self object, 225 escape characters, 149
separate frames, writing to, 228 formatting string variables, 150–151
set date values, 170 formatting text, 144
set time values, 171 indexOf( ) method, 158–159
setDate( ) method, 170 length property, 154
setHours( ) method, 170 link( ) method, 152–153
setInterval( ) method, 60–61 locating characters in a string, 158–159
setMinutes( ) method, 170 overview, 144–145
setMonth( ) method, 170 replace( ) method, 160–161
setSeconds( ) method, 170 search( ) method, 156–157
setTime( ) method, 172 searches within a string, 156–157
setTimeout( ) method, 60, 169 split( ) method, 162–163
setYear( ) method, 170 splitting a string, 162–163
Shockwave, 266 string length, determining, 154
single parameters, passing, 68 sub( ) method, 150–151
single-line comments, 248 substring( ) method, 146–147
SiteCheck, 266 substrings, 146–147
SmartSaver Pro, 266 sup( ) method, 150–151
Spider, 266 text case, changing, 145
split( ) method, 162–163 text in a string, replacing, 160–161
splitting a string, 162–163 toLowerCase( ) method, 155
sqrt( ) method, 185 toUpperCase( ) method, 155
square root method, 185 using, 96
string expressions, evaluating, 47 string variables, 15, 21
string length, determining, 154
280
JAVASCRIPT:
Your visual blueprint for
building dynamic Web pages
281
INDEX
converting strings to numbers, 24–25 confirm dialog box, enabling user decisions with, 142–143
decimal integer variables, 18 document.writeIn( ) method, 117
declaring, 16 foreground color, setting, 122
floating-point variables, 15, 19 link color, changing, 122–123
hexadecimal integer variables, 18 moving windows, 134–135
integer variables, 15, 18 new browser window, opening, 128–129
negative integer variables, 18 overview, 116–117
overview, 14–15 printing windows, 132–133
parseFloat( ), 24–25 prompt( ) method, 140–141
parseInt( ), 24–25 prompt dialog box, accepting input with, 140–141
scientific notation used to express, 19 remote window, closing, 130–131
string variables, 15, 21 resizing windows, 136–137
strings, assigning, 17 text color, changing, 122–123
tostring( ) method, 26–27 variables, adding, 117
typeof keyword, 22–23 window.blur( ) method, 131
types, determining, 22–23 window.close( ) function, 130
types of, 14–15 window.focus( ) method, 131
values, assigning, 17 window.moveBy( ) method, 134–135
VBScript, 3 window.moveTo( ) method, 134–135
window.open( ) method, 128
W-Z window.resizeBy( ) method, 136–137
Web page element objects, 92–93 window.resizeTo( ) method, 136–137
Web pages window.blur( ) method, 131
loading messages, 88–89 window.close( ) function, 130
personalizing with JavaScript, 7 window.focus( ) method, 131
Web Razor Pro, 266 window.moveBy( ) method, 134–135
while loops, 54–55 window.moveTo( ) method, 134–135
window object, 92–93 window.open( ) method, 128
alert( ) method, 138–139 window.resizeBy( ) method, 136–137
alert dialog box, informing user with, 138–139 window.resizeTo( ) method, 136–137
browser status bar, displaying text on, 118–119 WinZip, 266
changing background color, 120–121
confirm( ) method, 142–143
282
JAVASCRIPT:
Your visual blueprint for
building dynamic Web pages
283
IDG BOOKS WORLDWIDE, INC. Software to a single hard disk, provided that you keep
END-USER LICENSE AGREEMENT the original for backup or archival purposes. You may
not (i) rent or lease the Software, (ii) copy or
READ THIS. You should carefully read these terms
reproduce the Software through a LAN or other
and conditions before opening the software packet(s)
network system or through any computer subscriber
included with this book (“Book”). This is a license
system or bulletin-board system, or (iii) modify,
agreement (“Agreement”) between you and IDG
adapt or create derivative works based on the
Books Worldwide, Inc. (“IDGB”). By opening the
Software.
accompanying software packet(s), you acknowledge
that you have read and accept the following terms
and conditions. If you do not agree and do not want (b) You may not reverse engineer, decompile, or
to be bound by such terms and conditions, promptly disassemble the Software. You may transfer the
return the Book and the unopened software packet(s) Software and user documentation on a permanent
to the place you obtained them for a full refund. basis, provided that the transferee agrees to accept
the terms and conditions of this Agreement and you
retain no copies. If the Software is an update or has
1. License Grant. IDGB grants to you (either an
been updated, any transfer must include the most
individual or entity) a nonexclusive license to use one
recent update and all prior versions.
copy of the enclosed software program(s) (collectively,
the “Software”) solely for your own personal or
business purposes on a single computer (whether 4. Restrictions on Use of Individual Programs.
a standard computer or a workstation component You must follow the individual requirements and
of a multi-user network). The Software is in use on a restrictions detailed for each individual program in
computer when it is loaded into temporary memory the “What's On The CD-ROM Disc” section of this
(i.e., RAM) or installed into permanent memory (e.g., Book. These limitations are contained in the individual
hard disk, CD-ROM or other storage device). IDGB license agreements recorded on the CD-ROM. These
reserves all rights not expressly granted herein. restrictions may include a requirement that after using
the program for the period of time specified in its text,
the user must pay a registration fee or discontinue
2. Ownership. IDGB is the owner of all right, title and
use. By opening the Software packet(s), you will be
interest, including copyright, in and to the compilation
agreeing to abide by the licenses and restrictions
of the Software recorded on the CD-ROM. Copyright
for these individual programs. None of the material
to the individual programs on the CD-ROM is owned
on this disc(s) or listed in this Book may ever be
by the author or other authorized copyright owner of
distributed, in original or modified form, for
each program. Ownership of the Software and all
commercial purposes.
proprietary rights relating thereto remain with IDGB
and its licensors.
5. Limited Warranty.
3. Restrictions On Use and Transfer.
(a) IDGB warrants that the Software and CD-ROM
are free from defects in materials and workmanship
(a) You may only (i) make one copy of the Software
under normal use for a period of sixty (60) days from
for backup or archival purposes, or (ii) transfer the
the date of purchase of this Book. If IDGB receives
284
notification within the warranty period of defects in (b) In no event shall IDGB or the author be liable
materials or workmanship, IDGB will replace the for any damages whatsoever (including without
defective CD-ROM. limitation damages for loss of business profits,
business interruption, loss of business information,
(b) IDGB AND THE AUTHOR OF THE BOOK or any other pecuniary loss) arising out of the use
DISCLAIM ALL OTHER WARRANTIES, EXPRESS OR of or inability to use the Book or the Software,
IMPLIED, INCLUDING WITHOUT LIMITATION even if IDGB has been advised of the possibility
IMPLIED WARRANTIES OF MERCHANTABILITY of such damages.
AND FITNESS FOR A PARTICULAR PURPOSE, WITH
RESPECT TO THE SOFTWARE, THE PROGRAMS, (c) Because some jurisdictions do not allow the
THE SOURCE CODE CONTAINED THEREIN, AND/ exclusion or limitation of liability for consequential
OR THE TECHNIQUES DESCRIBED IN THIS BOOK. or incidental damages, the above limitation or
IDGB DOES NOT WARRANT THAT THE FUNCTIONS exclusion may not apply to you.
CONTAINED IN THE SOFTWARE WILL MEET YOUR
REQUIREMENTS OR THAT THE OPERATION OF 7. U.S. Government Restricted Rights. Use,
THE SOFTWARE WILL BE ERROR FREE. duplication, or disclosure of the Software by the
U.S. Government is subject to restrictions stated
(c) This limited warranty gives you specific legal in paragraph (c) (1) (ii) of the Rights in Technical
rights, and you may have other rights which vary Data and Computer Software clause of DFARS
from jurisdiction to jurisdiction. 252.227-7013, and in subparagraphs (a) through (d)
of the Commercial Computer—Restricted Rights
6. Remedies. clause at FAR 52.227-19, and in similar clauses in
the NASA FAR supplement, when applicable.
(a) IDGB’s entire liability and your exclusive remedy for
defects in materials and workmanship shall be limited 8. General. This Agreement constitutes the entire
to replacement of the Software, which may be returned understanding of the parties, and revokes and
to IDGB with a copy of your receipt at the following supersedes all prior agreements, oral or written,
address: Disc Fulfillment Department, Attn: JavaScript: between them and may not be modified or amended
Your visual blueprint for Building Dynamic Web pages, except in a writing signed by both parties hereto
IDG Books Worldwide, Inc., 10475 Crosspoint which specifically refers to this Agreement. This
Boulevard, Indianapolis, Indiana, 46256, or call Agreement shall take precedence over any other
1-800-762-2974. Please allow 3-4 weeks for delivery. documents that may be in conflict herewith. If any
This Limited Warranty is void if failure of the Software one or more provisions contained in this Agreement
has resulted from accident, abuse, or misapplication. are held by any court or tribunal to be invalid, illegal
Any replacement Software will be warranted for the or otherwise unenforceable, each and every other
remainder of the original warranty period or thirty provision shall remain in full force and effect.
(30) days, whichever is longer.
285