Improving JavaScript and AJAX with jQuery

In This Chapter

Downloading and including the jQuery library Making an AJAX request with jQuery Using component selectors Adding events to components
Creating a simple content management system with jQuery
JavaScript has amazing capabilities. It’s useful on its own and when you add J” AJAX, it becomes incredibly powerful. However, JavaScript can be tedious. There’s a lot to remember, and it can be a real pain to handle multiple platform issues. Some tasks (like AJAX) are a bit complex and require a lot of steps. Regardless of the task, there are always browser compatibility issues to deal with.
AJAX libraries have come to the rescue, and the jQuery library in particular is a powerful tool for simplifying AJAX. This chapter explains what JavaScript Libraries can do and introduces you to one of the most popular libraries in current use.

Introducing JavaScript Libraries

For these reasons, Web programmers began to compile commonly used functions into reusable libraries. These libraries became more powerful over time, and some of them have now become fundamental to Web development.
As these libraries became more powerful, the libraries not only added AJAX capabilities, but many library developers also add features to JavaScript/ DOM programming that were once available only in traditional programming languages. Many of these libraries allow for a new visual aesthetic as well as enhanced technical capabilities. In fact, most applications considered part of the Web 2.0 revolution are based in part on one of these libraries.

What is Web 2.0?

I’m almost reluctant to mention the term Web 2.0 here because it isn’t really a very useful description. There are actually three main ways people describe Web 2.0 (if such a thing really exists).
Some talk about Web 2.0 as a design paradigm (lots of white space, simple color schemes, and rounded corners). I believe the visual trends will evolve to something else, and that other aspects of the Web 2.0 sensibility will have longer-lasting impact.
The technical aspects of Web 2.0 (heavy use of AJAX and libraries to make Web programming more like traditional programming) are more important than the visual aspects. These technologies make it possible to build Web applications in much the same way desktop applications are now created.
I personally think the most important emerging model of the Web is the change in the communication paradigm. Web 2.0 is no longer about a top-down broadcast model of communication, but more of a conversation among users of a site or system. Although the visual and technical aspects are important, the changing relationship between producers and users of information is perhaps even more profound.
The design and communication aspects are fascinating, but this topic focuses on the technical aspects. When you can actually work in Web 2.0 technologies, you can decide for yourself how to express the technology visually and socially. I can’t wait to see what you produce.
A number of very powerful JavaScript/AJAX libraries are available. All make basic JavaScript easier, and each has its own learning curve. No library will write code for you, but a good library can handle some of the drudgery and let you work instead on the creative aspects of your program. JavaScript libraries can let you work at a higher level than plain JavaScript, so you can write more elaborate pages in less time.

Several important JavaScript/AJAX libraries are available. Here are a few of the most prominent:

DOJO ( A very powerful library that includes a series of user interface widgets (like those in Visual Basic and Java) as well as AJAX features.
MochiKit ( A nice lower-level set of JavaScript functions to improve JavaScript programming. It makes JavaScript act much more like the Python language, with an interactive interpreter.
Prototype ( One of the first AJAX libraries to become popular. Includes great support for AJAX and extensions for user interface objects (through the scriptaculous extension).
YUI Yahoo! Interface Library ( yui/): This is the library used by Yahoo! for all its AJAX applications. It has released this impressive library as open source.
jQuery ( jQuery has emerged as one of the more popular JavaScript and AJAX libraries. It’s the library I emphasize in this topic.

Getting to Know jQuery

This topic focuses on the jQuery library. Although many outstanding AJAX/ JavaScript libraries are available, jQuery has quickly become one of the most prominent. There are many reasons for the popularity of jQuery:
It’s a powerful library. The jQuery system can do all kinds of impressive things to make your JavaScript easier to write.
It’s lightweight. You’ll need to include a reference to your library in every file that needs it. The entire jQuery library fits in 55K, which is smaller than many image files. It won’t have a significant impact on download speed.
It supports a flexible selection mechanism. jQuery greatly simplifies and expands the document.getElementByld mechanism that’s central to DOM manipulation.
It has great animation support. You can use jQuery to make elements appear and fade, move and slide.
It makes AJAX queries trivial. You’ll be shocked at how easy AJAX is with jQuery.
It has an enhanced event mechanism. JavaScript has very limited support for events. jQuery adds a very powerful tool for adding event handlers to nearly any element.
It provides cross-platform support. The jQuery library tries to manage browser-compatibility issues for you, so you don’t have to stress so much about exactly which browser is being used.
It supports user interface widgets. jQuery comes with a powerful user interface library including tools HTML doesn’t have, like drag-and-drop controls, sliders, and date pickers.
It’s highly extensible. jQuery has a plugin library that supports all kinds of optional features, including new widgets and tools like audio integration, image galleries, menus, and much more.
It introduces powerful new programming ideas. jQuery is a great tool for learning about some really interesting ideas like functional programming and chainable objects. I explain these as you encounter them.
It’s free and open source. It’s available under an open-source license, which means it costs nothing to use, and you can look it over and change it if you want.
It’s reasonably typical. If you choose to use a different AJAX library, you’ll still be able to transfer the ideas you learned in jQuery.

Installing jQuery

The jQuery library is easy to install and use. Just go to and download the current version (1.3.2 as of this writing). Store the resulting .js file (jQuery-1.3.2.min.js) in your working directory.
You might be able to choose from a number of versions of the file. I recommend the minimized version. To make this file as small as possible, every single unnecessary character (including spaces and carriage returns) has been removed. This file is very compact, but it’s difficult to read. You can download the nonminimized version if you want to actually read the code, but it’s generally better to include the minimized version in your programs.
That’s basically all there is to it. Download the file and place it in the directory where you want to work.
To incorporate the library in your pages, simply link it as an external JavaScript file:
Be sure to include this script before you write or include other code that refers to jQuery.

Importing jQuery from Google

Easy as it is to download jQuery, there’s another great way to add jQuery (and other AJAX library) support to your pages without downloading anything. Google has a publicly available version of several important libraries (including jQuery) that you can download from the Google servers. This method has a couple of interesting advantages:
You don’t have to install any libraries. All the library files stay on the Google servers.
The library is automatically updated. You always have access to the latest version of the library without making any changes to your code.
The library might load faster. The first time one of your pages reads the library from Google’s servers, you have to wait for the full download, but then the library is stored in cache (a form of browser memory) so subsequent requests will be essentially immediate.

Here’s how you do it:


Essentially, loading jQuery from Google is a two-step process:

1. Load the Google API from Google.
Use the first <script> tag to refer to the Google AJAX API server. This gives you access to the google.loadO function.
2. Invoke google.loadO to load jQuery.
The first parameter is the name of the library you want to load. The second parameter is the version number. If you leave this parameter blank, you get the latest version. If you specify a number, Google gives you the latest variation of that version. In my example, I want the latest variation of version 1, but not version 2. Although version 2 doesn’t exist yet, I expect it to have major changes, and I don’t want any surprises.
Note that you don’t need to install any files locally to use the Google approach.

Using jQuery with Aptana

The Aptana editor is amazing. One of its most impressive features is the way it helps you build AJAX applications with several libraries. It has built-in support for jQuery, which is quite easy to use. Follow these steps to build a jQuery project within Aptana:
1. Create a new default Web project.
Many developers ignore the project mechanism in Aptana and simply create individual files. The project tool allows you to group a series of files. The Web Project Wizard (invoked when you create a new Web project) allows automatic integration of an AJAX library.
2. Select jQuery from the libraries wizard.
After you’ve entered a name for your project, you’re given a list of AJAX libraries you can add to the project, as shown in Figure 10-1. Pick jQuery from this list.
3. Do not create a hosted site.
The hosted site option allows you to simultaneously create an online version of your site within Aptana’s server structure (the cloud). Although this is an excellent option for commercial sites, you need to pay for server access, and that isn’t necessary when you’re just starting out.
Aptana has built-in support for many AJAX libraries.
Figure 10-1:
Aptana has built-in support for many AJAX libraries.
4. Look over your new project.
Aptana creates a directory structure for your project. It automatically includes access to the source files for jQuery.
5. Add a script tag to your index.html document.
As you begin to write the src attribute, the autocomplete feature helps you include the jQuery files.
6. jQuery functions are now supported in your editor.
As you write JavaScript code, Aptana gives you code completion hints for jQuery functions as if they were built into JavaScript. If you’re running an up-to-date version of Aptana, it already has the latest version of jQuery and attaches it to your project.
7. Note that now you’re working in a project.
Aptana’s project mechanism allows you to save an entire group of files (including the jQuery library together) so you can open them as one unit.
All these options for managing jQuery can be dizzying. Use whichever technique works best for you. I actually prefer using the local code, rather than the Google or Aptana solutions, because I find it easier, and this method works even if I’m offline. For smaller projects (like the demonstrations in this chapter), I don’t like the overhead of the Aptana solution or the online requirement of Google. In this chapter, I simply refer to a local copy of the jQuery file.

Writing Your First jQuery App

As an introduction to jQuery, I show you how to build an application that you can already create in JavaScript/DOM. The following sections introduce you to some powerful features of jQuery. Figure 10-2 illustrates the change.html page at work, but the interesting stuff (as usual) is under the hood.
The content of this page is modified with jQuery.
Figure 10-2:
The content of this page is modified with jQuery.

Setting up the page

At first, the jQuery app doesn’t look much different than any other HTML/ JavaScript code you’ve already written, but the JavaScript code is a bit different. Take a look at how jQuery simplifies this JavaScript code:
If you’re already knowledgeable about jQuery, you might be horrified at my use of body onload in this example. jQuery provides a wonderful alternative to the onload mechanism, but I want to introduce only one big new idea at a time. The next example illustrates the jQuery alternative to body onload and explains why it is such an improvement.

The basic features of change.html are utterly unsurprising:

The HTML has a div named output. This div initially says “Did this change?” The code should change the content to something else.
The HTML calls a function called changeme() when the body finishes
loading. This is a mechanism used frequently in DOM programming, although you see a new way to do this in the next section.
There is a reference to the jQuery library. Any page that uses jQuery must load it using one of the mechanisms described earlier in this chapter.
The changeme() function looks really crazy. When you run the program, you can tell what it does. The code gets a reference to the output div and changes its innerHTML property to reflect a new value (“I changed”). However, the syntax is really new. All that functionality got packed into one line of (funky looking) code.
Meet the jQuery node object
The secret behind jQuery’s power is the underlying data model. jQuery has a unique way of looking at the DOM that’s more powerful than the standard object model. Understanding the way this works is the key to powerful programming with jQuery.
The jQuery node is a special object that adds a lot of functionality to the ordinary DOM element. Any element on the Web page (any link, div, heading, or whatever) can be defined as a jQuery node. You can also make a list of jQuery nodes based on tag types, so you can have a jQuery object that stores a list of all the paragraphs on the page, or all the objects with a particular class name. The jQuery object has very useful methods like html(), which is used to change the innerHTML property of an element.
The jQuery node is based on the basic DOM node, so it can be created from any DOM element. However, it also adds significant new features. This is a good example of the object-oriented philosophy.
You can create a jQuery object in many ways, but the simplest is through the special $() function. You can place an identifier (very similar to CSS identifiers) inside the function to build a jQuery object based on an element. For example,
creates a variable called jQoutput, which contains a jQuery object based on the output element. It’s similar to
The jQuery approach is a little cleaner, and it doesn’t get a reference to a DOM object (as the getElementByld technique does), but it makes a new object called the jQuery object, which is an enhanced DOM object. Don’t worry if this is a little hard to understand. It gets easier as you get used to it.
Because jQoutput is a jQuery object, it has some powerful methods. You can change the content of the object with the html() method. The following two lines are equivalent:
jQuery doesn’t require you to create variables for each object, so the code in the changeMe() function can look like this:
Or you can shorten it like this:
This last version is how the program is actually written. It’s very common to refer to an object with the $() mechanism and immediately perform a method on that object as I’ve done here.

Creating an Initialization Function

Many pages require an initialization function. This is a function that’s run early to set up the rest of the page. The body onload mechanism is frequently used in DOM/JavaScript to make pages load as soon as the document has begun loading. I describe this technique in Chapter 8. Although body onload does this job well, the traditional technique has a couple of problems:
It requires making a change to the HTML. Really the JavaScript code should be completely separated from HTML. You shouldn’t have to change your HTML at all to make it work with JavaScript.
The timing still isn’t quite right. Code specified in body unload
doesn’t execute until after the entire page is displayed. It would be better if the code was registered after the DOM is loaded but before the page displays.
Using $(document).ready()

jQuery has a great alternative to body onload that overcomes its drawbacks. Take a look at the code for ready.html to see how it works:


This code is much like the change.html, but it uses the jQuery technique for running initialization code:

The <body> tag no longer has an onload attribute. This is a common feature of jQuery programming. The HTML no longer has direct links to the JavaScript because jQuery lets the JavaScript code attach itself to the Web page.
The initialization function is created with the $(document).ready() function. This technique tells the browser to execute a function when the DOM has finished loading (so it has access to all elements of the form) but before the page is displayed (so any effects of the form appear instantaneous to the user).
$(document) makes a jQuery object from the whole document.
The entire document can be turned into a jQuery object by specifying document inside the $() function. Note that you don’t use quotes in this case.
The function specified is automatically run. In this particular case, I want to run the changeMe() function, so I place it in the parameter of the ready() method. Note that I’m referring to changeMe as a variable, so it has no quotes or parentheses. (Look at Chapter 8 for more discussion of referring to functions as variables.)
You might see several other places (particularly in event handling) where jQuery expects a function as a parameter. Such a function is frequently referred to as a callback function because it is called after some sort of event has occurred. You might also notice callback functions that respond to keyboard events, mouse motion, and the completion of an AJAX request.

Discovering alternatives to document.ready

Programmers sometimes use shortcuts instead of document.ready because it’s so common to run initialization code. You can shorten
to the following code:
If this code isn’t defined inside a function and changeMe is a function defined on the page, jQuery automatically runs the function directly just like the
document.ready approach.
It’s also possible to create an anonymous function directly:
I think this method is cumbersome, but jQuery code frequently uses this technique.

Investigating the jQuery Object

The jQuery object is interesting because it’s easy to create from a variety of DOM elements and because it adds wonderful new features to these elements.

Changing the style of an element

If you can dynamically change the CSS of an element, you can do quite a lot to it. jQuery makes this process quite easy. When you have a jQuery object, you can use the css method to add or change any CSS attributes of the object. Take a look at styleElement.html shown in Figure 10-3 for an example.
All the styles here are applied dynamically by jQuery functions.
Figure 10-3:
All the styles here are applied dynamically by jQuery functions.

The code displays a terseness common to jQuery code:

This program has a few interesting things going on in it. Take a look at the
It contains an <h1> tag. I’m aware that’s not too exciting, but I use it to show how to target elements by DOM type.
A paragraph has the ID myParagraph. This paragraph is used to illustrate how to target an element by ID.
Two elements have the class bordered. In ordinary DOM work, you can’t easily apply code to all elements of a particular class, but jQuery makes it easy.
Several elements have custom CSS, but no CSS is defined. The jQuery code changes all the CSS dynamically.
The init() function is identified as the function to be run when the document is ready. In this function, I use the powerful CSS method to change each element’s CSS dynamically. I come back to the CSS in a moment, but first notice how the various elements are targeted.

Selecting jQuery objects

jQuery gives you several alternatives for creating jQuery objects from the DOM elements. In general, you use the same rules to select objects in jQuery as you do in CSS:
DOM elements are targeted as-is. You can include any DOM element inside the $(“”) mechanism to target all similar elements. For example, use $(“h1″) to refer to all hi objects, or $(“p”) to refer to all paragraphs.
Use the # identifier to target a particular ID. This works exactly the same as CSS. If you have an element with the ID myThing, use this code: $(“#myThing”).
Use the . identifier to target members of a class. Again, this is the same mechanism you use in CSS, so all elements with the class bordered attached to them can be modified with this code: $(“.bordered”).
You can even use complex identifiers. You can use complex CSS identifiers like img”); this identifier targets only images inside a list item.
These selection methods (all borrowed from familiar CSS notation) add incredible flexibility to your code. You can now easily select elements in your JavaScript code according to the same rules you use to identify elements in CSS.

Modifying the style

After you’ve identified an object or a set of objects, you can apply jQuery methods. One very powerful and easy method is the style() method. The basic form of this method takes two parameters: a style rule and value. For example, to make the background color of all h1 objects yellow, I used the following code:
If you apply a style rule to a collection of objects (like all h1 objects or all objects with the bordered class), the same rule is instantly applied to all the objects.
A more powerful variation of the style rule allows you to apply several CSS styles at once. It takes a single object in JSON notation (JavaScript Object Notation described in Chapter 5) as its argument:
This example uses a JSON object defined as a series of rule/value pairs. If you need a refresher on how JSON objects work, look at Chapter 5.

Adding Events to Objects

The jQuery library adds another extremely powerful capability to JavaScript. It allows you to easily attach events to any jQuery object. As an example, take a look at hover.html, shown in Figure 10-4.
When you move the mouse pointer over any list item, a border appears over the item. This effect would be difficult to achieve in ordinary DOM/JavaScript, but it’s pretty easy to manage in jQuery.
A border appears around each list item when the mouse is over it.
Figure 10-4:
A border appears around each list item when the mouse is over it.

Adding a hover event

Look at the code to see how it works:

The HTML couldn’t be simpler: It’s an unordered list. The JavaScript isn’t much more complex. It consists of three one-line functions.
init() : This function is called when the document is ready. It makes jQuery objects out of all list items and attaches the hover event to them. hover accepts two parameters. The first is a function to be called when the mouse hovers over the object. The second parameter is a function to be called when the mouse leaves the object.
border() : This function draws a border around the current element. The $(this) identifier is used to specify the current object. In this example, I use the css function to draw a border around the object.
noBorder(): It’s very similar to the border() function, but it removes a border from the current object.
In this example, I used three different functions. Many jQuery programmers prefer to use anonymous functions (sometimes called lambda functions) to enclose the entire functionality in one long line:
Note that this is still technically a single line of code. Instead of referencing two functions that have already been created, I build the functions immediately where they’re needed. Each function definition is a parameter to the hover() method.

jQuery events

jQuery supports a number of other events. Any jQuery node can read any of the following
change: The content of the element changes.
click: The user clicks the element.
dblClick: The user double-clicks the element.
focus: The user selects the element.
keydown: The user presses a key while the element has the focus.
hover: The mouse is over the element — a second function is called when the mouse leaves the element.
mouseDown: A mouse button is pressed over the element.
select: The user selects text in a text-style input.
If you’re a computer scientist, you might argue that this isn’t a perfect example of a lambda function, and you would be correct. The important thing is to notice that some ideas of functional programming (such as lambda functions) are creeping into mainstream AJAX programming, and that’s an exciting development. If you just mutter “lambda” and then walk away, people will assume you’re some kind of geeky computer scientist. What could be more fun than that?
Although I’m perfectly comfortable with anonymous functions, I often find the named-function approach easier to read, so I tend to use complete named functions more often.

Changing classes on the fly

jQuery supports another wonderful feature. You can define a CSS style and then add or remove that style from an element dynamically. Figure 10-5 shows a page with the ability to dynamically modify the border of any list item.
Click a list item to toggle its border on and off.
Figure 10-5:
Click a list item to toggle its border on and off.

The code for class.html shows how easy this kind of feature is to add:


Here’s how to make this program:

1. Begin with a basic HTML page.
All the interesting stuff happens in CSS and JavaScript, so the actual contents of the page aren’t that critical.
2. Create a class you want to add and remove.
I build a CSS class called bordered, which simply draws a border around the element. Of course, you can make a much more sophisticated CSS class with all kinds of formatting if you prefer.
3. Link an init() method.
As you’re beginning to see, most jQuery applications require some sort of initialization. I normally call the first function init().
4. Call the toggleBorder() function whenever the user clicks a list item.
The init() method simply sets up an event handler. Whenever a list item receives the click event (that is, the list item is clicked), the tog-gleBorder() function should be activated.
5. The toggleBorder() function, well, toggles the border.
jQuery has several methods for manipulating the class of an element. addClass() assigns a class to the element, removeClass() removes a class definition from an element, and toggleClass() switches the class (by adding the class if it isn’t currently attached or removing it otherwise).

Making an AJAX Request with jQuery

The primary purpose of an AJAX library like jQuery is to simplify AJAX requests. It’s hard to believe how easy this can be with jQuery. Figure 10-6 shows ajax.html, a page with a basic AJAX query.
The text file is requested with an AJAX call.
Figure 10-6:
The text file is requested with an AJAX call.

Including a text file with AJAX

The ajax.html program is very similar in function to the asynch.html program described in Chapter 9, but the code is much cleaner:
The HTML is very clean (as you should expect from jQuery examples). It simply creates an empty div called output.
The JavaScript code isn’t much more complex. A standard $(document). ready function calls the getAJAX() function as soon as the document is ready. The getAJAX() function simply creates a jQuery node based on the output div and loads the file hello.txt through a basic AJAX request.
This example does use AJAX, so if it isn’t working, you might need to review how AJAX works. You should run a program using AJAX through a Web server, not just from a local file. Also, the file being read should be on the same server as the program making the AJAX request.
I cover more sophisticated AJAX techniques in Chapter 14. The load() mechanism is suitable for a basic situation where you want to load a plain text or HTML code snippet into your pages.

Building a poor man’s CMS with AJAX

AJAX and jQuery can be a very useful way to build efficient Web sites even without server-side programming. Frequently a Web site is based on a series of smaller elements that can be swapped and reused. Such a technique is called a CMS (content management system). You can use AJAX to build a framework that allows easy reuse and modification of Web content.
As an example, take a look at cmsAJAX shown in Figure 10-7.
This page is actually created dynamically with AJAX and jQuery.
Figure 10-7:
This page is actually created dynamically with AJAX and jQuery.
Although there’s nothing all that shocking about the page from the user’s perspective, a look at the code shows some surprises:

The code has these interesting features:

The page has no content! All the divs are empty. None of the text shown in Figure 10-7 is present in this document, but all is pulled from smaller files dynamically.
The page consists of empty, named divs. Rather than any particular content, the page consists of placeholders with IDs.
It uses jQuery. The jQuery library is used to vastly simplify loading data through AJAX calls.
All contents are in separate files. The directory has very simple HTML files containing small parts of the page. For example, story1.html looks like this:
The init() method runs on document.ready. When the document is ready, the page runs the init() method.
The init() method uses AJAX calls to dynamically load content. It’s nothing more than a series of jQuery load() methods.
This approach might seem like a lot of work, but it has some very interesting characteristics. If you’re building a large site with several pages, you usually want to design the visual appearance once and re-use the same general template over and over again. Also, you’ll probably have some elements (such as the menu and heading) that will be consistent over several pages. You could simply create a default document and copy and paste it for each page, but this approach gets messy. What happens if you have created 100 pages according to a template and then need to add something to the menu or change the header? You would need to make the change on 100 different pages.
The advantage of the template-style approach is code reuse. Just like use of an external style allows you to multiply a style sheet across hundreds of documents, designing a template without content allows you to store code snippets in smaller files and reuse them. All 100 pages point to the same menu file, so if you want to change the menu, you change one file and everything changes with it.

Here’s how you use this sort of approach:

1. Create a single template for your entire site.
Build basic HTML and CSS to manage the overall look and feel for your entire site. Don’t worry about content yet. Just build placeholders for all the components of your page. Be sure to give each element an ID and write the CSS to get things positioned as you wish.
2. Add jQuery support.
Make a link to the jQuery library, and make a default init() method. Put code to handle populating those parts of the page that will always be consistent. (I use the template shown here exactly as it is.)
3. Duplicate the template.
When you have a sense how the template will work, make a copy for each page of your site.
4. Customize each page by changing the init() function.
The only part of the template that changes is the init() function. All your pages will be identical, except they will have customized init() functions that load different content.
5. Load custom content into the divs with AJAX.
Use the init() function to load content into each div. Build more content as small files to create new pages.
This is a great way to manage content, but it isn’t quite a full-blown content management system. Even AJAX can’t quite allow you to store content on the Web. More complex content management systems use databases rather than files to handle content. You need some sort of server-side programming (like PHP) and usually a database (like mySQL) to handle this sort of work. I introduce these topics in Chapter 14.

Next post:

Previous post: