<<

6Lesson 6: JavaScript Events, Functions and Methods

Objectives By the end of this lesson, you will be able to:  6.1: Define user events, and identify and use JavaScript handlers.  6.2: Describe the role of functions in JavaScript development.  6.3: Use JavaScript code to define functions.  6.4: Use JavaScript code to call functions.  6.5: Use methods as functions in JavaScript code.  6.6: Identify common errors in JavaScript. 6-2 Advanced HTML5 and CSS3 Specialist

Pre-Assessment Questions

1. Which JavaScript event occurs when a Web page is accessed and appears in the browser? a. submit b. focus c. change d. load

2. In JavaScript, what is a function? a. A named set of statements that performs a task or calculates a value. b. A customized method that compiles a script. c. A commonly used term for a script. d. A built-in object behavior.

3. Discuss the output of the following JavaScript statements. var x = 4; var y = 8; var z = 2; var result = x + y / z;

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 Lesson 6: JavaScript Events, Functions and Methods 6-3

User Events and JavaScript Event Handlers

OBJECTIVE Before you begin using JavaScript methods and functions, it is helpful to understand the 6.1: User events and role of events in JavaScript and how JavaScript handles them. JavaScript event handlers Whether they are submitting forms or navigating Web pages, users generate events. JavaScript contains predetermined event handlers that deal with these events. Table 6-1 describes some commonly used JavaScript events. Many others exist but are beyond the scope of this course.

Many of the events described in the table can be triggered by situations other than those given in the examples. The abort event, for example, can also occur when a transaction is canceled or when a resource has been moved. NOTE: The examples in this table are not a complete listing. You have the opportunity to use Table 6-1: JavaScript user event examples event handlers in Optional Lab 6-1: Using JavaScript Event Description event handlers. abort Occurs when the loading of an image is aborted

blur Occurs when input focus is removed from a form element (e.g., when a user clicks the mouse button outside of a particular field)

click Occurs when the user clicks on a link or form element

change Occurs when a user changes the value of a form field

error Occurs when an error takes place while a page or image is loading

focus Occurs when a user gives input or focus to a form element

load Occurs when a page is loaded into the browser (i.e., opened)

mouseOver Occurs when the user moves the mouse pointer over a link, image or other visible element on a page

mouseOut Occurs when the mouse pointer leaves a link, image or other visible element on a page

reset Occurs when a form's Reset button is clicked

select Occurs when the user selects the text in a form field

submit Occurs when a form's Submit button is clicked

unload Occurs when a page is unloaded from the browser (i.e., closed)

Table 6-2 lists JavaScript event handlers designed to process events such as those listed above, with the object(s) that can support each event. Note that these are commonly used event handlers. Many others exist but are beyond the scope of this course.

NOTE: Table 6-2: JavaScript event handlers As you gain more experience with Object Event Handler(s) JavaScript, you will see that learning button onclick how and when to use event handlers reset onclick is one of the most important submit onclick JavaScript skills you can acquire. radio onclick, onblur, onfocus checkbox onclick, onblur, onfocus

link onclick, onmouseover, onmouseout

form onsubmit, onreset

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 6-4 Advanced HTML5 and CSS3 Specialist

