Professional Documents
Culture Documents
murachs
JavaScript
and
DOM Scripting
(Chapter 2)
Thanks for downloading this chapter from Murachs JavaScript and DOM Scripting. We hope it will show you how easy it is to learn from any Murach book, with its paired-pages presentation, its how-to headings, its practical coding examples, and its clear, concise style. To view the full table of contents for this book, you can go to our website. From there, you can read more about this book, you can find out about any additional downloads that are available, and you can review our other books on web development. Thanks for your interest in our books!
iii
Contents
Introduction Section 1 Introduction to JavaScript programming Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Introduction to web development and JavaScript How to code a JavaScript application How to test and debug a JavaScript application A crash course in XHTML A crash course in CSS 3 43 89 121 169 xiv
Section 2 JavaScript essentials Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 How to get input and display output How to work with numbers, strings, and dates How to code control statements How to create and use arrays How to create and use functions How to create and use objects How to use regular expressions, handle exceptions, and validate data 223 249 275 301 327 355 385
Section 3 DOM scripting Chapter 13 Chapter 14 Chapter 15 Chapter 16 Chapter 17 Chapter 18 Basic DOM scripting Advanced event handling Advanced DOM manipulation How to script CSS How to script tables and forms Animation with DOM scripting 421 469 523 555 591 633
Section 4 Other JavaScript skills Chapter 19 Chapter 20 How to control the web browser How to use JavaScript libraries 663 701
Reference Aids Appendix A Index How to set up your computer for this book 745 753
Chapter 2
43
2
How to code a JavaScript application
In this chapter, youll learn how to code simple JavaScript applications like the Sales Tax application in the last chapter. That will get you off to a fast start and give you the perspective you need for learning rapidly in subsequent chapters. If you havent done much programming, this chapter will move quickly for you. But if you take it slow and do the exercises, you should master all of the skills. When youre finished, youll be able to write significant JavaScript applications of your own.
How to edit and test your web pages ................................ 44
How to edit a web page with Notepad++ ..................................................... 44 How to test a web page ................................................................................. 46 How to display error messages in Firefox .................................................... 48
Perspective .......................................................................... 84
44
Section 1
Chapter 2
45
Figure 2-1
46
Section 1
Chapter 2
47
How to retest a web page after you change the source code
To reload the edited file for the page, click the Reload or Refresh button. Then, run the application. Sometimes, clicking the Reload or Refresh button wont clear the browser memory completely so your changes wont work correctly. In that case, you may need to close the browser window and reopen the application.
Description
This chapter shows how to write JavaScript applications, and the next chapter shows you how to test and debug them.
Figure 2-2
48
Section 1
Chapter 2
49
The source code thats displayed when you click on the link
Description
The Error Console in Firefox is used to display errors, warnings, and messages generated by web pages. That includes messages caused by errors in JavaScript code. The buttons at the top of the Error Console let you display all errors, just fatal errors, just warnings, or just messages. The Clear button removes all errors from the console. If you click the link to the file in the Error Console, Firefox will display the code and highlight the line at which the error occurred. You will not, however, be able to edit the file.
Figure 2-3
50
Section 1
Chapter 2
51
Description
A required attribute that identifies the scripting language. For JavaScript, use type=text/javascript. Specifies the location of an external file. This file will run as if it were typed into the script tag at this point in the web document. Specifies the character encoding of the script. If omitted, the character encoding of the script will be the same as the character encoding of the document. Specifies that the script doesnt generate any document content. Then, the web browser processes the script after the rest of the page has been loaded. Coded as defer=defer.
Description
You can have multiple <script> tags in a web page. They are executed in the order that they appear in the document, unless the defer attribute has been used. In the body of a document, the <script> tag is replaced by the output of the code. The <noscript> tag is used to display content when JavaScript is disabled or not available. The XHTML document must be valid before and after all scripts have been executed.
How to include JavaScript with the script tag
Figure 2-4
52
Section 1
Chapter 2
53
A single-line comment
nextYear = thisYear + 1; // Determine what the next year is
A multi-line comment
/* The following line determines what the next year is by adding 1 to the current year */ nextYear = thisYear + 1;
Description
JavaScript has a syntax thats similar to the syntax of Java. JavaScript provides two forms of comments, which are ignored when the JavaScript is executed. In some cases, JavaScript will try to correct a missing semicolon by adding one at the end of a split line. This can cause errors. To prevent this, put a semicolon at the end of each statement, and follow the guidelines above for splitting a statement.
Figure 2-5
54
Section 1
Chapter 2
55
Description
Identifiers are the names given to variables, functions, objects, properties, and methods.
Figure 2-6
56
Section 1
Chapter 2
57
How the \n escape sequence can be used to start a new line in a string
"A valid variable name\ncannot start with a number." // represents the string: A valid variable name // cannot start with a number.
Description
JavaScript provides for just three primitive data types. These data types are used for storing numbers, strings, and Boolean values.
The primitive data types of JavaScript
Figure 2-7
58
Section 1
Chapter 2
59
Description
Addition Subtraction Multiplication Division Modulus Increment Decrement
Example
5 + 7 5 - 12 6 * 7 13 / 4 13 % 4 counter++ counter--
Result
12 -7 42 3.25 1 adds 1 to counter subtracts 1 from counter
Operators
++ -* + / %
Direction
Left to right Left to right Left to right Left to right
Description
Increment operator Decrement operator Multiplication, division, modulus Addition, subtraction
Description
Concatenation
Example
"Ray " + "Harris" "Months: " + 120
Result
"Ray Harris" "Months: 120"
Description
To code an arithmetic expression, you can use the arithmetic operators to operate on two or more values. An arithmetic expression is evaluated based on the order of precedence of the operators. To override the order of precedence, you can use parentheses. To concatenate two or more strings, you can use the + operator. Since the plus sign can be used for both numeric and string expressions, JavaScript looks at the data types to determine which operation to perform. If both values are numbers, JavaScript adds. If both values are strings, JavaScript concatenates. If one value is a number and one is a string, JavaScript converts the number to a string and concatenates.
Figure 2-8
60
Section 1
Chapter 2
61
Description
Assigns the result of the expression to the variable. Adds the result of the expression to the variable. Subtracts the result of the expression from the variable. Multiplies the variable by the result of the expression. Divides the variable by the result of the expression. Stores the modulus of the variable and the result of the expression in the variable.
Description
A variable stores a value that can change as the program executes. To declare a variable, code the keyword var and a variable name. To declare more than one variable in a single statement, code var and the variable names separated by commas. To assign a value to a variable, you use an assignment statement that consists of the variable name, an assignment operator, and an expression. When appropriate, you can declare a variable and assign a value to it in a single statement. Within an expression, a string literal is enclosed in quotation marks. A numeric literal is a valid integer or number that isnt enclosed in quotation marks. When the expression in an assignment statement contains both strings and numbers, the numbers are converted to strings before the expression is evaluated.
Figure 2-9
62
Section 1
Chapter 2
63
Description
An object has properties that represent attributes like the width of a window or the value thats in an XHTML element. An object also has methods that do functions that are related to the object. When you call a method, you may need to pass one or more parameters (or arguments) to it by coding them within the parentheses after the method name. If the method requires more than one parameter, you must separate them with commas. Object chaining lets you access the properties or methods of objects that are nested inside other objects. Often, an object is stored in the property of another object or returned by a method of another object.
Figure 2-10
64
Section 1
and then it gets the value property of that object. The second statement gets the location property of the window object, which is a string, and then uses the toLowerCase method of the string object to convert the location property to lowercase letters. If this is confusing right now, youre going to see many more examples of the use of objects and object chaining in the rest of this chapter. So by the end of this chapter, you should become comfortable with the use of object chaining.
Chapter 2
65
Description
The URL of the current web page. If you set this property, the browser will load the new page.
Description
Displays a dialog box with the string thats passed to it. Displays a dialog box with the string in the first parameter and a text box that contains the default value from the second parameter. When the user enters a value and clicks OK, the value is returned. Converts the string thats passed to it to an integer data type. Returns NaN if the string cant be converted to a valid integer. Converts the string parameter to a numeric data type. Returns NaN if the string cant be converted to a valid number.
parseInt(string) parseFloat(string)
Examples that use the properties and methods of the window object
alert("Invalid entry."); var userEntry = prompt(errorMessage,100); parseInt("12345.67"); // returns the parseFloat("12345.67"); // returns the parseFloat("Ray Harris"); // returns NaN // displays "Invalid entry." // accepts user entry integer 12345 floating point value 12345.67
Description
Gets the XHTML element that has the id thats passed to it and returns the element to the script. Writes the string thats passed to it to the document. Writes the string thats passed to it to the document and advances to a new line.
Description
The window object is the global object when JavaScript is used in a web browser. It provides the global and browser properties and methods. JavaScript lets you omit the object name and period when referring to the window object. The document object is the object that allows you to work with the DOM.
How to use the window and document objects
Figure 2-11
66
Section 1
Chapter 2
67
Description
Returns a string that contains the value of the object rounded to the number of decimal places in the parameter.
Examples
var balance = 2384.55678; alert ( balance.toFixed(2) ); // creates a number object named balance // displays 2384.56 // balance is still 2384.55678 balance = parseFloat( balance.toFixed(2) ); // balance is now 2384.56
Description
Returns a new string that contains part of the original string. This substring starts at the position in the first parameter and contains the number of characters in the second parameter. The positions in a string start with zero. Returns a new string with the letters converted to lowercase. Returns a new string with the letters converted to uppercase.
toLowerCase() toUpperCase()
Examples
var guest = "Ray Harris"; alert ( guest.toUpperCase() ); alert ( guest.substr(0,3) ); guest = guest.substr(4,6); // // // // creates a string object named employee displays "RAY HARRIS" displays "Ray" guest is now "Harris"
Description
Returns a string with the formatted date. Returns the month number from the date. The months are numbered starting with zero. January is 0 and December is 11. Returns the day of the month from the date. Returns the four-digit year from the date.
Examples
var today = new Date(); alert ( today.toDateString() ); alert ( today.getFullYear() ); alert ( today.getMonth() ); // // // // // creates a Date object named today assume the current date is 09/20/2008 displays Sat Sep 20 2008 displays 2008 displays 8, not 9, for September
Description
When you declare a number or string variable, a Number or String object is created. Then, you can use the Number or String methods with the variable. To create a Date object, assign new Date() to a variable. Then, you can use the Date methods with the variable.
How to use the Number, String, and Date objects
Figure 2-12
68
Section 1
Chapter 2
69
Type
String Boolean
Description
The contents of the text box. Controls whether the text box is disabled.
How to use the value property to get the value in a text box
In two statements
// Store a reference to the text box var rateTextbox = document.getElementById("rate"); // Get the value and convert it to a number var rate = parseFloat( rateTextbox.value );
Returns
Nothing
Description
Moves the cursor into the text box.
How to use the focus method to move the cursor to a text box
document.getElementById("investment").focus();
Description
When you use a text box to get numeric data that youre going to use in calculations, you need to use either the parseInt or parseFloat method to convert the string data to numeric data. To place the cursor in a text box, you use the focus method of the Textbox object.
Figure 2-13
70
Section 1
Chapter 2
71
Description
Equal Not equal Less than Less than or equal Greater than Greater than or equal
Example
lastName == "Harris" testScore == 10 firstName != "Ray" months != 0 age < 18 investment <= 0 testScore > 100 rate / 100 >= 0.1
Description
NOT AND OR
Example
!isNaN(age) age > 17 && score < 70 isNaN(rate) || rate < 0
Description
A conditional expression uses the relational operators to compare the results of two expressions. A compound conditional expression joins two or more conditional expressions using the logical operators. The isNaN method tests whether a string can be converted to a number. It returns true if the string is not a number and false if the string is a number.
Note
Confusing the assignment operator ( = ) with the equality operator ( ==) is a common programming error.
How to code conditional expressions
Figure 2-14
72
Section 1
The last example shows how to nest one if statement within another. Here, the second if statement is nested within the else clause of the first if statement. When these nested if statements are executed, an error message is displayed if totalMonths is not a number or totalMonths is a number less than or equal to zero. This ends the if statement and nothing else happens. But if totalMonths is a number greater than zero, the else clause starts by calculating the values of the variables named years and months. Then, the if statement thats nested in the else clause composes the message thats displayed based on the values of the years and months variables.
Chapter 2
73
A nested if statement
if ( isNaN(totalMonths) || totalMonths <= 0 ) { alert ("Please enter a number of months greater than zero."); } else { var years = parseInt ( totalMonths / 12 ); var months = totalMonths % 12; if ( years == 0 ) { alert ( "The investment time is " + months + " months."); } else if ( months == 0 ) { alert ( "The investment time is " + years + " years."); } else { var message = "The investment time is " + years + " years "; message += "and " + months + " months."; alert(message); } }
Description
An if statement can include multiple else if clauses and one else clause at the end. The if clause of the statement executes one or more statements if its condition is true. The else if clause is executed when the previous condition or conditions are false. The statement or statements within an else if clause are executed if its condition is true. The else clause is executed when all previous conditions are false. You can code one if statement within the block of statements of an if, else if, or else clause in another if statement. This is referred to as nested if statements.
How to code if statements
Figure 2-15
74
Section 1
Chapter 2
75
Description
The while statement is used to create a while loop that contains a block of code that is executed as long as a condition is true. This condition is tested at the beginning of the loop. When the condition becomes false, JavaScript skips to the code after the while loop. The for statement is used to create a for loop that contains a block of code that is executed a specific number of times. When you code one loop within another loop, you are coding nested loops. JavaScript also offers two other looping structures, which youll learn about in chapter 8.
Figure 2-16
76
Section 1
Chapter 2
77
How to call a function with two parameters that doesnt return a value
displayEmail( "mike", "murach.com");
Description
A function is a block of code that you can use multiple times in an application. It can require one or more parameters. A function can return a value to the code that called it by using the return statement. When a return statement is executed, the function returns the specified value and ends. The code that calls a function may discard the returned value, store it in a variable, or use it in an expression. If a function ends without encountering a return statement, it returns a special value called undefined.
Figure 2-17
78
Section 1
Chapter 2
79
Common events
Object
button window
Event
onclick onload
Occurs when
The button is clicked. The document has been loaded into the browser.
Description
An event handler is executed when the event that triggers it occurs. The event handler for the onload event of the window object can be used to assign event handlers to other events after the DOM has been built.
Figure 2-18
80
Section 1
Chapter 2
81
Figure 2-19
82
Section 1
Chapter 2
83
Figure 2-19
84
Section 1
Perspective
The goal of this chapter has been to get you started with JavaScript and to get you started fast. Now, if you understand the Future Value application, youve come a long way. You should also be able to write basic JavaScript applications of your own. Keep in mind, though, that this chapter is just an introduction to the JavaScript essentials that will be expanded upon by the chapters in section 2.
Terms
syntax statement comment identifier reserved word keyword camel casing primitive data type number data type integer decimal value floating-point number exponent string data type string empty string escape sequence Boolean data type Boolean value expression arithmetic operator order of precedence concatenate variable declare a variable assignment statement assignment operator compound assignment operator string literal numeric literal object property method instance constructor function dot operator call a method parameter argument object chaining global object window object document object control statement conditional expression relational operator compound conditional expression logical operator if statement if clause else if clause else clause nested if statements while statement while loop for statement for loop function return statement call a function event event handler
Chapter 2
85
Exercise 2-1
This exercise is for beginners. It steps you through the process of building the Sales Tax application of chapter 1. This exercise also gives you a chance to do some experimenting, which is a great way to learn JavaScript programming.
2. 3.
Enter valid numeric values in the first two input boxes and click the Calculate button. Notice that nothing happens. Use your text editor to open the sales_tax.js file for this application. It is in the same folder as the html file. Then, notice that this file only contains the $ function thats used to get the object for an XHTML element. Use your text editor to open the sales_tax.html file for this application. Then, note the ids that are used for the text boxes for this application. Start the event handler for the window.onload event by entering this code:
window.onload = function () { alert ("This is the window.onload event handler."); }
4.
Then, save the file, switch to Firefox, click the Reload button, and note the message thats displayed. Or, if nothing happens, check your code, fix it, and try this again. If necessary, you can access the Firefox Error Console as shown in figure 2-3. When youve got this working right, switch back to your editor. 6. Between the $ function and the window.onload event handler, start a function named calculate_click by entering this code:
var calculate_click = function () { alert ("This is the calculate_click event handler."); }
Then, save the code, switch to Firefox, click the Reload button, and note that this function isnt executed. Thats because it hasnt been called. Now, switch to your editor.
86
Section 1
7.
Call the calculate_click function from the window.onload event handler by entering this statement after the alert statement:
calculate_click();
Then, save the file, switch to Firefox, and click the Reload button. This time, two message boxes should be displayed: one by the window.onload event handler and one by the calculate_click function. If this doesnt work, fix the code and try it again. Then, switch to your editor. 8. Assign the calculate_click function to the click event of the Calculate button by replacing the statement you entered in step 7 with this statement:
$("calculate").onclick = calculate_click;
Then, save the file, switch to Firefox, click the Reload button, and click on the Calculate button. If you did everything right, the two message boxes are again displayed. Otherwise, fix the code and try again. Then, switch to your editor.
10. If you have any questions about how variables and arithmetic statements work, review figures 2-7 through 2-9. Then, experiment with any statements that you dont understand in the calculate_click function. To display the results of your statements, you can use alert statements as in step 9. 11. Replace the statements that you entered in step 9 with these statements:
var subtotal = parseFloat( $("subtotal").value ); var taxRate = parseFloat( $("taxRate").value ); // calculate results var salesTax = subtotal * (taxRate / 100); salesTax = parseFloat( salesTax.toFixed(2) ); var total = subtotal + salesTax; // display results $("salesTax").value = salesTax; $("total").value = total.toFixed(2);
The first two statements will get the user entries; the last two statements will display the results. This is explained in figure 2-13. At this point, the application should work if the user enters valid numbers. 12. Comment out the two alert statements by entering slashes before them.
Chapter 2
87
13. Check the user entries for validity by entering this code with the statements that do the calculations in the else clause:
if ( isNaN(subtotal) || isNaN(taxRate) ) { alert("Please check your entries for validity."); } else { // the statements that do the calculations should be here }
This just checks to make sure that both user entries are numeric before the calculations are done. 14. At this point, you have a working application, but one that can be improved. If you would like to improve it, review the code in figure 1-13 of the last chapter for ideas. For instance, you can check to make sure that each user entry is both numeric and greater than zero, and you can display a different error message for each text box. Or, you can add a statement to the window.onload function that moves the focus to the first text box. When youre through experimenting, close the files.
Exercise 2-2
In this exercise, youll enhance the Future Value application in several ways. That will give you a chance to use some of the skills that youve learned in this chapter.
2.
Enter valid numeric values in the three input boxes. For the first test run, keep these values simple like 100 for monthly investment, 12 for annual interest rate, and 1 for number of years. Then, click the Calculate button to display a valid result in the fourth text box. Enter invalid values in the three input boxes and click the Calculate button. Then, respond to the first message box by entering valid data and clicking the Calculate button again. Do the same for the next two message boxes. Use your text editor to open the future_value.js file for this application. This file should be in the same folder as the html file (see step 1). Modify the validity testing for the annual interest rate so it has to be a valid number thats greater than zero and less than or equal to 20. Next, adjust the error message thats displayed to reflect this third validity test. To test this enhancement, save the JavaScript file, switch to Firefox, click on the Reload button, enter an interest rate thats greater than 20, and click the Calculate button.
3.
88
Section 1
6.
Switch back to the JavaScript file in your text editor, modify the validity testing for the number of years so this value also has to be less than or equal to 50, and modify the error message to reflect this change. Then, save the file, switch to Firefox, and test this change. Use your text editor to open the html file for this application and add a Clear button below the Calculate button. To do that, you can just copy the XHTML for the Calculate button and modify the id and value attributes. Then, save the file, switch to Firefox, and test this change. Switch back to the JavaScript file in your text editor and add an event handler named clear_click that clears the text boxes when the Clear button is clicked. This handler should store empty strings in the four text boxes on the page. After you code the event handler, add a line to the window.onload handler that assigns the new event handler to the click event. Then, test this change. Change this application so it calculates the future value of a one-time investment instead of fixed monthly investments. To do that, modify the XHTML file so the first label reads One-Time Investment. Next, modify the code in the calculate_click event handler so interest is calculated and added to future value just once each year for the number of years that were entered by the user. Then, test this change.
8.
Disable and enable the text box for the annual interest rate
10. Modify the JavaScript code in the calculate_click event handler so it disables the text box for the annual interest rate after it finishes the for loop and displays the future value. Next, modify the code in the clear_click event handler so it enables this text box when the Clear button is clicked. Then, test these changes.
To do this, you need to use the toDateString method as shown in figure 2-12. Then, test this change.
If you were able to do all of the steps in this exercise, congratulations! Youre well on your way to learning JavaScript and DOM scripting.
To get your copy, you can order online at www.murach.com or call us at 1-800-221-5528 (toll-free in the U.S. and Canada). And remember, when you order directly from us, this book comes with my personal guarantee:
100% Guarantee
You must be satisfied. Each book you buy directly from us must outperform any competing book or course youve ever tried, or send it back within 90 days for a full refundno questions asked.