The following sample code ties a custom JavaScript function nameddisallowInputto the onKeyPressevent handler associated withthedocumentobject: For details on the other objects that supp
Trang 1Keyboard eventsKeyboard-related events occur when a user presses a key while a Web page
is loaded In addition to capturing the overall keyPressevent, you can separately capture (and respond to) the user’s pressing the key and thenreleasing the key
The following sample code ties a custom JavaScript function nameddisallowInput()to the onKeyPressevent handler associated withthedocumentobject:
<BODY onKeyPress=”disallowInput();”>
For details on the other objects that support keyboard events, check outTable 13-5
Table 13-5 Keyboard-Related Event Handlers
Event Supporting Objects Event (Event Handler Handler Triggered When )
onKeyDown Button, Checkbox, document, The user presses a key
FileUpload, Image, Link, Password, Radio, Reset, Select, Submit, Text, Textarea
onKeyPress Button, Checkbox, document, The user presses and
FileUpload, Image, Link, releases a key (which Password, Radio, Reset, Select, combines the onKeyDownSubmit, Text, Textarea and onKeyUpevent
handlers)
onKeyUp Button, Checkbox, document, The user releases a
FileUpload, Image, Link, previously pressed key
Password, Radio, Reset, Select, Submit, Text, Textarea
247
Chapter 13: Handling User-Initiated Events
Using window events for good, not evil
Some folks think pop-up ads are inherently evil,and some think they’re a legitimate use of Webtechnology Wherever you fall in the debate, beaware that pop-up-killer software exists, which
some surfers download and install to avoidseeing pop-up ads Know, too, that many surfersrefuse to revisit sites which bombard them withpop-up ads
Trang 3Chapter 14
Handling Runtime Errors
In This Chapter
Getting familiar with runtime errors and exceptions
Taking a peek at the try, catch, and throw statements
Support for exception handling — a technique for anticipating and
recov-ering gracefully from errors that has long been supported in languageslike C++ — was finally implemented for JavaScript in Internet Explorer 5.xand Navigator 6.x
Exceptional Basics
Technically, an exception is any unexpected condition, good or bad, thatoccurs during the processing of a script Practically speaking, however, anexception is virtually always an error Exceptions can result from
A JavaScript error
An unanticipated user-input error
A problem with a user’s browser, operating system, or hardware configuration
Trying to make your code access objects (such as array elements, properties,files, and so on) that don’t exist is a common source of exceptions that mightoccur while your JavaScript code is executing in someone’s browser
If you’re creating a commercial JavaScript application, you want to make eral use of JavaScript’s exception-handling abilities Allowing your users toview cryptic, system-generated errors such as File Not Foundor No SuchObjectis unacceptable in a commercial environment Although anticipating
Trang 4lib-the errors from occurring, it does give you lib-the opportunity to
Reassure users You can use JavaScript’s exception-handling functions
to display a message telling users that an error has occurred but is beinghandled appropriately (This approach is much better than allowing acryptic system message or blank screen to confuse and alarm users.)
Provide users with helpful, appropriate suggestions You can explain
the cause of the error and provide users with tips for avoiding that error
in the future
Handling Exceptions
You handle exceptions by creating two special JavaScript functions, or blocks:
a tryblock and a catchblock Then, in any statement that might generate
an error, you use the keyword throwto throw an error to the catchblock.The code in Listing 14-1 shows you how
Look for the code in Listing 14-1 in the file list1401.htmon the ion CD
compan-Listing 14-1: Handling Exceptions with try-catchand throw
.
<SCRIPT LANGUAGE=”JavaScript” TYPE=”text/javascript”>
function getMonthName (monthNumber) { // JavaScript arrays begin with 0, not 1, so // subtract 1.
monthNumber = monthNumber - 1 // Create an array and fill it with 12 values var months = new Array(“Jan”,”Feb”,”Mar”,”Apr”,”May”,”Jun”,”Jul”,
“Aug”,”Sep”,”Oct”,”Nov”,”Dec”) // If the monthNumber passed in is somewhere
// between 0 and 11, fine; return the corresponding // month name.
if (months[monthNumber] != null) { return months[monthNumber]
} // Otherwise, an exception occurred, so throw // an exception.
Trang 5else { // This statement throws an error // directly to the catch block.
throw “InvalidMonthNumber”
} } //////////////////////////////////////////////////////
// The try block wraps around the main JavaScript // processing code Any JavaScript statement inside // the try block that generates an exception will // automatically throw that exception to the // exception handling code in the catch block.
alert(getMonthName(13)) alert(“We never get here if an exception is thrown.”) }
// The catch block catch (error) { alert(“An “ + error + “ exception was encountered Please contact the
program vendor.”) // In a real-life situation, you might want // to include error-handling code here that // examines the exception and gives users specific // information (or even tries to fix the problem, // if possible.)
}Take a look at Figure 14-1 to see the error that running the code in Listing 14-1generates in Internet Explorer
Trang 6alert(getMonthName(13))Because only 12 months are defined in the monthsarray, passing a value
of13to getMonthName()causes an exception (“InvalidMonthNumber”)
to be thrown, as shown here:
function getMonthName(monthNumber) {
throw “InvalidMonthNumber”
All thrown exceptions are processed automatically by whatever code exists
in the catchblock, so the message that you see in Figure 14-1 (and defined inthe catch block code shown in Listing 14-1) appears automatically when theexception is thrown
If you want to write truly airtight JavaScript code, you need to identify all theevents that could possibly cause an exception in your particular script (such
as actions the user could take, error conditions the operating system couldgenerate, and so on), and implement a try-catchblock for each
Depending on your application, you might want to include more processingcode in the catchblock than the simple pop-up message shown in Figure 14-1.For example, you might want to include JavaScript statements that examinethe caught exception, determine what kind of exception it is, and process itappropriately
You aren’t limited to a string literal when it comes to identifying a thrownexception Instead of InvalidMonthNumber, you can create and throw anelaborate custom exception object (by using the functionand newopera-tors that I describe in Chapter 3)
For more information on how Netscape implements exception handling(including examples), visit
http://developer.netscape.com/docs/manuals/js/core/jsguide/stmtsov.htm#1011537
To see how Microsoft does the same for Internet Explorer, check out this page:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/jscript7/html/jsstmtrycatch.asp
Trang 7Part V
The Part of Tens
Trang 8In this part
Part V begins with a list of some great JavaScript-relatedWeb sites that are full of useful information about allaspects of JavaScript If you feel the need to communicatewith real people about your JavaScript scripts, Chapter 15even provides you with a list of some user groups thatenable you to do just that
These online resources are followed by a chapter ing the most common mistakes that people run into whenimplementing Web pages (along with tips on how to avoidthem) And finally, no programming book worth its saltwould be complete without at least a few handy debuggingtechniques Chapter 17 provides you with lots of bug-relatedtips that make debugging at least entirely bearable, if notdownright pleasant!
Trang 9explain-Chapter 15
Top Ten (Or So) Online JavaScript Resources
In This Chapter
Finding and using JavaScript tutorials
Finding cool JavaScript examples online
Taking advantage of the essential JavaScript-related newsgroups
Getting help on how to do something has never been easier than it isright now Why? The Internet, of course! From its roots in governmentand university installations, the Internet remained a close-knit, mostly acade-mic community until as recently as a decade ago Inevitably, commercialismreared its ugly head and has had a tremendous effect — and not all bad,either — on all things Net (For example, the commercialism of the Internet
is directly responsible for the proliferation of Web tools and languages such
as JavaScript.)
Although marketing and advertising have become common on the Internet,the spirit of sharing and intellectual collaboration hasn’t yet been snuffedout Helping other people (and maybe showing off a little in the process)
is a fundamental joy And because access to the Internet is relatively cheapand easy, everybody and their dog indulges — as you see when you visit theURLs and newsgroups that I list in this chapter
Ten Web Sites to Check Out
With no further ado, then, on to the good stuff: a list of irresistible related Web resources You find tips, tricks, tutorials, examples, and up-to-the-minute documentation The site’s URL follows a description of the goodiesoffered
Trang 10JavaScript-NetscapeThe Netscape DevEdge site contains a wealth of information on getting startedwith JavaScript, including a complete language reference, how-to articles, andsample code It also offers a downloadable JavaScript debugger.
http://devedge.netscape.com
MicrosoftMicrosoft maintains an information-packed site devoted to its JavaScript-compatible language, JScript Documentation, tutorials, sample code, andaccess to JScript-related newsgroups are just some of the great resourcesthat you find here
http://msdn.microsoft.com/scripting/jscript/default.htm
Builder.comThe JavaScript section at CNET Builder.com features tips and tutorials inaddition to copy-and-paste JavaScript code
http://builder.com.com/1200-31-5084860.html
WebmonkeyWebmonkey maintains a killer JavaScript code library containing not just awealth of scripts but a handy browser reference chart, cheat sheets on HTMLand CSS, and more — all free for the taking
http://hotwired.lycos.com/webmonkey/reference/javascript_code_library
Project Cool’s JavaScript QuickStartsProject Cool’s JavaScript QuickStarts offer hands-on JavaScript (and DHTML)tutorials From basic to advanced, all are organized into neat, bite-sized chunksperfect for beginning JavaScript programmers
www.devx.com/projectcool
Trang 11EarthWeb.comThe EarthWeb.com JavaScript site offers a huge repository of cut-and-pastescripts — scripts for everything from navigation to multimedia.
http://webdeveloper.earthweb.com/webjs
About.comThe Focus on JavaScript Web page at About.com contains articles, tutorials,and downloadable scripts on every conceivable JavaScript-related topic —including my personal favorite, troubleshooting
http://javascript.about.com/compute/javascript
IRT.orgInternet Related Technologies’ JavaScript section offers an exhaustive knowl-edge base of frequently asked (and answered) script-related questions
to commercial sites You can cut and paste
embedded JavaScript source code from any site,
with or without that Webmaster’s permission,simply by clicking View➪Source (from Internet
Explorer) or View➪Page Source (Navigator)
(This is one reason why password protection andother highly sensitive features aren’t typicallyimplemented in JavaScript!)
One caveat: If you run across source that
includes a copyright notice, contact the author
or Webmaster and ask for permission beforeusing it If in doubt, don’t copy a file line for line;
instead, take a look at how the programmersolved the problem and base your solution onthe overall approach
Trang 12WebReference.comWebReference.com’s homegrown JavaScript resource list contains links toonline JavaScript magazines, script archives, and much more.
www.webreference.com/programming/javascript/index.html
ScriptSearch.comScriptSearch.com maintains a giant database of JavaScript scripts, from adbanners to visual effects
http://scriptsearch.internet.com/JavaScript/
Not-to-Be-Missed Newsgroups
The Web sites listed in the preceding sections are a great source of information.Sometimes, though, you just have to send a message to a real live person andask a point-blank question Newsgroups can be a great timesaver, especiallywhen it comes to researching specific how-to’s and known bugs
To access newsgroups, you need to have a news server defined Generally,you set up both a Web server and a news server as part of the browser instal-lation and configuration process, but you can always add news support later
To participate in a user group, by viewing other peoples’ messages or byposting your own, you need to switch from surfing the Web to perusing thenews To do this, choose Window➪Mail & Newsgroups from the Navigatormenu or Tools➪Mail and News➪Read News if you’re an Internet Explorer fan
For detailed instructions on configuring your browser software to access groups, check with your browser provider (in other words, contact technicalsupport at Microsoft or Netscape) or check out a good book on the topic, such
news-as The Internet For Dummies, 9th Edition, by John R Levine, Carol Baroudi, andMargaret Levine Young (Wiley Publishing, Inc.)
Collectively, newsgroups are known as Usenet For more information aboutnewsgroups — including where to find news, how to write effective posts,and even how to create your own — visit
http://groups.google.com
Trang 13Although user groups come and go, the following have established selves as the best places to be for JavaScript-related development:
them- If you follow only one user group, make it the following one This group
is very well attended and is currently the premier JavaScript informationgroup for newbies and advanced scripters alike:
comp.lang.javascript(The it.comp.lang.javascriptand de.comp.lang.javascriptnewsgroups are high-traffic Italian- and German-language versions.)
Get answers to HTML questions answered here:
Trang 15Chapter 16
Ten (Or So) Most Common JavaScript Mistakes (And How to Avoid Them)
In This Chapter
Catching typographical errors
Fixing unmatched pairs
Putting scripting statements between HTML tags
Nesting quotes incorrectly
Treating numbers as strings
Treating strings as numbers
Finding logic errors
Every JavaScript author makes mistakes (Actually, I like to think of it inthe reverse — it’s the JavaScript interpreter that makes the mistakes bynot figuring out what the programmer means by something Yeah! That’s it!)Most of the time, the errors you make fall into one of the categories listed inthis chapter The good news is that the errors are all easy to correct Thebetter news is that the JavaScript interpreter tells you quickly — and in nouncertain terms — when it encounters an error
Check out this book’s companion CD to see the sample listings scatteredthroughout this chapter I’ve named the files after the listings so you can findthem easily For example, you can find Listing 16-1 in the file list1601.htm
Trang 16Typing-in-a-Hurry Errors
Spelling and capitalization errors easily take first prize for being the mostcommon mistakes that all JavaScripters make, from the greenest beginner
to the most highly seasoned veteran
The JavaScript interpreter is a stickler for correct spelling: You simply can’taccess an object, property, method, variable, or function unless you spell itsname properly For example, the second line of the following bit of code gen-erates an error:
var identification = “ABC”;
alert(“The id number is “ + identificatoin);
The JavaScript interpreter is also case-sensitive, which means you can’t tute uppercase letters for lowercase letters in object, property, method, vari-able, and function names The following example generates an error becausethe correct name of the method is toLowerCase()(not TOLOWERCASE()):
substi-alert(“Broadcast network ID = “
+ identification.TOLOWERCASE());
To detect and correct these errors:
Be aware, as you write your JavaScript code, that consistency in spellingand capitalization is essential to bug-free statements
Take advantage of any spell-checking utilities or point-and-click methodname insertion utilities that your text editor provides
In this case, the JavaScript interpreter doesn’t display an error message because the error doesn’t
concern it What does happen is that your buttonelement fails to display properly
If your page doesn’t behave as expected and JavaScript doesn’t alert you, you’re probably ing with an HTML error If this happens (and you can’t find the solution in this chapter), check out
deal-a good HTML reference such deal-as HTML For Dummies, 4th Edition, by Ed Tittel deal-and Ndeal-atdeal-anydeal-a Pitts
(Wiley Publishing, Inc.)
Trang 17Breaking Up a Happy Pair
JavaScript scripts are typically rife with pairs: pairs of opening and closingtags (courtesy of HTML), pairs of parentheses and curly braces, pairs ofsingle quotes and double quotes The JavaScript interpreter treats the stuffbetween the pairs as one entity, so if half of the pair is missing, the inter-preter gets confused — mighty confused, in some cases!
The following are specific examples of happy couples that you don’t want tobreak up in JavaScript
Lonely angle bracketsLooking at the following code, you’d think that the display would include twotext elements: one to hold a first name and one to hold a last name It doesn’t,though, because a closing angle bracket is missing
<FORM NAME=”myForm”>
First name: <INPUT TYPE=”text” NAME=”firstName” LENGTH=15
Last name: <INPUT TYPE=”text” NAME=”lastName” LENGTH=30>
.
If a text element doesn’t appear — no error message, no nothing, just blankspace where the element should have appeared — the likely suspect is amissing angle bracket on the line directly before the invisible text element
Lonely tagsThe code that you see in Listing 16-1 depicts a tiny little script, perhaps a firstattempt at a JavaScript-enabled Web page At first blush, perhaps you don’tsee anything amiss If you were to load this script, though, you’d see thatsomething is definitely amiss!
Listing 16-1: HTML Source Containing a Missing Tag
<HEAD>
<SCRIPT LANGUAGE=”JavaScript”>
function test() { var aString = “some text”
(continued)
263
Chapter 16: Ten (Or So) Most Common JavaScript Mistakes
Trang 18alert(“aString is “ + aString) }
//The closing </SCRIPT> tag that should be here is missing.
First name: <INPUT TYPE=”text” NAME=”firstName” LENGTH=15>
Last name: <INPUT TYPE=”text” NAME=”lastName” LENGTH=30>
Whenever elements refuse to appear, check your HTML statements to seewhether an opening half of a two-part tag, such as <TITLE>, <SCRIPT>, or
<BODY>, is missing its closing half (</TITLE>, </SCRIPT>, and </BODY>,respectively)
Lonely parenthesesWhen you look closely at the body of the following test()function, you caneasily spot the missing parenthesis on line three:
function test() {
var aString = “some text”
alert(“aString is “ + aString }
As your JavaScript skills increase, though, you might find yourself puttingtogether whopping long statements Furthermore, each of the whopping longstatements might contain many pairs of parentheses, often nested a few layersdeep — and that’s when you’re most likely to make this kind of mistake
Unless the editor that you use to create your script provides an automaticparentheses-pair-checking utility, you need to eyeball your code to catch andcorrect this mistake
Trang 19Lonely quotesTake a good look at the following example:
<INPUT TYPE=”button” NAME=”testButton” VALUE=”test”
onClick=’test(“hello)’>
The mistake here is that no closing double quote appears after the wordhello The preceding code doesn’t generate an error; it just disables thetestButtonobject’s onClickevent handler
Here’s how the corrected statement looks:
<INPUT TYPE=”button” NAME=”testButton” VALUE=”test”
onClick=’test(“hello”)’>
Putting Scripting Statements
in the Wrong Places
When you’re new to JavaScript, remembering the order of things might be alittle difficult For example, JavaScript statements are valid only when they’replaced between the <SCRIPT>and </SCRIPT>tags or as values assigned toevent handlers If you forget and place them somewhere else, you’re bound toget an unexpected result
The good news is that you find out as soon as you load your page and take
a look at it that something is amiss — because your source code appearsright there on the page! Check out the source shown in Listing 16-2 to seewhat I mean
Listing 16-2: HTML Source Containing Misplaced Scripting Statements
<SCRIPT LANGUAGE=”JavaScript” TYPE=”text/javascript”>
function test(inputValue) {
alert(“Wow, I sure do love JavaScript!” +
“\nHere’s what the public is saying about JavaScript: “ + inputValue)
}
</SCRIPT>
// The addNumbers() function is incorrectly defined
// below the closing </SCRIPT> tag.
(continued)
265
Chapter 16: Ten (Or So) Most Common JavaScript Mistakes