ppk on JavaScript - Introduction

This is part of the Introduction of my book "ppk on JavaScript".

Excerpted from ppk on JavaScript by Peter-Paul Koch. Copyright © 2006. Used with permission of Pearson Education, Inc. and New Riders.

Buy it here.

Back to the Book homepage.

The purpose of this book is to offer easy access to all the basic JavaScript knowledge I've gathered in the eight years 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 developer—which 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 therefore I had to make choices—occasionally 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. I left out other features that aren't quite so essential—in my opinion. Some of my readers will disagree with my selections, but that can't be helped.

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.

The example scripts

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

Textarea Maxlength example script.

In September 2004 Website agency Lost Boys contracted me to create templates for a site that unfortunately never went online. Among other things, I was asked to write 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 "JavaScript Triggers" article here.

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

Usable Forms

Usable Forms example script. This page also contains Form Validation.

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 my "Forms, Usability, and the W3C DOM" article here. You'll notice that the version of the script I discuss there is older than the one used in this book.

This is an example of 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 (one single document.onclick to power the script), and the advantages of the Level 0 DOM when working with form fields.

Form Validation

Form Validation example script. This page also contains Usable Forms.

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 the—then major—innovation 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 (which really are objects) in an interesting way.

Dropdown Menu

Dropdown Menu example script. This page also contains Edit Style Sheet.

In January 2004 I was contacted by the American company Orchid for Change to help them create an interesting framework. Orchid 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 close to seven 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 event-handling topics.

Edit Style Sheet

Edit Style Sheet example script. This page also contains Dropdown Menu.

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 of their actions become 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 as such works, and provides an excellent example of editing style sheets, as well as preparing your HTML forms to closely cooperate with a script.

Sandwich Picker

Sandwich Picker example script.

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 a general overview of his products.

Ordering sandwiches was to become a major feature of the site. Clients could select from a list of about 100 sandwiches. Since a full database solutions 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 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 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

XMLHTTP Speed Meter example script.

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 their 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 either the rough download speed the client could expect or an error message ("postal code invalid","your neighborhood doesn't yet have ADSL", etc).

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

The Site Survey example script runs in this fake "host site".

Shortly after the XMLHTTP Speed Meter was delivered, I started working on an unusual and interesting script for the Internet 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. Popups, when incorrectly used, can be great annoyances. The core of my solution is to clearly explain what's going on: "We are currently conducting a survey on this site, and for this reason a popup will shortly open". Besides, if a user doesn't want the popup despite all these messages, he only has to close the popup and will never be bothered again.

The script gives an excellent example of 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 to be included in all pages of the host site, and popup.js that is included in the popup.

Errors

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

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