Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning JavaScript With DOM Scripting And Ajax - From Novice To Professional (2006)

.pdf
Скачиваний:
83
Добавлен:
17.08.2013
Размер:
17.27 Mб
Скачать

466

A P P E N D I X D E B U G G I N G J A V A S C R I P T

Opera 8.5

Opera not only comes with options to quickly turn off all kinds of browser support (JavaScript, cookies, plug-ins, pop-ups) by pressing F12, which helps immensely to test whether your web page is dependent on JavaScript or not, it also has a built-in JavaScript console that gives very detailed error reports. You can turn on the console via Tools Advanced JavaScript console as shown in Figure A-7.

Figure A-7. Showing the JavaScript console in Opera

Firefox 1.5.0.3

Firefox stays silent and doesn’t bother the visitor by reporting JavaScript errors. However, it comes with a very powerful JavaScript console, which you can show by selecting Tools JavaScript console on the main toolbar as shown in Figure A-8.

A P P E N D I X D E B U G G I N G J A V A S C R I P T

467

Note Don’t be confused if your Firefox browser doesn’t have the same options as shown in Figure A-8; some of them are dependent on extensions I installed. However, you should have the JavaScript console.

Figure A-8. Showing the JavaScript console in Firefox

Once activated, the JavaScript console is visible in its own browser window, which lists the JavaScript errors that occur in any page you open in any of your Firefox windows or tabs. It is quite amazing to see how many errors accumulate when you surf the Web a bit with the console open. The error in exampleMissingCurly.html would display as shown in Figure A-9.

Figure A-9. The Firefox JavaScript console showing an error

You can either show errors, warnings, and messages, or filter the list for each of them. Clicking the Clear button will wipe the list clean. You can even evaluate any JavaScript by pasting it into the code box and clicking the Evaluate button.

468

A P P E N D I X D E B U G G I N G J A V A S C R I P T

By default, the JavaScript console will open in a new window, but there is a trick you can use to show it in the sidebar instead.

1.Make sure the bookmarks toolbar is visible by selecting View Toolbars Bookmarks Toolbar.

2.Right-click the toolbar and select New Bookmark.

3.Add the information shown in Figure A-10. The location must be chrome://global/ content/console.xul, but you can name the bookmark anything you like.

4.Make sure the Load this bookmark in the sidebar option is activated.

This will add a new bookmark button to the toolbar that opens the JavaScript console in the sidebar when you click it.

Figure A-10. A trick to make Firefox show the JavaScript console in the sidebar

This should get you started in spotting errors quickly in Firefox; however, it is only the tip of the iceberg when it comes to great helpers available for this browser. Mozilla and Firefox can be easily improved with extensions written in JavaScript and an XML-based language called XUL.

A P P E N D I X D E B U G G I N G J A V A S C R I P T

469

Developers keep churning out new extensions and putting them on the Web. Two of those are very handy for you as a JavaScript developer:

The Web Developer Extension

The Web Developer extension is a toolbar by Chris Pederick that is available at http:// www.chrispederick.com/work/webdeveloper/. This toolbar allows you to quickly toggle JavaScript support (which you can do otherwise via Tools Options Content Enable JavaScript), show HTML generated by JavaScript in the Source Viewer, populate forms automatically with data, edit the page’s style sheet on the fly, and choose from many more options. It is a “Swiss Army Knife” for web development.

FireBug

If you thought the JavaScript console of Opera, Safari, and Firefox was handy, get the FireBug extension by Joe Hewitt (who is also responsible for the DOM inspector that is part of the default Firefox installation) at http://www.joehewitt.com/software/firebug/. The FireBug extension is visible in the bottom right of the browser window and either shows a warning icon with the number of errors in the console or a green icon indicating that everything is OK. If there are errors, you can click the icon (or press F12) to open the FireBug console in the bottom half of the browser window as shown in Figure A-11.

Figure A-11. The FireBug extension with open console

The features of FireBug are too many to mention here. Whatever is happening to the document, you can see it in the console. It shows the DOM structure, the applied CSS, the dimensions and properties of elements, events assigned to elements, the return values of Ajax requests, and much, much more. In the DOM inspector mode, you are even able to change the document on the fly to test changes quickly in a remote document. This is for testing purposes only—you cannot save the changes on the remote server, of course.

470

