Improving Usability with jQuery (Javascript And Ajax)

In This Chapter

Creating an accordion page Building a tab-based interface Working with scrollbars Managing selectable items Building a sorting mechanism Using the dialog box tool
The jQuery UI adds some outstanding capabilities to your Web pages. Some of the most interesting tools are widgets, which are user interface elements not supplied in standard HTML. Some of these elements supplement HTML by providing easier input options. For example, getting users to enter dates in a predictable manner can be quite difficult. The datePicker widget’s interface is easy for programmers to add and easy for users to use. Another important class of tools provided by the jQuery UI helps manage complex pages by hiding content until it is needed.

Multi-Element Designs

The issue of how to handle page complexity has been constant in Web development. As a page grows longer and more complex, navigating it becomes difficult. Early versions of HTML had few solutions to this problem. The use of frames was popular because it lets programmers place navigation information in one frame and content in another. Frames added usability problems, however, so they have fallen from favor. Although dynamic HTML and AJAX seem like perfect replacement technologies, they can be difficult to implement, especially in a reliable cross-browser manner.

The jQuery UI provides two incredible tools for the management of larger pages:

Accordion tool: Creates a large page but display only smaller parts of it at a time.
Tabs tool: Easily turns a large page into a page with a tab menu.
These tools are incredibly easy to use, and they add tremendously to your page development options. Both tools help automate and simplify the task of working with the DOM (document object model) and AJAX, which is necessary to build a large page with dynamic content.


Using the Accordion widget

Some of the most powerful jQuery tools are the easiest to use. The Accordion widget has become an extremely popular part of the jQuery UI toolset. Take a look at accordion.html in Figure 13-1 to see how it works.
The original chapter outline of a familiar-sounding topic.
Figure 13-1:
The original chapter outline of a familiar-sounding topic.
When you look at Figure 13-1, you see headings for the first three chapters of this topic. The details for the first chapter are available, but the other chapters’ details are hidden. If you click the heading for Chapter 2, you see the screen shown in Figure 13-2, where the Chapter 1 TOC is minimized and the Chapter 2 TOC is expanded.
The Chapter 1 TOC is minimized; the Chapter 2 TOC is expanded.
Figure 13-2:
The Chapter 1 TOC is minimized; the Chapter 2 TOC is expanded.
This marvelous effect lets a user focus on a particular part of a larger context while seeing the overall outline. It’s called an accordion because the various pieces expand and contract to let a user focus on a part of the page without losing track of its position in the whole. Collapsible content has become an important usability tool made popular by the system bar in the Mac OS and by other popular usability tools.

The accordion effect is strikingly easy to achieve with jQuery:

tmp16342_thumb_thumbtmp16343_thumb_thumb
As you can see by looking over this chunk of code, it consists mainly of HTML. The accordion effect is easy to accomplish — follow these steps:
1. Import all the usual suspects.
Import the jQuery and jQuery UI JavaScript files and a theme CSS file. (See Chapter 12 for a refresher.) Also, make sure that the CSS can access the images directory, with icons and backgrounds, because the CSS uses some of these images automatically.
2. Build your HTML page in the normal way.
Build an HTML page, and pay attention to the sections you want to collapse. You should normally have a heading tag for each element, all at the same level (Level 2 headings, in my case).
3. Create a div containing the entire collapsible content.
Put all collapsible content in a single div with an id. You’ll turn this div into an accordion jQuery element.
4. Add an anchor around each heading you want to specify as collapsible.
Place an empty anchor tag (<a href = “#”></a>) around each heading you want to use as a collapsible heading. The # sign indicates that the anchor will call the same page and is used as a placeholder by the jQuery UI engine. You can add the anchor directly in the HTML or by using jQuery code.
5. Create a jQuery init() function.
Use the normal techniques (described in Chapter 10) to build a jQuery initializer.
6. Apply the accordion() method to the div.
Use jQuery to identify the div containing collapsible content and apply
accordion() to it:
tmp16344_thumb_thumb
The accordion tool automatically breaks the page into sections based on the header elements. Look into the jQuery UI documentation for details on other options. You can set some other element to indicate section breaks, allow for all elements to be collapsed at the same time, and other interesting effects.

Building a tabbed interface

Another important technique in Web development is the use of a tabbed interface. A user can then change the contents of a segment by selecting one of a series of tabs. Figure 13-3 shows an example.
Another way to look at that hauntingly familiar table of contents.
Figure 13-3:
Another way to look at that hauntingly familiar table of contents.
In a tabbed interface, only one element is visible at a time, but all tabs are visible. The tabbed interface is a little more predictable than the accordion because the tabs (unlike the accordion’s headings) remain in place. The tabs change colors to indicate which tab is highlighted, and a tab changes state to indicate that a user is hovering the mouse over it. Whenever you click another tab, the main content area of the widget is replaced with the corresponding content. Figure 13-4 shows you what happens when the user clicks the Chapter 3 tab.
Clicking a tab changes the main content and the appearance of the tabs.
Figure 13-4:
Clicking a tab changes the main content and the appearance of the tabs.
Like the accordion, the tab effect is incredibly easy to achieve. Look over the following chunk of code:
tmp16347_thumb_thumbtmp16348_thumb_thumb
The mechanism for building a tab-based interface is quite similar to the one for accordions. Follow these steps:
1. Add all appropriate files.
As with most jQuery UI effects, you need jQuery and jQueryUI and a theme CSS file. You also need to have access to the images directory for the theme’s background graphics.
2. Build HTML as normal.
If you’re building a well-organized Web page anyway, you’re already close to the organization you’ll need for tabs.
3. Build a div containing all tabbed data.
This element is the one you perform the jQuery “magic” on.
4. Place main content areas in named divs.
Place each piece of content to be displayed as a page in a div with a descriptive id. Place each div in the tab div. (See the preceding code listing for organization if you’re confused.)
5. Add a list of local links to the content.
Build a menu of links and place it at the top of the tabbed div. Each link should be a local link to one of the divs. For example, my index looks like this:
tmp16349_thumb_thumb
6. Build an init function as usual.
Use the normal jQuery techniques.
7. Call the tabs() method on the main div. Incredibly, one line of jQuery code does all the work!

Using tabs with AJAX

You have an even easier way to work with the jQuery tab interface. Rather than place all your code in a single file, place the HTML code for each panel in a separate HTML file. You can then use a simplified form of the tab mechanism to automatically import the various code snippets by using AJAX calls. The following AJAXtabs.html code is an example:
tmp16350_thumb_thumb
Note: I didn’t provide a figure for the AJAXtabs.html page because it looks to the user exactly like tabs.html (refer to Figure 13-4).
This version of the code contains none of the actual content. Instead, jQuery builds the tab structure and then uses the links to make AJAX requests to load the content. As a default, it finds the content specified by the first tab (chap1.html) and loads it into the display area. This chunk of code shows you what chap1.html contains:
tmp16351_thumb_thumb
As you can see, chap1.html is simply a code snippet. It doesn’t need the complete trappings of a Web page (such as a doctype or header) because it’s meant to be pulled in as part of a larger page.
This technique is marvelous because it lets you build a modular system quite easily — you can build these code pages separately and include them in a larger page. You then have a good foundation for a content management system.

Improving Usability

Although the UI widgets are good looking and fun to use, another important aspect of these tools is how they can improve usability. Often, Web pages are used to get information from users. Certain kinds of information can be difficult for users to enter correctly. The jQuery UI elements include a number of tools to help you with this specific problem. The UItools.html page, shown in Figure 13-5, illustrates some of these techniques.
A great deal is happening on this page, but the tabbed interface truly cleans it up and lets users concentrate on one idea at a time. Using the tabbed interface can simplify your users’ lives.
This page is a bit long because it has a number of sections. I demonstrate the code in chunks to make it easier to manage. Be sure to look on  for the complete code.
The UITools page uses a tabbed interface to demonstrate a few input tools.
Figure 13-5:
The UITools page uses a tabbed interface to demonstrate a few input tools.
Here’s the main HTML code so that you can see the general structure of the
page:
tmp16353_thumb
A main div, named tabs, contains a list of links to the various divs that will contain the demonstrations. I describe each of these divs in the section that demonstrates it, later in this chapter. The page also imports jQuery, jQueryUl, and the theme CSS. The init() method contains most of the jQuery code:
tmp16354_thumb
The details of the init() function are described in the following sections.

The dating game

Imagine that you’re writing a program requiring a birth date or other date information. Getting date information from a user can be an especially messy problem because so many variations exist. Users might use numbers, month names, or abbreviations to indicate the month, for example. Some people use the format month/day/year, and others use day/month/year. Some people indicate the year by entering two characters, and other people use four. Worse, picking a date without a calendar in front of you is difficult.
The Date Picker dialog box is one of the coolest elements in the entire jQuery UI library. When you add datepicker() functionality to a text box, the text box becomes a date picker. When a user selects the date box, a calendar automatically pops up, like the one shown in Figure 13-6.
The datePicker element turns any text field into a calendar.
Figure 13-6:
The datePicker element turns any text field into a calendar.
After a user selects a date on the calendar, the date is placed in the text box in a standard format — there’s no better way to get date input from the user. Building a date picker couldn’t be easier. Follow these steps:
1. Begin with a jQuery UI page.
You need jQuery and jQuery UI and a theme to use datePicker.
2. Build a form with a text field.
Any standard text input element will work. Be sure to give the element an id so that you can refer to it in JavaScript:
tmp16356_thumb
3. Isolate the text input element by using jQuery.
Build a standard jQuery node from the input element.
4. Add datepicker() functionality.
Use the datePicker() method to convert the text node into a date picker. The rest of the magic happens automatically. When the user selects the text area, it is automatically converted to the calendar. When the user has selected a date on the calendar, the element converts back to a text area with the appropriate date in place.
tmp16357_thumb
5. Retrieve data from the form element in the normal way.
When a user selects a date, it’s placed in the text field automatically. As far as your program is concerned, the text field is still an ordinary text field. Retrieve the data as you do for a normal text field.
The date picker is a powerful tool with a large number of additional options. Look at the jQuery UI documentation to see how to use it to select date ranges, produce specific date formats, and do much more.

Picking numbers with the slider

Numeric input is another significant usability problem. When you want users to enter numeric information, ensuring that the data is truly a number, and that it’s in the range you want, can be quite difficult. Traditional programmers often use sliders (sometimes called scrollbars) to simplify the acceptance of numeric input. Figure 13-7 shows a slider in action.
The slider is, like many jQuery UI objects, easy to set up. Here’s the relevant chunk of HTML code:
tmp16358_thumb
The slider tab is a basic div. It contains two other divs. The slider div is empty. It’s replaced by the slider element when the jQuery is activated. The other div in this section is used to output the current value of the slider.
Create the slider element in the init() function with some predictable jQuery code:
tmp16359_thumb
The slider() method turns any jQuery element into a slider, replacing the contents with a visual slider.
Using a slider to choose a number with the mouse.
Figure 13-7:
Using a slider to choose a number with the mouse.
Note that you can add a JSON object as a parameter to set up the slider with various options. See rgbSlider.html on this topic for an example of sliders with customization.
You can set up a callback method to be called whenever the slider is moved. In my example, I chained this callback code to the code that created the slider in the first place:
tmp16361_thumb
Use the bind method to bind the reportSlider function (described next) to the slide event.
The reportSlider() function reads the slider’s value and reports it in an output div:
tmp16362_thumb
To read the value of a slider, identify the jQuery node and invoke its slider() method again. This time, pass the single word value and you get the value of the slider. You can pass the resulting value to a variable, as I did, and then do anything you want with that variable.

Selectable elements

You may have a situation where you want users to choose from a list of elements. The selectable widget is a useful way to create this functionality from an ordinary list. Users can drag or Control-click items to select them. Special CSS classes are automatically applied to indicate that the item is selected or being considered for selection. Figure 13-8 illustrates the selection in process.
You can easily choose selectable items with the mouse.
Figure 13-8:
You can easily choose selectable items with the mouse.
To make a selectable element, follow these steps:
1. Begin with an unordered list.
2. Build a standard unordered list in your HTML. Give the ul an id so that it can be identified as a jQuery node:
tmp1872_thumb_thumb
3. Add CSS classes for selecting and selected states.
If you want to have a specific appearance when the items are being selected or have been selected, add CSS classes:
tmp1873_thumb_thumb
4. In the init() function, specify the list as a selectable node. Use the standard jQuery syntax: selectable():
tmp1874_thumb_thumb
The ui-selected class is attached to all elements when they have been selected. Be sure to add some kind of CSS to this class or else you can’t tell that items have been selected.
If you want to do something with all the items that have been selected, just create a jQuery group of elements with the ui-selected class:
tmp1875_thumb_thumb

Building a sortable list

Sometimes, you want users to be able to change the order of a list, which is easily done by using the sortable widget. The top of Figure 13-9 shows the sortable list in its default configuration. The user can “grab” members of the list and change their order (see the bottom of Figure 13-9).
Users can drag the elements of an ordinary list (top) into different orders (bottom).
Figure 13-9:
Users can drag the elements of an ordinary list (top) into different orders (bottom).
Making a sortable list is easy. Follow these steps:
1. Build a regular list.
2. Add an id.
Sortable elements are usually lists. The list is a regular list, but with an id:
tmp1877_thumb_thumb
3. Turn it into a sortable node by adding the following code to the init() method:
tmp1878_thumb_thumb

Creating a custom dialog box

Although JavaScript supplies a few dialog boxes (the alert and prompt dialog boxes), they’re quite ugly and relatively inflexible. The jQuery UI includes a technique for turning any div into a virtual dialog box. The dialog box follows the theme and can be resized and moved. Figure 13-10 shows a dialog box in action.
This dialog box is a jQuery UI node.
Figure 13-10:
This dialog box is a jQuery UI node.
Building the dialog box isn’t difficult, but you need to be able to turn it on and off by using code. Follow these steps:
1. Create the div you intend to use as a dialog box.
Create a div and give it an id so that you can turn it into a dialog box node. Add the title attribute, and the title shows up on the title bar of the dialog box:
tmp18710_thumb_thumb
2. Turn the div into a dialog box.
Use the dialog() method to turn the div into a jQuery dialog box node in the init() function:
tmp18711_thumb_thumb
3. Hide the dialog box by default.
Usually, you don’t want the dialog box visible until an event takes place. In this particular example, I don’t want the dialog box to appear until the user clicks a button. I added some code that will close the dialog box in the init() function so that the dialog box doesn’t appear until it’s summoned.
4. Close the dialog box.
Refer to the dialog box node and call the dialog() method on it again. This time, send the single value “close” as a parameter, and the dialog box immediately closes:
tmp18712_thumb_thumb
5. Click the x to close the dialog box.
The dialog box has a small x icon that looks like the Close icon in most windowing systems. Users can close the dialog box by clicking this icon.
6. Write code to manage opening and closing the dialog box.
My Open and Close buttons call functions that control the behavior of the dialog box. For example, here’s the function attached to the Open Dialog button:

tmp18713_thumb_thumb

Next post:

Previous post: