Introduction


The purpose of this book is to offer easy access to the basic JavaScript knowledge I've gathered since I've been a professional Web developer.

Since this book reflects my knowledge, it also reflects the limitations of that knowledge. I am a Web developer, not an application developerwhich means I talk about browser incompatibilities, accessibility, low-level syntax, and cooperation with the HTML structural layer, instead of modules, design principles, and abstraction layers.

During the eight years that I've earned a living by making Web sites, I have used some JavaScript features extensively but largely ignored others. I always took the tools I needed to do the job I was paid to do, and it turns out that the JavaScript toolbox contains many features I don't need in my day-to-day use.

Obviously, I cannot teach you to use a tool that I myself don't understand. Therefore this book only treats those language features I work with. Object-oriented JavaScript, for instance, is conspicuously absent because I've never seen the need to use it. Besides, a book has a fixed length, and so I had to make choicesoccasionally very difficult ones. In the end I selected those JavaScript features that I feel you must understand in order to use the language at competent intermediate to advanced level.

What you already should know

I expect you to be fluent in HTML and CSS. As we'll see in Chapter 4, integration with a clean and useful HTML structure is crucial for writing simple, effective scripts. Chapter 9 is incomprehensible without basic CSS knowledge.

In addition I expect you to have some JavaScript experience, even if only at copy/paste level. Take this code:

var x = document.getElementsByTagName('a'); for (var i=0;i<x.length;i++) {     if (x[i].className != 'popup') continue;     x[i].onclick = openPopup; } 


I expect you to vaguely understand that this code goes through all links in a page and defines a popup for those links that have a class="popup". You don't have to understand all the details (in fact, the purpose of this book is to explain those details), but you should have a general idea of what's going on.

Ideally, I want every beginning scripter to ascend to intermediate status by reading this book, while it should help every intermediate scripter well along the way to advanced understanding.

Companion site

My Web site, www.quirksmode.org, is a major JavaScript resource. At the directory www.quirksmode.org/book/ you'll find all example scripts, errata lists, and such.

You won't find compatibility tables in the book because they'd be outdated too quickly. Instead, such tables are online, where I can update them when browser compatibility patterns shiftor when I turn out to have made a mistake. Look for them at my site, which has been their natural habitat for the past five years anyway.

The book contains references to other Web sites: you can, of course, type the URLs into your browser's Location bar, but an easier route is to visit the companion site, where I've provided links to every site mentioned in the book.

Any JavaScript book needs example scripts. Once the writer has explained a bit of theory, he should show how to apply this theory in practice. An example script is the most obvious way of doing that.

Ideally, these scripts should be of practical value. It's all fine and dandy to create a script that lists your pets in alphabetical order and shows their fluffy images when you click on their cute names, but even if it illustrates the theory of, say, objects and popups, its practical value is essentially nil.

Therefore this book features eight real-world scripts that real-world clients paid me real-world money to write.

Each of the eight scripts was written for a specific client with a specific, commercial goal in mind, and each of the clients indicated he or she was happy with the script. In fact, six out of seven clients granted me additional business, and the only reason the seventh didn't is that he's a small business owner who needed just the one website.

You can't get much more real-world than that.

How the example scripts are used

The one disadvantage of using real-world example scripts is that it's impossible for me to treat one script per book chapter. I can't ask my clients to be content with a script that uses Core and Events but not DOM just because I haven't yet explained DOM to you.

Therefore the example scripts do everything in the book: They all use event handling, accessibility, DOM scripting, HTML structure, and CSS modification.

Essentially I chopped the scripts into pieces and then ordered these pieces thematically. You can find all example scripts at http://www.quirksmode.org/book/. Even if you're going to read this book somewhere other than in front of your computer, I advise you to familiarize yourself with the scripts beforehand. Throughout the book I assume you have an overall idea of what they do and why.

Textarea Maxlength

In September 2004 Website agency Lost Boys contracted me to create, among other things, a script that keeps track of the number of characters the user enters in a textarea. This was the Textarea Maxlength script. I subsequently discussed aspects of this script at great length in my "JavaScript Triggers" article at A List Apart, implemented it in the comment areas of my own blog, and added a description to QuirksMode. You can find my article at http://alistapart.com/articles/scripttriggers.

This is an extremely simple DOM script that slightly enhances the page it's on.

Usable Forms

In April 2003 the ING Bank contracted me to create a demo mortgage application form. Since this is one of the most complicated forms in existence, a way to hide irrelevant form fields until they're needed was mandatory. After all, a "Date of Divorce" field is only useful when the user indicates he is, in fact, divorced. In all other cases the field should remain hidden.

So I wrote Usable Forms, and to celebrate that fact I wrote "Forms, Usability, and the W3C DOM". You can find this article at http://www.digital-web.com/articles/forms_usability_and_the_w3c_dom/. You'll notice that the version of the script I discuss there is older than the one used in this book.

This is a moderately complex DOM script that continually restructures the document it's running in. It contains valuable lessons about working with custom attributes, the definition of relations between HTML elements, the use of markers, global events, and the advantages of the Level 0 DOM when working with form fields.

Form Validation

Form Validation was finalized in Spring 2004, when Website company SQR contracted me to create templates for a form-heavy site. Obviously, forms need validation scripts, and I created Form Validation, which hinged on the custom validation attribute and contained thethen majorinnovation of displaying error messages next to the form field they apply to instead of in an alert.

Form Validation contains the basics of form handling, it generates a bit of HTML, and it uses JavaScript associative arrays in an interesting way.

Dropdown Menu

In January 2004 I was contacted by Orchid for Change which offers Websites to local organizations affiliated to the Democratic Party.

One script Orchid needed was an all-time classic: the dropdown menu. Even though its usability is somewhat suspect, it has been a favorite for years and is likely to remain one of the most requested scripts in the near future.

This script gives excellent examples of the close cooperation between CSS and JavaScript to ensure accessibility, making a script keyboard-compatible, the complete mess a mouseout event can cause, and a few more advanced topics.

Edit Style Sheet

The next example script was also written for Orchid.

Orchid has several HTML templates with main style sheets that define the positioning of the various items (masthead, navigation, main content, etc.). A client selects one of these pre-defined templates, and a site is created.

However, to make each site unique, the client should have the opportunity to fine-tune the styles, mainly the colors, background-colors, fonts and typographical styles. For that purpose, each site has a second style sheet that can be tweaked to accommodate unique parts of the design.

I wrote the Edit Style Sheet script to allow clients to change this second style sheet for themselves. The client enters the desired colors and typography into a form, and the style sheet is changed so that the results are immediately visible.

Unfortunately this script never left prototype phase. It therefore lacks a few features, notably a way of submitting the changed style sheet to the server and applying it to the entire site. Nonetheless the script provides an example of editing style sheets, as well as preparing your HTML forms to cooperate with a script.

Sandwich Picker

Of all the example scripts I like this one best.

In October 2004 I worked on a Website for my butcher, Keurslager Drost, who also owns a small but successful catering service. The site was meant to streamline catering orders, as well as give visitors an overview of his products.

Ordering sandwiches was to become a major feature of the site. Since a full database solution was out of the question for budgetary reasons, the 100 or so sandwiches would end up in one static HTML file, and users would have to be able to search through this huge list.

With this in mind I created the Sandwich Picker script. A large data table contains all sandwiches, and two, initially empty, tables would contain the search results and the order information. A search box at the top of the page allows users to search for sandwiches, and the script moves the correct <tr>s to the top of the page, directly below the search box. I added a tiny order system, containing an 'order' and a 'remove' button. Pressing these buttons would move the <tr> to the correct table. A price calculation script completed the page.

The script offers an interesting example of interacting with the user by modifying the document structure, and it illustrates a few key points in the cooperation between JavaScript and CSS.

XMLHTTP Speed Meter

In September 2005 Website company Eend contracted me to create a script for a ADSL download speed meter for the ISP Wanadoo. The plan was extremely simple: users would enter their postal code and house number in a form, and an XMLHttpRequest script would silently send this data to a server side script that returned a bit of XML with the rough download speed the client could expect.

The download speed was displayed as an animation that moved between the minimum and maximum speeds. Besides being graphically interesting, this animation would clearly show that the download speed was only an indication of what clients could expect, and not a definite promise. This was very important to Wanadoo, since an exact download speed is almost impossible to predict.

The script gives a simple example of working with XMLHTTP, shows how to read out the response, illustrates the principles of JavaScript animation, and gives an excellent handle to explain the difference between setTimeout and setInterval.

Site Survey

Shortly after the XMLHTTP Speed Meter was delivered, I started working on an unusual and interesting script for research company RM Interactive.

This company is hired by large Website owners to keep track of which pages their users visit, and to present an additional, and wholly voluntary, questionnaire after the user has left the site. All this is done by means of a popup.

The script that did all these things was old, couldn't handle popup blockers, and was inaccessible to noscript users. Since RM Interactive was about to be hired by the Dutch government, all accessibility issues needed to be solved.

So I rewrote the script from scratch, with emphasis on usability and accessibility. The script demonstrates circumventing popup blockers, keeping track of what happens in the main window, restoring communications between the popup and the main window, and finding out if the user has left the site.

Note that Site Survey is the only script that's spread out over two JavaScript files: survey.js in all pages of the host site, and popup.js in the popup.

Errors

Since these are real-life scripts they contain real-life errors. While writing this book I noticed two especially.

  1. Sandwich Picker contains an accessibility error. Although in theory the page is accessible to noscript users, the usability of this noscript variant is severely hampered for reasons we'll discuss in 2G.

  2. Form Validation works with the validation custom attribute (ie. an attribute that's not a part of any (X)HTML specification). While writing Chapter 4, I noticed that in contrast to Usable Forms and Textarea Maxlength, which definitely need custom attributes, Form Validation could do without. Moving the information to the class attribute would result in a script that cooperates more closely with the CSS presentation layer. We'll discuss all this in 4B.

I decided not to correct these mistakes, since both are instructive and give insight in how JavaScript relates to HTML, accessibility, Web standards, and CSS.

The book's structure

In the first four chapters of this book we'll discuss high-level topics. The last six are devoted to technical topics.

Chapter 1 discusses JavaScript's purpose, gives a technical overview, and treats JavaScript history to show how its purpose has been redefined.

Chapter 2 discusses JavaScript's context: a usable, accessible, standards-compliant site in which structure, presentation and behavior are separated.

Chapter 3 discusses browser incompatibilities and strategies for dealing with them.

Chapter 4 discusses JavaScript's interaction with the HTML structural layer, initialization, and the <script> tag.

Chapters 5 to 10 discuss JavaScript's technical nuts and bolts: Core, BOM, Events, DOM, CSS modification, and data retrieval. 1B contains an overview of these topics.

Conventions in this book

Finally some words about the conventions in this book.

Sections

This book is divided into 10 chapters, each of which is divided into sections that are lettered A, B, C, etc.

The topics I cover are inextricably intertwined, but one of the disadvantages of the printed book format is that I cannot use hyperlinks. Therefore I did the next best thing: I created cross-references that use these chapter numbers and section letters. Example: "We're going to treat this in detail in 4B."

Code examples

Most chapters are heavily studded with code examples, which look like this.

var rows = document.getElementsByTagName('tr'); for (var i=0;i<rows.length;i++) {     var cells = rows[i].getElementsByTagName('td'); } 


If they're taken from one of the example scripts, I give the line numbers:

[Example script name, lines 14-17]

var rows = document.getElementsByTagName('tr'); for (var i=0;i<rows.length;i++) {     var cells = rows[i].getElementsByTagName('td'); } 


Occasionally I condense the example scripts because I want to focus on one feature and ignore everything else. In that case the message 'condensed' appears with the line numbers. The message 'changed' means that I changed the script a bit for reasons explained in the surrounding text.

Some lines of code are too long for this book, and are spread across two printed lines. In that case the line always ends with a special icon that means "the code on the next line really should be on this one". For instance:

var writerootRows = document.getElementById('writeroot'). getElementsByTagName('tr'); 


Sometimes JavaScript allows you to break the line at the indicated place; sometimes it doesn't. To avoid errors it's best to assume that all code is on one line in your source file.

Occasionally I give incorrect examples, which look like this:

   var rows = getElementsByTagName('tr');    for (var i=0;i<rows.length;i++) {        var cells = rows.getElementsByTagName('td'); } 


The surrounding text always explains why these examples are wrong.

Sometimes a code example contains a text between square brackets:

var rows = [get the rows in the start table]; for (var i=0;i<rows.length;i++) {     var cells = rows[i].getElementsByTagName('td'); } 


This always means: "we're going to do this-and-that first, but right now it doesn't matter how we do it". I want you to focus on the lines of real code in the example, and although they require some preparations I don't want to treat those in detail because they'd distract you from the subject I'm explaining.

You shouldn't confuse these square brackets with the square brackets that denote keys in (associative) arrays, as explained in 5K and 5L. Usually the difference is obvious.

A note on browser names

This book mainly focuses on four browsers, and I always name them "Explorer", "Mozilla", "Opera" and "Safari", followed by a version number where applicable.

"Mozilla" includes any browser based on the Gecko rendering engine, such as Firefox, Camino, and Netscape.

"Explorer" means Microsoft Internet Explorer on Windows versions 5 and up.

I decided to use this name long ago, and I have done so on www.quirksmode.org for the past seven years. Since I want to keep this book consistent with the site, it also uses "Explorer" throughout.

Although I know some people will retort that it really ought to be called Internet Explorer to distinguish it from Windows Explorer, I don't think anyone will confuse a WWW browser with a file manager especially not when they're as tightly integrated as they are.

As we'll see in Chapter 3, the Windows version of Explorer is a completely different browser than the Mac version. Since the Mac version is on the way out and not a very good browser from a JavaScript perspective, "Explorer" without qualification always means the Windows version. I only refer to the Mac version when I explicitly add "on Mac".

Timestamp

The final version of this book was written in May 2006. Obviously, developments that occurred after that time haven't been covered.

During the writing of this book I tested my scripts in the following browsers:

Explorer 6.0 and 7.0 beta 2 preview

Mozilla 1.7.12 and Firefox 1.5

Opera 8.54 and 9 beta

Safari 1.3.2

Konqueror 3.0.5

iCab 3.0



ppk on JavaScript. Modern, Accessible, Unobtrusive JavaScript Explained by Means of Eight Real-World Example Scripts2006
ppk on JavaScript. Modern, Accessible, Unobtrusive JavaScript Explained by Means of Eight Real-World Example Scripts2006
ISBN: N/A
EAN: N/A
Year: 2005
Pages: 116

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net