Within the updateStatusfunction, create a new variable called trgt, and add an if/else block to test the event model type for Internet Explorer compatibility, using the statement if win
Trang 1Lab 8:
Event Handling
TIP: Because this lab includes a great deal of typed code, we‘ve tried to make it
simpler for you You will find all the code in SpreadSheet.html, SpreadSheet.js, and SpreadSheet.css, in the same directory as the sample
project To avoid typing the code, you can cut/paste it from the source files instead
Trang 2information given in the Objective section If you require more information to complete the exercise, the Objective section is followed by detailed step-by-step instructions
Trang 3 The status bar is accessed using window.status
Remember Internet Explorer and W3C compliant browsers handle event objects differently!
Unless it is helpful to what you are scripting outside of this class, do not worry about Netscape 4 for this exercise
Step-by-Step Instructions
1 Open SpreadSheet.js in your editor Look over the code briefly to get an
idea of what is going on First, you will create a function to initialize the
event listeners Right under the global variables, abc and formname, create a function called initEvents() You will want to use the formname
to create a reference to the form using the eval method, with the statement
var elemnt = eval(“document.” + formname); On the next line, define
the event handler, using the statement elemnt.onmouseover =
updateStatus;
Trang 4Mouse Interception
var abc = "abcdefghijklmnopqrstuvwxyz";
var formname = "ssform";
function initEvents() { var elemnt = eval("document." + formname);
elemnt.onmouseover = updateStatus;
}
2 For Netscape 6 and W3C compliant browsers, you should add an if
statement with the condition (elemnt.addEventListener) This is known
as object detection Basically if the if elemnt has the method
addEventListener, then this is a W3C DOM, like Mozilla 1+ On the first statement in the if block add the mouseover event listener:
element.addEventListener(“mouseover”, updateStatus, true); Finally,
add one last statement to the if block, elemnt.onmouseover = null;, to
guarantee that the new event listener you created will function in Netscape 6+ browsers (as well as in Opera)
function initEvents() { var elemnt = eval("document." + formname);
elemnt.onmouseover = updateStatus;
if (elemnt.addEventListener) { elemnt.addEventListener("mouseover", updateStatus, true);
elemnt.onmouseover = null;
}
3 Create a nested function inside of initEvents() called updateStatus(evnt)
You will recall from the chapter that, for browsers that implement the W3C object model, your event handling functions must include a parameter that represents the event the function will catch Within the
updateStatus()function, create a new variable called trgt, and add an if/else
block to test the event model type for Internet Explorer compatibility,
using the statement if (window.event)
Trang 5if (elemnt.addEventListener) { elemnt.addEventListener("mouseover", updateStatus, true);
elemnt.addEventListener("click", setTitle, true); elemnt.onmouseover = null;
elemnt.onclick = null;
}
function updateStatus(evnt) { var trgt;
if(window.event) { } else {
} }
4 Within the if block, assign window.event to the evnt variable to make sure
evnt is defined properly if the client browser is Internet Explorer On the
next line, set trgt to reference the event‘s target, using the statement trgt =
evnt.srcElement; If the client‘s browser is not Internet Explorer, then the
else block will execute, and trgt should be set to reference evnt.target
function updateStatus(evnt) { var trgt;
5 Create an if block with the condition trgt.type == “text” &&
trgt.name.match(/cell/g)) This ensures that you are in a textfield within
the spreadsheet, which has ―cell‖ within the name
Trang 6Mouse Interception
function updateStatus(evnt) { var trgt;
if(window.event) { evnt = window.event;
trgt = evnt.srcElement;
} else { trgt = evnt.target;
}
if (trgt.type == "text" &&
trgt.name.match(/cell/g)) { }
}
6 Finally, inside of the if /else statement, populate the status bar with the
target‘s name using the statement window.status = trgt.name;
if (trgt.type == "text" &&
trgt.name.match(/cell/g)) {
window.status = trgt.name;
} }
7 Test the application by running SpreadSheet.html in your browser When
you mouseover a cell, its name should appear in the status bar, as shown in Figure 7
Trang 7Figure 7 Cell 1_1 shows in the status bar in Mozilla
Trang 8Title Cell Info
Title Cell Info
Objective
In this exercise, you will make the title show the information provided in the cell on the window title area Capturing the onclick event, the title will be adjusted to inform the user of the page they are on, and the current cell‘s information
Things to Consider
With text, password, and textarea objects, the onclick event bubbles up through the document hierarchy, or captures downwards through the hierarchy However, onBlur and onChange only fire at the object level
Prior to Internet Explorer 4 and Netscape Navigator 6, you can only read the document title
The cell‘s onclick event will still fire, even when you catch it higher
up in the document
You will need to use a provided method, getNumAlpha(cell column number) to determine what letter(s) the current column is (A – ZZZZ and beyond)
Step-by-Step Instructions
1 This exercise builds on the functionality of the previous exercise While the contents of updateStatus are similar to the function needed for this exercise, to reduce confusion, updateStatus will be copied to a new function called setTitle Remove the line that sets the window.status
function setTitle(evnt) { var trgt;
if(window.event) { evnt = window.event;
trgt = evnt.srcElement;
} else { trgt = evnt.target;
}
Trang 9if (trgt.type == "text" &&
trgt.name.match(/cell/g)) { window.status = trgt.name;
} }
2 Inside of the second if/else block, the one that checks for the cell type and
name, start a new string: var strTitle = “SpreadSheet: ” and then
separate the properties located in the target cell‘s name, using the
statement var id = trgt.name.substring(4, (trgt.name.length));
if (trgt.type == "text" &&
trgt.name.match(/cell/g)) {
var strTitle = "SpreadSheet: ";
var id = trgt.name.substring(4, (trgt.name.length));
}
3 Redefine your code so that the variable id refers to an array of cell
information by splitting itself into its component elements, using the
statement id = id.split(“_”); This places the column number in id[0] and
the row number in id[1]
if (trgt.type == "text" &&
trgt.name.match(/cell/g)) { var strTitle = "SpreadSheet: ";
var id = trgt.name.substring(4, (trgt.name.length));
id = id.split("_");
}
4 Append cell information onto the strTitle with the statement strTitle += “
Current Cell: ” + getNumAlpha(id[0]) + id[1]; The function getNumAlpha() returns the column letter equivalent of the column
number you pass in
Trang 10Title Cell Info
if (trgt.type == "text" &&
trgt.name.match(/cell/g)) { var strTitle = "SpreadSheet: ";
var id = trgt.name.substring(4, (trgt.name.length));
id = id.split("_");
strTitle += " Current Cell: " + getNumAlpha(id[0]) + id[1];
}
5 Add an if statement to the block with the condition (trgt.value) For the
first statement in the new if block, add the value of the cell to the title
string: strTitle += “ – Value: ” + trgt.value;
id = id.split("_");
strTitle += " Current Cell: " + getNumAlpha(id[0]) + id[1];
if(trgt.value) { strTitle += " Value: " + trgt.value; }
6 At the end of the if block, add another if statement with the condition
(trgt.formula), then for the first line in that block add the formula
information to the title: strTitle += “ – Formula: (” + trgt.formula +
“)”;
if(trgt.value) { strTitle += " Value: " + trgt.value; }
if(trgt.formula) { strTitle += " Formula: (" + trgt.formula + ")";
}
7 Finally, add a line immediately following the if block to change the window title to reflect the new title string, using the statement
document.title = strTitle;
Trang 11if(trgt.formula) { strTitle += " Formula: (" + trgt.formula + ")";
}
document.title = strTitle;
8 Now that the title function is complete, you must register the events so that
they can execute Proceed to the top of the initEvents() function, and add
a new elemnt.onclick definition under the elemnt.onmouseover line, which was defined in the first exercise, that points to the setTitle()
function
elemnt.onmouseover = updateStatus;
elemnt.onclick = setTitle;
9 Two additional lines must be added to the if statement on the next line
First, for W3C browsers, add an elemnt.addEventListener() for the
“click” action, passing in setTitle, and true as parameters On the next
line, set elemnt.onclick to null, since the listener is already defined
elemnt.onclick = setTitle;
if (elemnt.addEventListener) { elemnt.addEventListener("mouseover", updateStatus, true);
elemnt.onmouseover = null;
elemnt.addEventListener("click", setTitle, true); elemnt.onclick = null;
}
NOTE Steps 8 and 9 have already been added to the completed lab file
However, they have been commented out so that first exercise can
be viewed To launch this exercise, be sure to uncomment the lines described above
Trang 12Title Cell Info
10 Now it is time to test the application When you mouseover a cell, its name will appear in the status bar like before However, if you click on a cell, the title information will be displayed in the title bar of the window, as shown in Figure 8
Figure 8 Mouse clicked on cell C1, with the formula in the Mozilla browser
Trang 14Error Handling
Error Handling
Objectives
Read error messages effectively
Investigate problems with your scripts
Learn about exception handling
Learn to create try…catch blocks
Create your own custom Error objects
Discover a free JavaScript debugger
Learn how to effectively test your scripts
Trang 15Reading Error Messages
Even the best programmers and scripters make mistakes in their code What separates them from mediocre developers is the ability to effectively test and debug their work The first step to fixing an error in your script is, of course, being aware of the error At first, this might seem like a fairly simple thing to
do, but it is actually far more complex than it seems
Most modern browsers do their best to suppress obvious error notification, which makes it difficult to find scripting errors The early scriptable browsers displayed an obvious error dialog box, but this proved too disruptive for users, especially nontechnical users who often thought that they were to blame for breaking the page Suppressing these dialog boxes in later browser versions has been good for users, but makes it far too easy for scripters to overlook errors in their code
Displaying Errors
Each of the major browsers has a different way of displaying errors to the user
In Internet Explorer 5+, error notifications are displayed in the browser window‟s status bar Figure 1 shows an example
Figure 1 Internet Explorer notifies the user of script errors in the left edge of the status bar
If you double-click on the icon in the status bar, the error dialog box appears Click on the Show Details button to see useful details about the error,
including the line number within your script file on which the error occurred Figure 2 shows the Internet Explorer error dialog box, expanded to show details
Trang 16Reading Error Messages
Figure 2 The Internet Explorer error dialog box
It is advisable to click the check box labeled “Always display this message when a page contains errors” and leave it checked This choice displays the Internet Explorer error dialog box every time the browser encounters an error
in your scripts, so that you don‟t have to monitor the status bar continually
You can also enable this option by going to Tools|Internet Options|
Advanced|Browsing and checking the check box labeled “Display a
notification about every script error.”
To view errors in a Netscape-based browser, open the JavaScript console by
selecting Tools|Web Development|JavaScript Console from the main menu
This displays a detailed list of all of the errors within a script Figure 3 shows the JavaScript console, which lists several errors that it found in a script
Figure 3 The JavaScript console displays a detailed list of all script errors
Trang 17You can leave the JavaScript console open as you test your pages, and subsequent error messages will be appended to the list
TIP: If you leave the Netscape Navigator JavaScript console open as you test, be
sure to clear it before each test Otherwise, you may confuse old error messages that you have already fixed with current errors
When tackling issues listed in the JavaScript console, you should always start
by addressing the first error in the list Errors appear in the list in the order that they occurred, and quite often errors that appear later in the list were caused by the earlier errors If you test your script after fixing the first error, you may be pleasantly surprised to find that the fix also addresses many subsequent errors
Investigating Problems
The exact information within error messages differs depending on which browser you are using, but generally the messages include three pieces of information: the name of the file in which the error occurred, the location of the error within that file, and a description of the error Using these bits of information, you should be able to track down most errors in your source code Before you try to track down an error, you should be aware of a difference in how the major browsers report the name of the offending file When an error occurs in a script that is embedded within an HTML page, both Internet Explorer and Netscape Navigator properly list the name of that HTML page in their error messages However, if the error occurs in a separate js file that an HTML page references, the filename reported in the error message will differ depending on the browser Netscape Navigator‟s error message properly reports that the error occurred in the external js file However, Internet Explorer‟s error message reports that the error occurred in the HTML page that references the js file, which makes it a bit harder to track down the error unless you are aware of this quirk in Internet Explorer
Generally, the error line number in the report reflects the exact line on which a script error occurs However, on some occasions Internet Explorer
misinterprets the context of errors; it can miss closing braces and report the error on a later line than it truly is This usually occurs when the missing brace
is followed by a new function declaration: Internet Explorer thinks that the new function should be nested within the function with the missing brace In addition, if an error arises in a script that was referenced from an HTML event handler, such as onClick, Internet Explorer will commonly report that the script error originated in the line of HTML where the event handler is defined, rather than in the offending line of JavaScript code If you are aware of Internet Explorer‟s error reporting discrepancies, it will help you identify the
Trang 18Reading Error Messages
The details of the error report also differ based upon the browser that loads the page While the detail text is meant to help you understand the nature of the error, the text can be quite cryptic Complete coverage of even the most common error messages and their meanings is beyond the scope of this text due to the number of possible errors and how the different browsers interpret them In time, though, you will become familiar with them
Trang 19Exception Handling
In programming terminology, an exception can be defined as an occurrence that falls outside the range of expected results This is a kind way of saying that something went wrong while your code was running Exception handling involves making provisions in your code to allow for the unexpected
Generally speaking, scripters make little distinction between an exception and
an error—an exception causes a script to deviate from the intended execution
in unexpected ways, typically resulting in an error In discussions of these JavaScript concepts, it is perfectly acceptable to think of errors and exceptions
as the same thing
Whenever an exception is raised, the browser creates an Error object that contains information about the exception The browser uses these Error objects
to provide you with the error messages mentioned in the previous sections The real utility of these Error objects, however, is as a mechanism for handling these exceptions intelligently
Try…Catch…Finally Blocks
One method for handling exceptions is to surround the code with a try catch…finally block, to encapsulate any script statements that may generate a run-time error When you use this mechanism, your scripts can handle any possible exceptions that arise within those statements in a controlled manner and can prevent any resulting errors from appearing in the browser‟s error reporting mechanism The syntax for a try…catch…finally block is as follows:
try { // statements that might generate an error }
catch (errorVariable) { // code that handles any errors that arise }
finally { // statements to execute, regardless of error status }
In the try block, place the statements that you think could potentially raise an