A P P E N D I X D E B U G G I N G J A V A S C R I P T

Venkman

Mozilla’s answer to the Microsoft Script Debugger is called Venkman and is available at https:// addons.mozilla.org/firefox/216/. Venkman is a full debugging suite that allows you to watch variables, set debugging points, and really go down into the depths of JavaScript development. Explaining all the features of Venkman would fill its own chapter, and for day-to-day JavaScript tasks, it may be overkill to use. If you want to know all the features of Venkman and how to use it, check the walkthrough provided on the homepage at http://www.mozilla.org/projects/ venkman/venkman-walkthrough.html. Another good start is the introductory article “Learning Venkman” by Svend Tofte, available at http://www.svendtofte.com/code/learning_venkman/. The newest versions of the aforementioned FireBug extension also include a debugger like Venkman, which makes it obsolete in some way; however, it is worth mentioning as it is in use in some companies.

JSLint and JSUNIT

Some browser-independent tools are available that could also help you with JavaScript development. One is the online JavaScript verifier JSLint by Douglas Crockford, available at http:// www.jslint.com/lint.html. JSLint is a tool written in JavaScript that verifies scripts in terms of syntactical validity and tries to ensure good coding style. As “good coding style” is a subjective matter, you may want to take JSLint reports with a grain of salt. JavaScript development happens mostly in browser environments, and from time to time you need to bend the rules or cut corners to make a script work faster or work around browser issues. That being said, it is still a great tool to find ways to optimize your scripts in terms of cleanliness of code if you don’t have to cut corners. The great thing about JSLint is that it gives you a full analysis of your script, including reports on global variables and how many times different functions have been called.

If you come from a back-end coding environment, you may have already used or at least heard about unit testing (http://en.wikipedia.org/wiki/Unit_testing). In a very small nutshell, unit testing means that you write test cases for all your methods and functions, and a “testing harness” allows you to run all these tests in succession when you press a button. This way you can ensure that your code works as you define the test cases it has to fulfill before you develop the code. For Java, there is JUnit; for PHP, there is PHPUnit; and yes, for JavaScript there is JSUnit, available at http://www.jsunit.net/.

Summary

All in all, debugging JavaScript is much easier these days than it was some years ago, and especially in the Firefox extension world it is very important to keep your eyes open, as new products that you may profit from are released almost weekly. The renaissance of JavaScript as part of the Ajax methodology has also made development IDE vendors a lot more aware of the need for good JavaScript debugging tools. Products that were traditionally meant exclusively for Java or .NET development are beginning to add support for JavaScript that goes beyond color-coding the sources.

Index

Special Characters

#text nodes, 89 $1 variable, 362

$(document).ready ( ) method, 421 $.get( ) method, 425

% operator, 21 && operator, 48 * operator, 21

*/ syntax, JavaScript, 8 /* syntax, JavaScript, 8 // syntax, JavaScript, 8 \\ escape sequence, 20 || operator, 48

+ operator, 21, 23 ++ operator, 21 != operator, 46 == operator, 46 > operator, 46 >= operator, 46

\' escape sequence, 20 / operator, 21

! operator, 49

A

abort( ) method, 321, 445 accessibility, 69–71 accesskey attribute, 179

addEvent( ) method, 166, 190, 325, 330, 433 addEventListener( ) method, 156, 166 addListener( ) method, 441

addMap( ) function, 429 addOverlay( ) method, 432, 436 ADDRESS element, 125

advantages of JavaScript, 5–6 after( ) method, 425

Ajax, back-end interaction with

and caching, 309

connected select boxes, 323–331 optional dynamic Ajax menus, 331–340 overview, 299–309

replacing XML with JSON, 314–316 turning XML into HTML, 309–314

using server-side scripts to reach third-party content, 316–320

XHR on slow connections, 320–322

alert( ) method, 10, 90–95, 101, 121, 308, 452, 456, 458–459

Anim( ) method, 442–443 animate( ) method, 443 animation, 222–230

APIs (application programming interfaces), 4 appendChild( ) method, 312

application/x-www-form-urlencoded content type, 329

appName attribute, 65 appVersion attribute, 65 Array data type, 30 array_slice( ) method, 409 arrays

Array object

converting array to string and back, 43–44

cutting slice of array, 42–43 joining two arrays, 43 overview, 42

sorting array, 44–45

overview, 39–42

471

 

472I N D E X

asynchronously, 300 attachEvent( ) method, 166 attributes of elements

changing, 107–108 reading, 117

B

\b escape sequence, 20 back( ) method, 230, 246 background image, 192

background-position property, 191 before( ) method, 422

behavior layer, JavaScript as

object detection vs. browser dependence, 65–68

overview, 63–65

progressive enhancement, 68–69 block property, 261

blocking software, 238

blur( ) method, 215, 219–220, 238, 276, 278 BODY element, 448

Boolean data type, 18, 45 border property, 185 <br> line breaks, 426 braces, closing, 454–456 brackets (<>), 86

branches, breaking out of, 52 break statement, 52, 58 browser cache settings, 212

browser window, navigation methods of layer ads, 231–238

overview, 230–231 browsers

browser dependence vs. object detection, 65–68

error reporting in Firefox, 466–470

Microsoft Internet Explorer, 6 (MSIE6),

463–464

Opera, 466

overview, 463 Safari, 464–465

vendors, 212 business logic layer, 63 button, 295

button attribute, event object, 157 buttons, radio buttons, 281–284

C

caching, 309 camel notation, 24 camelCase, 72

Campbell, Chris, 364

cancelClick( ) method, 169, 211, 219, 228, 325, 329–330, 372, 393, 395, 404, 413–414

captions, displaying in thumbnail galleries, 396–401

Cascading Style Sheets (CSS), 61, 64 easing maintenance, 139–143 overview, 131

styling dynamic pages, 131–139 support problems

:hover pseudo-class, 148–152

multiple columns with same height, 143–148

overview, 143 thumbnail galleries, 388

case statements, 52 case-sensitivity issues, 451 catch( ) method, 459–462 CDATA commenting syntax, 7 ceil( ) function, Math object, 37

CGI (Common Gateway Interface), 3 chainable methods, 420

character encoding method, 20 charAt(n) method, 346 charCodeAt( ) method, 346, 349 check boxes, 279–281

checked attribute, 273, 279

checked property, 275, 279–281, 283–284, 294 childNodes property, 100

children, 99–100 Clark, Chris, 139 click( ) method, 276

click event, 163, 247, 249, 257, 259, 294 click event handler, 335

client-side validation, pros and cons of, 343–344

close( ) method, 215, 220

closestSibling( ) method, 120, 125, 178, 203, 294

closing braces, incorrect number of, 454–456 CMS (Content Management System), 139 CODE element, 420, 426

code execution, 9–11 code layout, 72–74 code library, 426 coding syntax, 24 cols attribute, 276

columns, multiple with same height, 143–148 commenting, 74–76

complete property, 185 composite data types, 30

concat( ) method, Array object, 43 concatenation, 27, 456–457 concatenation operator, 23 conditional statements, 17

breaking out of branch or loop, 52 overview, 49–52

confirm( ) method, 90–95, 215

console elements, tracing errors with, 458–459

constraintoviewport property, 447 Content-length, 329

continue keyword, 58

converting array to string and back, 43–44 converting different types of data, 26–30 Cross-Site Scripting (XSS), 213

I N D E X 473

CSS. See Cascading Style Sheets

CSS class, 248, 257, 398

cssjs method, 149 curly braces {} syntax, 8

custom attribute, 366–367 custom elements, 297 cutting slice of array, 42–43

D

data comparison, 45–48

data conversion, 26–30

 

data types, 17

 

Date object, 30, 355–356

 

overview, 34

Find

using, 35–37

DDA (Digital Discrimination Act), 6, 62

it

atfaster

debugging

Debug menu option, 464

com.apress.http://superindex

overview, 451

common mistakes

 

assigning instead of testing value of

 

variable, 458

 

concatenation gone wrong, 456–457

 

incorrect number of closing braces and

 

parentheses, 454–456

 

misspellings and case-sensitivity

 

issues, 451

 

trying to access undefined variables,

 

452–454

 

error handling with try and catch( ),

 

459–462

 

error reporting in browsers

 

Firefox, 466–470

 

Microsoft Internet Explorer, 6 (MSIE6),

 

463–464

 

Opera, 466

 

overview, 463

 

Safari, 464–465

 

JSLint and JSUNIT, 470

 

overview, 451

 

474I N D E X

debugging (continued) sequential uncommenting, 462

tracing errors with alert( ) and console elements, 458–459

decision making comparing data, 46–48 conditional statements

breaking out of branch or loop, 52 overview, 49–52

logical operators, 48 loops

continuing, 58–59 for loop, 54–56 overview, 54 while loop, 56–58

overview, 45

switch statement, 52–54 testing multiple values, 52–54

delimiters, 18 Developer Network, 438 DHTML, 5

Diaz, Dustin, 139

Digital Discrimination Act (DDA), 6, 62 dimensions of windows, 221

disabled attribute, 136, 285, 295 disabled property, 138 disadvantages of JavaScript, 5–6 display property, 125, 130 DOCTYPE element, 85–86 document object, 12, 15, 96, 184, 413 Document Object Model. See DOM

Document Type Definition (DTD), 86 document.createElement( ) method, 109, 117

document.createTextNode( ) method, 109, 117

documentElement.scrollTop property, 413 document.getElementById('id') element, 116

document.getElementsByTagName ('tagname') element, 116

document.write( ) method, 15, 41, 89, 96, 174

DOJO toolkit, 340

DOM (Document Object Model), 67, 85 accessing document via, 96–99 creating new nodes, 117

methods, 277

navigating between nodes, 117 overview, 116

reaching elements in document, 116

reading element attributes, node values, and other node data, 117

scripting, 63, 289 DOM-2 event handling, 183

DOMhelp library, 123, 190, 198, 419 do.while loop, 56, 59 drag-and-drop interface, 179

dyn class, 232

dynamic Ajax menus, 331–340 dynamic class, 127, 267 dynamic pages, styling, 131–139 dynamic slide shows, 207–211 dynamic technology syntax, 3

E

each( ) method, 425 Easing utility, 442 Edward, Dean, 345 Eisenberg, David, 367 element node, 100

element.innerHTML node, 117 elements, 39, 297

attributes of, changing, 107–108 creating, removing, and replacing avoiding NOSCRIPT, 113–115

DOM features, 116–117 overview, 109–113

shortening scripts via innerHTML, 115–116

buttons, 284–286 check boxes, 279–281 overview, 275–276

radio buttons, 281–284 select boxes, 286–291

text fields, text areas, hidden and password fields, 278–279

using blur( ) and focus( ), 278

reading element attributes, node values, other node data, 117

elements collection, 276–277, 288 else condition, 281

else statement, 9, 15 <embed> tag, 153

embedded slide shows, 197–207 enctype attribute, 274

error handling, with try and catch( ), 459–462 error reporting, in browsers

Firefox, 466–470

Microsoft Internet Explorer, 463–464

Opera, 466

overview, 463 Safari, 464–465 escape sequence, 19

escape sequences, 19–20 eval( ) method, 188, 315–316 event bubbling, 158

event capturing, 156 event handling

changing document's behavior via

events in W3C-compliant world, 156–165

fixing events for non-W3C-compliant world, 165–172

overview, 153–156

reading and filtering keyboard entries, 174–179

ugly page load problem, 173–174 dangers of, 179–180

event listener, 156 event object, 157 event target, 156 Exception object, 460

I N D E X 475

exec( ) method, 357 explanatory comments, 75

F

\f escape sequence, 20

failed( ) method, 307–308, 313, 320, 330, 336

 

false keyword, 281

 

feedback

 

data validation

 

highlighting erroneous fields

 

individually, 376–379

 

instant validation feedback, 379–380

 

overview, 369

 

replacing main form with clickable error

it Find

message, 374–376

showing list of erroneous fields, 369–374

user feedback methods, 215

faster

 

in web pages, 89–95

at

filtering keyboard entries, 174–179

com.apress.http://superindex

FireBug, 469

 

Firefox, error reporting in

 

FireBug, 469

 

overview, 466–469

 

Venkman, 470

 

Web Developer extension, 469

 

firstChild property, 100

 

flash of unstyled content (FOUC), 173

 

Flash Satay, 153

 

Flickr, 417

 

Flickr badges, 406

 

floor( ) function, Math object, 37

 

focus( ) method, 215, 219, 238, 276, 278

 

focus event, 243

 

focus pseudo-selector, 152

 

for attribute, 365

 

for keyword, 54

 

for loop, 54–56, 59, 98

 

for.in loop, 55

 

FORM element, 274, 305

 

Form object, 274