Table 6-2: JavaScript event handlers (cont'd)

Object Event Handler(s)

text onchange, onfocus, onblur, onselect

textarea onchange, onfocus, onblur, onselect

select onchange, onfocus, onblur

image onabort, onerror, onload

area onclick, onmouseover, onmouseout

window onload, onunload, onerror

Almost every object in an HTML document is capable of receiving some type of event. The objects will only respond to these events if the developer adds event handlers in the appropriate places in the document's code.

Remember that event handlers can be placed in script blocks within an HTML file or in an external script file. They can also be placed inline into HTML element tags, which is generally considered poor practice but may be useful in some situations.

You will use several of these events and event handlers in this course.

® CIW Online Resources – Movie Clips Visit CIW Online at http://education.Certification-Partners.com/CIW to watch a movie clip about this topic. Lesson 6: JavaScript Events and Functions

® CIW Online Resources – Online Exercise Visit CIW Online at http://education.Certification-Partners.com/CIW to complete an interactive exercise that will reinforce what you have learned about this topic. Exercise 6-1: JavaScript user events

OBJECTIVE Introduction to JavaScript Functions 6.2: Functions in JavaScript As you have learned, JavaScript defines some commonly used methods such as alert(), prompt(), confirm() and document.write(). Some methods return values and some do not.

For example, the document.write() method does not return a value to any other variable or function. However, the prompt() method returns a value in the form of a text string, which you can then pass to a variable or to another method, such as alert(). function To take full advantage of such values, you must be able to define your own processes, A named set of statements that called functions. A user-defined function is a named set of statements that performs a performs a task or task or calculates a value. calculates a value. Functions are fundamental tools in JavaScript. By plugging data into a function, a value will return either to the screen, to a variable, or to another function. Functions enable you to write code and place it into a single unit that can perform a specific task repeatedly throughout the program, as needed.

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 Lesson 6: JavaScript Events, Functions and Methods 6-5

NOTE: Generally speaking, all methods are functions, but not all functions are JavaScript makes necessarily methods. In most programming, methods belong to an object or no distinction class, whereas functions do not. between a function that returns a value In JavaScript, you can use several built-in functions to improve your program's efficiency and a function that does not. Some and readability. In addition, you can create your own functions to make your programs programming scalable. languages require different syntax for procedures that To use functions effectively, you need to know how to: simply perform actions, and • Define (or declare) functions. functions that perform actions and • Pass arguments to them. return a value. • Call them. • Return function results. Defining a Function

OBJECTIVE You define a function when you encompass a group of script statements into a function 6.3: Defining block. A function definition consists of the following in this order: JavaScript functions

6.4: Calling • The function keyword JavaScript functions • The name of the function (which may be defined by the user) • A list of arguments to the function, enclosed in parentheses ( ) and separated by commas • The JavaScript statements that define the function, enclosed in curly braces { } calling statement A function's statements are processed when the function is called by a calling A statement that transfers program statement. A function can be called by: execution to a , • Another function. procedure or function. When the • A script block. subroutine is complete, • An event, such as a mouse click, or a page loading or unloading. execution transfers back to the The generic syntax for a function is as follows: command following the call statement. function functionName(argument1, argument2, ...) { //statement(s) here } NOTE: This example demonstrates how The keyword function must be typed as shown, in all lowercase letters. The user defines to create a user- the function name in this example. Function names must be unique for each particular defined function. You will apply this page. As with variable names, function names should reflect the function's intended info in the next lab. purpose. Also, the naming rules that apply to variables also apply to function names: You will not copy code. This example • The function name must begin with a letter or underscore character is your reference point if you need to • see how to perform Subsequent characters can be letters, numbers, underscore ( _ ) characters or a this task. dollar sign ($).

Be aware that the dollar sign ($) can also be used in JavaScript as a single-letter name for a function or as shorthand to refer to the jQuery namespace. These uses are beyond the scope of this course, but you should be aware that the $ sign has some specific uses.

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 6-6 Advanced HTML5 and CSS3 Specialist

argument The curly braces must encompass any statements that are to execute as part of that A value or expression function. Parentheses () must follow the user-defined function name. These parentheses containing data or are used to receive arguments, but a function does not necessarily have to take or use code that is passed them. Arguments (often referred to as parameters) are pieces of data that the function on to a function or procedure. Also receives and manipulates within the function. called a parameter.

A function can receive as many arguments as it needs to perform its task.

One of the most powerful features of a function is its ability to return a value to the calling statement. The return keyword is used to return values from a function. This concept will be discussed later in this lesson.

Adding JavaScript functions to an HTML page As discussed in the previous lesson, there are multiple ways to add JavaScript to your HTML pages:

• You can define functions in an external JavaScript file, then include a

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 Lesson 6: JavaScript Events, Functions and Methods 6-7

This example demonstrates two coding practices:

• A short comment indicates the function's intended purpose. Some developers prefer to place this type of explanation before the beginning of the function definition, whereas others prefer to place it inside the function as shown in the example. • The statements that compose the function are indented from the function keyword. In this example, the code is indented four spaces. This spacing scheme has no effect on the performance of the function, but makes the code much easier to read. In this example, the benefit of indentation may not be as apparent as it is in a script that contains many more lines.

Note that indenting improves human readability but not program performance. There are no rules about how many spaces to indent certain lines of code, and some programmers do not use spaces but rather tab stops. Different text programs can render tabs differently from spaces, and different fonts can render even spaces to look variable in length. Therefore a file that looks consistently indented when viewed in one program or font may look inconsistent in another. Although many programmers tend to vary their indentation schemes, it is helpful to develop your own spacing scheme and stick to one (preferably monospace) font.

It is recommended that you adopt consistent coding practices as you learn JavaScript. Consistent coding will help you later on as you troubleshoot errors.

In the following lab, you will create a simple function that displays an alert dialog box when the Web page is loaded. Suppose that due to the economy and tight resources, your company has been slow to release new products this year. You have had a couple new items in production, and you know customers are anticipating them. Next week you will finally release the first of the new products. The boss asks your Web team to put some fanfare on the site. So you suggest that in addition to announcing the new products on the home page, you can use JavaScript to create an alert box that will pop up when your company's site loads in the user's browser. The alert could say, "Finally! Our new product is here! Visit our New Products page to learn more." Your site visitors will not miss this announcement.

Lab 6-1: Creating a user-defined function in JavaScript

OBJECTIVE In this lab, you will create a simple function that displays an alert dialog box. The 6.3: Defining function will be invoked by the onload event handler. JavaScript functions

6.4: Calling 1. Windows Explorer: Copy the Lesson06 folder from your student lab files to your JavaScript functions Desktop.

2. Editor: Open Lab_6-1.htm in your student lab files. NOTE: Be aware that if 3. Editor: Create a function named myFunction() in the

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 6-8 Advanced HTML5 and CSS3 Specialist

4. Editor: Inside the function, create an alert dialog box. For the alert's message, use: The HTML page has loaded.

5. Editor: You will now add an onload event handler inline to the document's tag. The onload event handler will be used to call the function that you just created. Locate the tag near the top of the document. Modify the tag as indicated in bold:

6. Editor: Save Lab_6-1.htm.

7. Browser: Open Lab_6-1.htm. Your screen should resemble Figure 6-1.

Figure 6-1: Page for Lab_6-1.htm with alert

8. Browser: After clicking OK, your screen should render the HTML page seen behind the alert box in the preceding figure.

9. Close your browser and text editor.

In this lab, you successfully created a simple function that displayed an alert dialog box. In addition, you launched your function using the onload event handler and inline scripting.

Remember that inline scripting is generally considered poor coding practice; however, you will see it used in Web development so therefore it is useful for you to understand how it is written and how it works.

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 Lesson 6: JavaScript Events, Functions and Methods 6-9

Calling a Function

OBJECTIVE Calling a function can be performed from one function to another, from a user event, or 6.4: Calling from a separate

NOTE: In this example, the function showName() is called using the onload event handler, as in Consider the the previous lab. Note that the first line of the showName() function calls the getName() importance of creating and function. The getName() function would then execute in its entirety before processing of maintaining a library the showName() function is completed. of functions. Experienced developers prefer to You have now seen two techniques for calling functions: use code that is already written as • The first was to use an event handler to capture an event and invoke the function. opposed to having to write code from • The second was to simply include the name of the function in a

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 6-10 Advanced HTML5 and CSS3 Specialist

NOTE: You can examine a form that calls aware that the Optional Lab uses

some advanced functions in the Note that in the second

Multiply By

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 Lesson 6: JavaScript Events, Functions and Methods 6-11

NOTE: In this example, the values entered in the text boxes are multiplied by the returnValue() This section function, with the resulting value returned to the calling statement. This example demonstrates how to return a value demonstrates some JavaScript syntax that has not yet been discussed. Consider this line from a function to of code: the calling statement. This myProduct = document.myForm.input1.value ... section also demonstrates how to wrap an alert() This code demonstrates JavaScript syntax for accessing a value entered in an HTML text method around a box and assigning that value to a variable. In this case, one value is multiplied by function call. another, and that value is assigned to the myProduct variable. Note that the form is named myForm, and the text boxes are named input1 and input2. This type of syntax will be discussed in detail later in the course.

Note that the returnValue() function is called from within the alert() method argument. The name of the function is concatenated into the alert() message. Remember that the return keyword returns a value to the calling statement. So after the function calculates the numbers, the result (held in myProduct) is returned to the calling statement and concatenated into the alert() message.

Any type of value can be returned, as can global and local variables. Global and local variables will be discussed following a brief discussion of operator precedence.

Operator precedence NOTE: When a JavaScript interpreter reads JavaScript, it must determine which operations to In JavaScript, all perform first. Operator precedence determines which expressions will be evaluated before mathematical and string others. concatenation operators take JavaScript uses more operators than just mathematical operators, thus it has somewhat precedence over comparison more complex precedence rules than those of mathematics alone. However, JavaScript operators, allowing operator precedence does generally follow the precedence rules of mathematics. expressions that act as operands for comparisons to be For example, consider the expression 4 + 6 * 2. You might expect this expression to completely evaluate to 20. However, JavaScript follows mathematical precedence, so: evaluated before they are used for • Operations within parentheses ( ) or brackets [ ] are performed first. comparison operations. • Multiplication and division take precedence over addition and subtraction. • Remaining operations are performed left to right. Thus the expression 4 + 6 * 2 would evaluate to 16. However, if you were to rewrite this expression as (4 + 6) * 2, it would evaluate to 20 because parenthetical expressions take precedence over multiplication. local variable In JavaScript, a variable declared within a function, Global vs. local variables whose value cannot If you declare a variable within a function definition, the only way you can access or be accessed from any function other change it is from within that function. Once you declare a variable within a function, the than the one in variable is known as a local variable, and you cannot access its value from any other which it was declared. function except the one in which it was declared. global variable Occasionally, you will want to declare a variable that can be accessed by more than one In JavaScript, a function or script block in your program. You will need to declare that variable outside of variable declared outside of any any function definition, usually at the start of your script. This variable is known as a function, whose global variable. If you declare a global variable, you can then access its value from any value can be accessed from any function or script block on that page. function or script block on the page.

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 6-12 Advanced HTML5 and CSS3 Specialist

JavaScript allows you to use the same variable name in different functions. However, same-named variables are treated as separate variables. Note that you should create different names for variables in your scripts whenever possible.

Recall that JavaScript provides the var keyword to declare variables. Recall also that JavaScript does not require the var keyword when you want to create a variable. You can simply name the variable in your scripts and start using it. A variable can have its data type changed over the course of a script.

Be aware that not using the var keyword can cause some unexpected behavior in certain situations. As previously stated, a variable created in a function took on local scope and was available only to that script. That statement is true provided that you use the var keyword to declare the variable. Any variable that is created without the var keyword is global in scope, regardless of where that variable was created. However, a variable created under this circumstance is not available until the function is called. This is another good reason to always use the var keyword to declare your variables prior to using them in your scripts.

In the following lab, you will use JavaScript create a simple function, pass arguments to that function when it is called, and return a value to the calling statement. Suppose your company employees find that they are spending too much time answering phone calls from customers who ask questions that are already answered on the Web site. Your Web team supervisor asks you to modify the company site's Contact page to reduce the phone calls. She wants customers to read the Frequently Asked Questions (FAQ) page first to see if they can find the help they need before they try contacting the company by phone. You suggest that you add an alert box to the Contact page that will pop-up when users open that page to look for the phone number. The alert can advise customers to check the FAQ page first for help. When the customer clicks OK, he is then redirected to the FAQ page, and a new alert pops up. This one asks the customer if after reading the FAQ page, he still needs help. If the customer clicks the Yes button, then a new alert box will appear with the customer service phone number.

Lab 6-2: Using functions, arguments and return values in JavaScript

OBJECTIVE In this lab, you will create a simple function, pass arguments to that function when it is 6.3: Defining JavaScript functions called, and return a value to the calling statement.

6.4: Calling 1. Editor: Open Lab_6-2.htm in your student lab files. JavaScript functions 2. Editor: A simple function has been created for you. The Lab_6-2.htm file contains a form button. Add an onclick event handler to the tag. Use this event handler to invoke myFunction(). Enter the following code:

3. Editor: Save Lab_6-2.htm.

4. Browser: Open Lab_6-2.htm. Your screen should resemble Figure 6-2.

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 Lesson 6: JavaScript Events, Functions and Methods 6-13

Figure 6-2: Page for Lab_6-2.htm

5. Browser: Click Call Function. You should see an alert as shown in Figure 6-3.

Figure 6-3: Result of function call

6. Browser: Click OK.

7. Editor: Open Lab_6-2a.htm. You will now add an argument to a function call, then use that argument in the function. Locate the tag in the HTML form. Add the following string in the parentheses after the function name in the onclick expression:

'a string of text'

You are passing literal text to the function, so be sure to include the quotation marks around the string (single quotes in this case because they are inside the quoted function). Enter the following code as shown in bold:

8. Editor: Add an argument named arg1 in the parentheses after the function name. Concatenate arg1 into the argument of the alert() method. To perform this task, enter the code as shown in bold:

function myFunction(arg1) { alert("The function has been called and was passed " + arg1); }

9. Save Lab_6-2a.htm.

10. Browser: Open Lab_6-2a.htm. Your screen should resemble Figure 6-2. Click Call Function. You should see an alert as shown in Figure 6-4.

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 6-14 Advanced HTML5 and CSS3 Specialist

Figure 6-4: Result of function call after adding argument

11. Browser: Click OK.

12. Editor: Open Lab_6-2b.htm. Add a return statement to myFunction() after the alert() statement. Add this code:

function myFunction(arg1) {

alert("The function has been called and was passed " + arg1);

return "myFunction() return value";

}

13. Editor: In order to see the return value from the function, you will add an alert() method to the calling statement. Locate the onclick event handler defined in the tag near the bottom of the file. Wrap an alert() method around the call to myFunction() by entering the following code:

14. Save Lab_6-2b.htm.

15. Browser: Open Lab_6-2b.htm. Your screen should resemble Figure 6-2. Click Call Function. You should see an alert as shown in Figure 6-4. Click OK. You should then see an alert as shown in Figure 6-5.

Figure 6-5: Return value from myFunction()

16. Close your browser and text editor.

In this lab, you created a function that received an argument.

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 Lesson 6: JavaScript Events, Functions and Methods 6-15

® CIW Online Resources – Online Exercise Visit CIW Online at http://education.Certification-Partners.com/CIW to complete an interactive exercise that will reinforce what you have learned about this topic. Exercise 6-2: JavaScript functions

pass by value When you created the calling statement in Lab 6-2, you passed a value to the function as Mode that an argument. You then returned a value to the calling statement. When a value is passed describes when values are passed into a function and changed, the value of the original data (also called a primitive value) to a function, and is not changed. In programming, this mode is known as pass by value. The exception to the function's parameters receive this rule is if an object reference is passed as an argument to a function. JavaScript uses a copy of its pass by reference for object arguments. argument's value. The next lab will use one function to call another. It will also pass a value to that pass by reference Mode that function, and then return a value to the calling statement. The program is in the form of describes when an online quiz. Suppose you work for an online training company that offers quizzes and values are passed to a function, and exams on its site. You could use a function such as this one for the study quizzes used in the function's between exams. This would provide feedback to students as they answer questions, parameters receive letting them know what percentage of the material they already understand, as well as its argument's actual value. which topics they need to study more.

Each time the user answers a question, the runningTotal() function tabulates the running total of points that user has received for correct answers. The conditional assignment operator will assign a point or not, depending on whether the user's answer to a quiz question is correct. In addition, this lab will use the concept of operator precedence. This lab is rather complex, so be sure to refer to the lab recap that follows to examine the lab in a line-by-line analysis.

OBJECTIVE 6.3: Defining Lab 6-3: Calling a function from within another function in JavaScript JavaScript functions

6.4: Calling JavaScript functions In this lab, you will use one function to call another. It will also pass a value to that function, and then return a value to the calling statement.

1. Editor: Open Lab_6-3.htm in your student lab files.

2. Editor: Examine the following source code:

numCorrect variable to the takeTest() function 3. Editor: Locate the

tag near the bottom of the document. Examine the unless it is assigned tag. Note especially the code indicated in bold: to a local variable inside the function.

4. Editor: Close Lab_6-3.htm.

5. Browser: Open Lab_6-3.htm. Your screen should resemble Figure 6-6.

Figure 6-6: Page for Lab_6-3.htm

6. Browser: Click the Take Quiz button. Respond to each of the prompts. Enter both correct and incorrect answers to check the logic of the quiz.

7. Close your browser.

Examining Lab 6-3 NOTE: Note the use of the if (response) statement in the lab code, which is included at key points The values for the so that the JavaScript interpreter would not return an error if the user clicked the Cancel q2 and q3 variables use a \n character, option repeatedly. For now, take the time to examine the most relevant parts of this lab in which is the newline detail. Following are the key script elements, numbered for discussion purposes only. character. 01. var numCorrect = 0; 02. function takeTest() {

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 Lesson 6: JavaScript Events, Functions and Methods 6-17

03. var response = ""; 04. var points = 0; 05. var q1 = "What company developed JavaScript?"; 06. var a1 = "NETSCAPE"; 07. var q2 = "Using JavaScript operator precedence,\n what is the result of the following expression? 2 + 4 * 6";

08. var a2 = 26; 09. var q3 = With what object-oriented programming language\n is JavaScript often compared and confused??";

10. var a3 = "JAVA"; 11. response = prompt(q1,""); 12. if (response) points = runningTotal((response.toUpperCase() == a1) ? 1 : 0); 13. alert(points); 14. response = prompt(q2,""); 15. if (response) points= runningTotal((response == a2) ? 1 : 0); 16. alert(points) 17. response = prompt(q3,"") 18. if (response) points = runningTotal((response.toUpperCase() == a3) ? 1 : 0);

19. alert("You answered a total of " + points + " correctly."); 20. numCorrect = 0; 21. points = 0; 22. } 23. function runningTotal(i) { 24. numCorrect += i; 25. return numCorrect; 26. } • Line 01: Global variable The numCorrect variable is declared outside either function, making it a global variable with global scope. This variable is needed by both the runningTotal() and the takeTest() functions, and therefore is defined outside of either function. • Line 02: Defining the takeTest() function Note the standard syntax of function takeTest() { to open the function definition. • Lines 03 through 10: Local variables The variables response and points, and the question and answer variables (q1, a1, etc.), are declared here within the takeTest() function. Their values can only be changed and accessed from within this function, which is appropriate because these variables are not needed in the runningTotal() function.

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 6-18 Advanced HTML5 and CSS3 Specialist

• Line 11: Collecting the user's answer to a question The variable response is assigned the user's input to the prompt(). The prompt itself uses the variable q1, which contains the text of the first question. • Line 12: Comparing the user's answer to the correct answer, and calling the runningTotal() function This line reads as follows: if (response) points= runningTotal((response.toUpperCase()  == a1) ? 1 : 0)

JavaScript will process this expression in the following order.

First: if (response)

An if statement checks whether the user has clicked the Cancel button on the prompt dialog box. If so, a null value will be returned. Later in the program, the toUpperCase() method will be applied to two of the user's answers. If you attempt to apply the toUpperCase() method to a null value, an error will be generated. Thus, the if statement averts this possible error message.

Second: (response.toUpperCase() == a1)

A logical expression has been presented, and evaluates to true or false, depending on the user's answer.

Third: JavaScript evaluates (response.toUpperCase() == a1) ? 1 : 0

NOTE: If the user's response is correct (the expression is true), then the value of 1 will Note that the user's be made ready for whatever comes next. If not, then the value of 0 will be made input is compared to the value held by ready. The conditional operator ? : decides which of these values will be the a1 variable. returned. Remember that the answer variables were defined in Fourth: The original line will be read by JavaScript as one of the following: uppercase letters. Thus the runningTotal(1) toUpperCase() or function is needed runningTotal(0) to convert the user's response to uppercase letters as JavaScript will at this point call the runningTotal() function and at the same time well. pass one of two values, either 0 or 1.

At this point, skip forward to Line 23.

• Lines 23 through 26: The runningTotal(i) function Note that the function definition takes an argument named i, which has no meaning of its own and is simply a variable that holds whatever value is passed to this function. You know from Line 11 that the value being passed can only be 1 or 0, and whichever it is will be added to the numCorrect variable. If the answer is incorrect, numCorrect will be incremented by 0, meaning that its value will remain unchanged. If the answer is correct, numCorrect will increase by the value of 1. • Once numCorrect has been manipulated, the current value of numCorrect is returned to the line in which the function was called, in this case Line 12. At this point, the return value contained in numCorrect is assigned to the points variable. So now we return to Line 13. • Line 13: The running total is displayed The updated points value is displayed to the user through the alert() method.

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 Lesson 6: JavaScript Events, Functions and Methods 6-19

• Lines 14 through 19: Repeating the process With the exception of one variation, these lines basically repeat the process outlined in Lines 11 through 13. The difference is in Line 15. Here, the toUpperCase() method is not needed because the answer is an integer. • Line 19: The final score This line is a variation on Lines 13 and 16. Because this line follows the last question, code has been added to indicate that the quiz is over. • Lines 20 through 21: Resetting a variable The numCorrect and points variables are reset to 0 in anticipation of the next quiz. • Lines 22 and 26: Closing the functions It is easy to forget to close a function. Because every function opens with a curly brace, every function must end with one as well. You now have seen another example of functions and how they can be used. You have learned that you can call a function from a user event or from another function. You have also seen another example of an argument passed to a function and a value returned to the calling statement. Methods as Functions

OBJECTIVE In JavaScript, you can use built-in functions to manipulate object properties or to 6.5: Methods as perform calculations. In some programming languages, methods and functions are two functions in JavaScript different operations. In JavaScript, methods are functions that are scoped to an object. Thus, all methods are functions, but not all functions are methods.

JavaScript has built-in functions that are already defined, and it offers developers the ability to define their own functions. You have already seen the syntax required to create user- defined functions. In the following example, the toUpperCase() method works as a function:

var answer; var correctAnswer = "WASHINGTON, D.C."; answer = prompt("What is the capitol of the United States?",""); answer = answer.toUpperCase();

In this code, the end-user might enter "Washington, D.C." in response to the prompt in a quiz, for example. But the correctAnswer variable contains "WASHINGTON, D.C." Because JavaScript is case-sensitive, the user's answer could be read as insufficient simply because the user did not type the answer in capital letters. By using the toUpperCase() method, you can convert the answer to its uppercase equivalent, thus making a useful comparison possible. This function is also a method because the toUpperCase() method belongs to the String object.

Remember that the window object is the default object in JavaScript, thus it is assumed and can be omitted when calling its functions.

Using built-in methods in functions As you have learned, JavaScript has several built-in methods that can make your work easier. These types of functions are referred to as top-level functions. As you learn more about JavaScript, you will use these top-level built-in functions to enhance your scripts.

Some examples you have not yet used that are handy in mathematical calculations include:

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 6-20 Advanced HTML5 and CSS3 Specialist

• isNaN() — short for "is not a number"; used to determine whether an operand is a floating-point calculation number A calculation in • which the decimal parseInt() — short for "parse to integer"; converts a string to its integer equivalent point can move as needed to account • parseFloat() — converts a string to its floating-point decimal equivalent for significant digits. Using the parseInt() or parseFloat() method in your coding will eliminate the problem of the + operator being used for string concatenation when you want it to be used in a mathematical expression. You will see that using either the parseInt() or the parseFloat() method solves the problem of JavaScript misinterpreting the dual-purpose + operator.

The following example demonstrates the use of the parseInt() and parseFloat() methods: NOTE: This section

NOTE: In this example, the string "3 abc" is converted to the integer 3 and the floating-point You can use some number 4.75 is converted to the integer 4 using parseInt(). The string "4.75 abc" is of these ideas in Optional Lab 6-3: converted to the floating-point number 4.75 using parseFloat(). Using a JavaScript conversion function. It is recommended that you specify a radix as the second argument of parseInt. A radix is a parameter that specifies the numeral system to be used. For example, a radix of 16 specifies a hexadecimal numeral system, which parses hexadecimal numbers to decimal. Specifying the radix guarantees predictable behavior. You should be familiar with this term, although further instruction is beyond the scope of this course.

You can cast variables in this situation, which we will discuss next.

Casting variables Recall from the previous lesson that variables can store different data types in JavaScript, including integers, alphanumeric strings and Boolean values. Casting refers to a way of changing a variable from one data type to another. casting In some situations, you need to make the browser interpret variables a different way. For In JavaScript, a technique for example, you may need to convert a string value into a numeric value for the purpose of variable control in calculations, or you may need to convert a numeric value to a string value. You can do which a variable's this with a technique for variable control called casting. Essentially, you cast a variable value is changed from one data type from one type to another. to another. Casting variables can be useful — as well as harmful — to your JavaScript programming. NOTE: When you think of casting variables, consider this: Remember that placing quotation marks around a • 1 + 1 = 2 — mathematical precedence performed on number variables numeral causes JavaScript to treat it • "one" + "one" = "oneone" — concatenation performed on string variables as a string variable instead of number. • "1" + "1" = "11" — concatenation performed on string variables

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 Lesson 6: JavaScript Events, Functions and Methods 6-21

Often, when you report on a variable (for example, when using an alert box), it does not matter whether the variable is actually being cast or not. However, when performing mathematical operations, casting is very important because you need mathematical precedence — rather than concatenation — to occur.

This concept is key in scripts where expressions combine different data types, such as strings and numerics. Study the following example, which is provided in the file Example_casting_error.htm in your student files: OBJECTIVE 6.6: Errors in JavaScript Example: Casting Error

CIW Advanced HTML5 and CSS3 Specialist


When you run this script, you would expect the following output:

The answer is 3

Instead, this result is displayed:

The answer is 12

A casting error is the reason for this result. Following mathematical precedence, the script reads the third expression from left to right. It sees the first portion of this expression ("The answer is") as a string data type, which is correct. So it continues reading from left to right, and it treats the rest of the expression (a + b) as a string as well, because it has not been instructed to do otherwise. Thus it concatenates the values 1 and 2 into 12 as if they were string values, instead of adding the numeric values 1 and 2 to get 3. The final answer (12) seems incorrect, but according to JavaScript, it followed the rules.

You can cast these variables to force their data types in various ways. One way is by rewriting the script to separate the mathematical portion from the string portion in the code, thereby making it easier for JavaScript to follow mathematical precedence rules. Study the following script, which is provided in the file Example_casting_error_fixed.htm.

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 6-22 Advanced HTML5 and CSS3 Specialist

When you run this script, you see the following output:

The answer is 3

This answer is correct, and it is the expected output. Notice that the developer separated the mathematical portion from the string portion in the code to create this expected result. The script now performs the math operation before it arrives at the string concatenation.

Another way to correct this script would be to alter the operator precedence in the expression combining two data types. In this way, you can keep the math and the string concatenation in the same expression, rather than separating them, as in the previous correction. However, you must instruct the script to perform the math before concatenating the result with the string. You can do this by adding parentheses around the math operation. Study the following script, which is provided in the file Example_casting_error_fixed2.htm.

When you run this script, you see the following output:

The answer is 3

This answer is correct, and it is the expected output. But in this case, the developer instructed the script to perform the math operation in the expression first, before concatenating the result with the string. According to mathematical precedence, any operation in parentheses ( ) is performed first. After completing operations in parentheses, the remaining operations are performed left to right. This creates this expected result for this expression.

® CIW Online Resources – Online Exercise Visit CIW Online at http://education.Certification-Partners.com/CIW to complete an interactive exercise that will reinforce what you have learned about this topic. Exercise 6-3: JavaScript variables and built-in methods

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 Lesson 6: JavaScript Events, Functions and Methods 6-23

Errors In JavaScript

OBJECTIVE In relation to a programming, scripting or markup language, a "bug" is an error 6.6: Errors in in the code. There are several types of bugs: JavaScript • Load-time errors — Commonly called compiler or interpreter errors, these are typically syntax errors. Load-time errors usually cause error alerts. • Run-time errors — After the script has loaded and is running, an error occurs. These are typically caused by improper use of commands. Run-time errors usually cause error alerts as well. • Logic errors — These are mathematical errors, casting errors, errors in proper command usage or errors in the structure of the script, which result in the script running improperly. Logic errors do not cause error alerts. The script may return unexpected results or may fail to execute at all.

Common errors in JavaScript No developer writes perfectly clean code all the time. Scripting and programming languages are complex, precise and demanding. Some errors are very common because they are easy to make. When writing or checking JavaScript code, watch for the following:

• Incorrect capitalization — Always remember that JavaScript is case-specific. For example, the built-in JavaScript language objects are named with a capital letter. Referring to an object with improper capitalization will result in an error. The most common error made in JavaScript programming is neglecting to verify and follow proper case-sensitivity. • Inconsistent capitalization — Whether you are declaring variables, defining functions or otherwise using JavaScript, remember to use consistent capitalization. One of the most common causes of errors in variables is failing to apply letter case consistently. Many of your initial scripting errors will come from improper case usage. • Inconsistent spelling — Similarly, built-in JavaScript objects, methods and events have specified names, and so do any objects or variables that you create. You must spell (and capitalize) each name correctly and consistently every time, or your script will not understand your commands. • Language and browser versions — Although JavaScript is no longer version- specific, it does matter which version you are programming for if you want your scripts to work in as many browsers and browser versions as possible. If a user's browser does not support some syntax or version of the code you use, then the browser may return an error. • Inconsistent or incomplete use of braces — Good coding practices can help you check code easily to ensure that you close every set of parentheses or curly braces that you open. Also note that a common syntax error is to forget the curly braces when designating a block of code for execution. • Casting errors — Use caution when defining data types, and keep them consistent throughout your programming. One of the most common errors is when an integer is changed into a character inadvertently. Bear in mind that JavaScript follows mathematical precedence, which means if it does not recognize the entire function as mathematical, it may very well concatenate numbers ( 1 + 1 = 11), commonly resulting in logic errors.

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 6-24 Advanced HTML5 and CSS3 Specialist

If you are encountering errors in your code, first look for misspellings. Next, verify that you are using the proper case for each command. Careless typing in your script can lead to hours of troubleshooting. Get in the habit of checking for misspellings and case- sensitivity before you look for other errors.

Although errors are an expected part of coding, the goal in professional program development is to produce error-free code as quickly as possible. Therefore, if a piece of code has been written, does what you need and is clean, you generally do not want to spend time rewriting that code. For this reason, there are JavaScript code libraries. Code libraries are beyond the scope of this course, but are worth your time to research if you plan to pursue code development.

Steps for debugging JavaScript code NOTE: Code errors can be repaired, once you are aware of them. The steps for debugging Debugging is a very JavaScript code are the same as for other types of code. important skill for developers to acquire. Without The debugging process begins after you have written your script code, placed it in (or solid troubleshooting attached it to) an HTML file, run the file, and discovered that it has some errors. methodologies, your scripts will never run • consistently or Test the code. properly. • Identify the problem. • Review the code manually line-by-line, as well as with a debugging tool. • Locate the error and determine the error type. • Determine the best way to fix the problem. • Correct the code. • Review the code again, watching for other errors introduced by the corrections. • Test your code again ... and again. • Repeat as needed. The debugging process is finished once your code performs as expected when tested repeatedly in a variety of browsers and platforms.

Tools for debugging code It is always wise to review your code manually, but manual reviews do not always catch errors, and with long programs they can be time-consuming. Fortunately, various debugging tools are available to help you detect and locate errors in your code so you can begin the work of fixing them.

It should be clear that debugging tools do not repair code for you. They simply locate and sometimes define errors in the code. However, locating errors helps developers find errors they might otherwise overlook, determine the types of errors they are dealing with, and make the necessary repairs more quickly.

Some browsers offer native (i.e., integrated or built-in) debugging tools, whereas some do not. Browsers that offer native debugging include:

• Microsoft Internet Explorer. • Google Chrome. • Apple Safari. • Mozilla Firefox.

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 Lesson 6: JavaScript Events, Functions and Methods 6-25

Various supplemental debugging tools are available as well, some as browser plug-ins or add-ons, others as stand-alone tools.

Remember that not all add-ons are safe or come from reliable sources. You should be very careful when choosing third-party additions to use in your browsers. Add-ons are capable of introducing security risks.

® CIW Online Resources – Online Exercise Visit CIW Online at http://education.Certification-Partners.com/CIW to complete an interactive exercise that will reinforce what you have learned about this topic. Exercise 6-4: Programming errors

® CIW Online Resources – Course Mastery Visit CIW Online at http://education.Certification-Partners.com/CIW to take the Course Mastery review of this lesson or lesson segment. Course Mastery Lesson 6

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 6-26 Advanced HTML5 and CSS3 Specialist

Case Study Need Coffee to Function Tori owns a small coffee shop with a unique feature: a drive-thru window. Customers love it, but at certain times of the day, the line gets long. Tori knows that sometimes people drive up, see the long line, and leave if they don't have time to wait. Business lost. Nonetheless, she has many dedicated customers, and some she sees almost every day.

Tori has an idea. What if her Web site included a feature that allowed customers to place an order in advance and schedule a pick-up time? If some of the coffee orders are ready for pick-up, then the drive-thru can move faster, reducing the wait and shortening the line. She could even start accounts for her regular customers to pre-pay their coffee, speeding the drive-thru even more.

Tori calls her Web site developer, Sampson, and tells him about her idea. Brilliant, Sampson says. Can we do it? Tori asks.

Sampson suggests adding an Order page to the site. When users access this page, they'll see information about the pre-order service and a form to open a charge account for faster service. For users who open an account, there will be another feature called Express Pre-Order — because, as Sampson points out, these customers want fast service, so why not make the order process faster too?

The Express Pre-Order feature will launch a pop-up alert box on the home page each time an express customer visits the site. The pop-up will greet the customer and ask for his or her coffee order. The customer will enter his or her order and the desired pick-up time in the alert box. When the customer clicks OK, another pop-up window will appear, which recaps the order and pick-up time, and advises the customer of the charge that will be applied to his or her account.

How about that? Sampson asks. Brilliant, Tori says. She can have the coffee orders ready as scheduled and paid for — and customers can pick up quickly and be on their way.

* * *

Consider this scenario and answer the following questions:

• How can Sampson use JavaScript functions to create the Express Pay feature on the Web site? Which functions could he use?

• Which events and event handlers can Sampson use in the Express Pay feature?

• Which methods can Sampson use in the Express Pay feature?

• How might Sampson need to change the script to offer customers a list of check box or radio button choices for their coffee orders, instead of a text field in which they type any order they want?

• What other functionality could Sampson add to the Express Pre-Order feature using JavaScript functions, methods and events? Could he personalize the greeting to each user? Could he offer each customer a personalized option called "The Usual" as an order choice? What JavaScript commands would he use for this? Remember that he wants to keep the Express Pre-Pay feature as quick and easy to use as possible.

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 Lesson 6: JavaScript Events, Functions and Methods 6-27

Lesson Summary

Application project

This project will challenge you to use what you have learned in this lesson. Create an HTML5 page with a JavaScript block in the section of the document and another JavaScript block in the section. In the first JavaScript block, create four functions named add(), subtract(), multiply() and divide(). Define two arguments for each function, arg1 and arg2, in the parentheses following the function name. Define one line of code in each function, a return statement that returns the result of adding, subtracting, multiplying or dividing arg1 with arg2.

In the second JavaScript block, create four document.write() statements that invoke each function. Pass two literal values as the arguments for each function. The result of the functions should be displayed on the HTML page.

Skills review A powerful feature of JavaScript is the fact that developers can create their own functions. A function is an organized, named block of code that handles actions generated by user events. Assigning a name to a block of code allows it to be called repeatedly as needed throughout a program. JavaScript functions can receive arguments and return values. JavaScript also provides built-in functions that perform tasks. Calling a function can be performed from one function to another, from a user event, or from a separate script block. A variable declared within a function with the var keyword is known as a local variable, and you cannot access its value from any other function except the one in which it was declared. Global variables are declared outside of any function definition, and are available to all functions and script blocks on the page. JavaScript contains predetermined event handlers that process user-generated events. Most objects in JavaScript have events and event handlers associated with them.

Now that you have completed this lesson, you should be able to:

 6.1: Define user events, and identify and use JavaScript event handlers.  6.2: Describe the role of functions in JavaScript development.  6.3: Use JavaScript code to define functions.  6.4: Use JavaScript code to call functions.  6.5: Use methods as functions in JavaScript code.  6.6: Identify common errors in JavaScript.

® CIW Practice Exams Visit CIW Online at http://education.Certification-Partners.com/CIW to take the Practice Exams assessment covering the objectives in this lesson. Objective 6.01 Review Objective 6.04 Review Objective 6.02 Review Objective 6.05 Review Objective 6.03 Review Objective 6.06 Review

Note that some objectives may be only partially covered in this lesson.

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 6-28 Advanced HTML5 and CSS3 Specialist

Lesson 6 Review

1. What is a user event? Name at least three examples of JavaScript user events.

2. What is an event handler? Name at least three examples of JavaScript event handlers.

3. In JavaScript, what is the relationship between a function and a method?

4. What is a built-in function? Name at least one built-in JavaScript function.

5. How can you define a function in JavaScript?

6. Explain good coding practice and when it is required in JavaScript.

7. When passing arguments in JavaScript, what must you include with a string literal that is not required for numeric literals?

8. In JavaScript, how many arguments can you pass into a function, and how long does each argument exist?

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 Lesson 6: JavaScript Events, Functions and Methods 6-29

9. What is operator precedence? Give at least one example that relates to JavaScript.

10. How do global variables differ from local variables?

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0 6-30 Advanced HTML5 and CSS3 Specialist

© 2014 Certification Partners, LLC. — All Rights Reserved. Version 1.0