Improving Usability with jQuery - Integrating the Client and Server with AJAX - HTML5 and CSS3 All-in-One For Dummies (2014)

HTML5 and CSS3 All-in-One For Dummies (2014)

Book VII Integrating the Client and Server with AJAX

Chapter 5 Improving Usability with jQuery

In This Chapter

arrow Working with scroll bars

arrow Building a sorting mechanism

arrow Managing selectable items

arrow Using the dialog box tool

arrow Creating an accordion page

arrow Building a tab-based interface

The jQuery UI adds some really great 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, it can be quite difficult to get the user to enter a date in a predictable manner. The datepicker widget provides an easy-to-use calendar for picking dates. The interface is easy for the programmer to add and makes it hard for the user to enter the date incorrectly. Another important class of tools provided by the jQuery UI helps manage complex pages by hiding content until it is needed.

Multi-Element Designs

Handling page complexity has been a constant issue in web development. As a page gets longer and more complex, navigating the page becomes more difficult. The early versions of HTML had few solutions to this problem. The use of frames was popular for a time because it allows the programmer to place navigation information in one frame and content in another. However, frames added additional usability problems and have fallen from favor. Dynamic HTML and AJAX seem like perfect replacement technologies, but they can be difficult to implement, especially in a reliable cross-browser manner.

The jQuery UI provides two incredible tools for managing larger pages:

· The accordion tool allows you to create a large page but display only smaller parts of it at a time.

· The tabs tool allows you to easily turn 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 of these tools automate and simplify the DOM and AJAX work it takes to build a large page with dynamic content.

Playing the accordion widget

Some of the most powerful jQuery tools are actually 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 5-1 to see how it works.

9781118289389-fg4101.tif

Figure 5-1: This page shows the first minibook outline of a familiar-sounding book.

When you look at Figure 5-1, you see headings for the first three minibooks of this book. The details for the first minibook are available, but the other books’ details are hidden. If you click the heading for Book II, Book I is minimized and Book II is now expanded, as you can see Figure 5-2.

9781118289389-fg4102.tif

Figure 5-2: Book I is minimized, and Book II is now expanded.

This marvelous effect allows the user to 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 allow the user to focus on a part without losing place of its position in the whole. Collapsible content has become an important usability tool made popular by the system bar in Mac OS and other popular usability tools.

The accordion effect is strikingly easy to achieve with jQuery:

<!DOCTYPE html>
<html lang = "en-US">
<head>

<title>accordion.html</title>
<meta charset = "UTF-8" />
<link rel = "stylesheet"
type = "text/css"
href = "css/ui-lightness/jquery-ui-1.10.3.custom.css" />
<script type = "text/javascript"
src = "js/jquery-1.9.1.js"></script>
<script type = "text/javascript"
src = "js/jquery-ui-1.10.3.custom.min.js"></script>
<script type = "text/javascript">

$(init);
function init(){
$("#accordion").accordion();
}
</script>
</head>
<body>
<h1>Accordion Demo</h1>
<div id = "accordion">
<h2><a href = "#">Book I - Creating the HTML Foundation</a></h2>
<ol>
<li>Sound HTML Foundations</li>
<li>It's All About Validation</li>
<li>Choosing your Tools</li>
<li>Managing Information with Lists and Tables</li>
<li>Making Connections with Links</li>
<li>Adding Images</li>
<li>Creating forms</li>
</ol>
<h2><a href = "#">Book II - Styling with CSS</a></h2>
<ol>
<li>Coloring Your World</li>
<li>Styling Text</li>
<li>Selectors, Class, and Style</li>
<li>Borders and Backgrounds</li>
<li>Levels of CSS</li>
</ol>
<h2><a href = "#">Book III - Using Positional CSS for Layout</a></h2>
<ol>
<li>Fun with the Fabulous Float</li>
<li>Building Floating Page Layouts</li>
<li>Styling Lists and Menus</li>
<li>Using alternative Positioning</li>
</ol>
</div>
</body>
</html>

As you can see by looking over the code, it's mainly just HTML. The effect is really easy to accomplish:

1. Import all the usual suspects.

You need to import the jQuery and jQuery UI JavaScript files, and a theme CSS file. (See Book VII, Chapter 4 if you need a refresher on this process.) You also need to make sure that the CSS has access to the images directory with icons and backgrounds because it will use some of these images automatically.

2. Build your HTML page as normal.

Build an HTML page as you would normally do. Pay attention to the sections that you want to collapse. There should normally be a heading tag for each element, all at the same level (Level 2 headings in my case).

3. Create a div that contains the entire collapsible content.

Put all the collapsible content in a single div with an ID. You'll be turning 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 that 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 through jQuery code.

5. Create a jQuery init()function.

Use the normal techniques to build a jQuery initializer as shown in Chapter 3 of this minibook.

6. Apply the accordion()method to the div.

Use jQuery to identify the div that contains collapsible content and apply accordion() to it:

function init(){
$("#accordion").accordion();
}

Building a tabbed interface

Another important technique in web development is the use of a tabbed interface. This allows the user to change the contents of a segment by selecting one of a series of tabs. Figure 5-3 shows an example.

In a tabbed interface, only one element is visible at a time, but the tabs are all visible. The tabbed interface is a little more predictable than the accordion because the tabs (unlike the accordion's headings) stay in the same place. The tabs change colors to indicate which tab is currently highlighted, and they also change state (normally by changing color) to indicate that they are being hovered over. When you click another tab, the main content area of the widget is replaced with the corresponding content. Figure 5-4 shows what happens when the user clicks the Book 3 tab.

9781118289389-fg4103.tif

Figure 5-3: This is another way to look at that hauntingly familiar table of contents.

9781118289389-fg4104.tif

Figure 5-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 code:

<!DOCTYPE html>
<html lang = "en-US">

<head>
<meta charset = "UTF-8" />
<link rel = "stylesheet"
type = "text/css"
href = "css/ui-lightness/jquery-ui-1.10.3.custom.css" />
<script type = "text/javascript"
src = "js/jquery-1.9.1.js"></script>
<script type = "text/javascript"
src = "js/jquery-ui-1.10.3.custom.min.js"></script>
<script type = "text/javascript">

$(init);
function init(){
$("#tabs").tabs();
}

</script>
<title>tabs.html</title>
</head>
<body>
<h1 class = "ui-state-default">Tab Demo</h1>
<div id = "tabs">
<ul>
<li><a href = "#book1">Book 1</a></li>
<li><a href = "#book2">Book 2</a></li>
<li><a href = "#book3">Book 3</a></li>
</ul>
<div id = "book1">
<h2>Book I - Creating the HTML Foundation</h2>
<ol>
<li>Sound HTML Foundations</li>
<li>It's All About Validation</li>
<li>Choosing your Tools</li>
<li>Managing Information with Lists and Tables</li>
<li>Making Connections with Links</li>
<li>Adding Images</li>
<li>Creating forms</li>
</ol>
</div>
<div id = "book2">
<h2>Book II - Styling with CSS</h2>
<ol>
<li>Coloring Your World</li>
<li>Styling Text</li>
<li>Selectors, Class, and Style</li>
<li>Borders and Backgrounds</li>
<li>Levels of CSS</li>
</ol>
</div>
<div id = "book3">
<h2>Book III - Using Positional CSS for Layout</h2>y<line><![CDATA[ <ol>
<li>Fun with the Fabulous Float</li>
<li>Building Floating Page Layouts</li>
<li>Styling Lists and Menus</li>
<li>Using alternative Positioning</li>
</ol>
</div>
</div>
</body>
</html>

The mechanism for building a tab-based interface is very similar to the one for accordions:

1. Add all the appropriate files.

Like most jQuery UI effects, you need jQuery, jQuery UI, and a theme CSS file. You also need 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 pretty close.

3. Build a div that contains all the tabbed data.

This is the element that you'll be doing the jQuery magic on.

4. Place main content areas in named divs.

Each piece of content that will be displayed as a page should be placed in a div with a descriptive ID. Each of these divs should be placed in the tab div. (See my code for organization if you're confused.)

5. Add a list of local links to the content.

Build a menu of links. Place this 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:

<ul>
<li><a href = "#book1">Book 1</a></li>
<li><a href = "#book2">Book 2</a></li>
<li><a href = "#book3">Book 3</a></li>
</ul>

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 placing 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 through AJAX calls. Look at the AJAXtabs.html code for an example:

<!DOCTYPE html>
<html lang = "en-US">

<head>
<meta charset = "UTF-8" />
<link rel = "stylesheet"
type = "text/css"
href = "css/ui-lightness/jquery-ui-1.10.3.custom.css" />
<script type = "text/javascript"
src = "js/jquery-1.9.1.js"></script>
<script type = "text/javascript"
src = "js/jquery-ui-1.10.3.custom.min.js"></script>
<script type = "text/javascript">

$(init);
function init(){
$("#tabs").tabs();
}
//
</script>
<title>AJAXtabs.html</title>
</head>
<body>
<h1>AJAX tabs</h1>
<div id = "tabs">
<ul>
<li><a href = "book1.html">Book 1</a></li>
<li><a href = "book2.html">Book 2</a></li>
<li><a href = "book3.html">Book 3</a></li>
</ul>
</div>
</body>
</html>

Note: I didn't provide a screen shot for the AJAXtabs.html page because it looks exactly like tabs.html, shown in Figure 5-4.

This version of the code doesn't contain any 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. Here's what book1.html contains:

<h2>Book I - Creating the HTML Foundation</h2>
<ol>
<li>Sound HTML Foundations</li>
<li>It's All About Validation</li>
<li>Choosing your Tools</li>
<li>Managing Information with Lists and Tables</li>
<li>Making Connections with Links</li>
<li>Adding Images</li>
<li>Creating forms</li>
</ol>

As you can see, book1.html is simply a code snippet. It doesn't need all the complete trappings of a web page (like the doctype or header) because it's meant to be pulled in as part of a larger page. The AJAX trick is a marvelous technique because it allows you to build a modular system quite easily. You can build these code pages separately and include them easily into a larger page. This is a good foundation for a content-management system.

Improving Usability

Although the UI widgets are good-looking and fun, another important aspect is how they can improve usability. Web pages are often used to get information from users. Certain kinds of information can be very difficult for the user 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 5-5, illustrates some of these techniques.

9781118289389-fg4105.tif

Figure 5-5: The UItools page uses a tabbed interface to demonstrate many input tools.

A lot is going on in this page, but the tabbed interface really cleans it up and lets the user concentrate on one idea at a time. Using the tabbed interface can really simplify your user's life.

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 the website for the complete code.

Here's the main HTML code so that you can see the general structure of the page:

<h1>UI tools</h1>
<div id = "tabs">
<ul>
<li><a href = "#datePickerTab">datePicker</a></li>
<li><a href = "#sliderTab">slider</a></li>
<li><a href = "#selectableTab">selectable</a></li>
<li><a href = "#sortableTab">sortable</a></li>
<li><a href = "#dialogTab">dialog</a></li>
</ul>

You see a main div named tabs. This 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. The page also imports jQuery, jQuery UI, and the theme CSS. The init() method contains most of the jQuery code:

$(init);

function init(){
$("h1").addClass("ui-widget-header");

$("#tabs").tabs();
$("#datePicker").datepicker();

$("#slider").slider()
.bind("slide", reportSlider);

$("#selectable").selectable();

$("#sortable").sortable();

$("#dialog").dialog();

//initially close dialog
$("#dialog").dialog("close");

} // end init

The init section initializes the various components. The details of the init() function are described in each section as they are used.

Most of these special widgets require the standard jquery link, jqueryui, and a template to be installed. Many of the widgets use features from the template library. Of course, you can start with a default template and tune it up later. You just have to have a template available to see all the effects.

Playing the dating game

Imagine that you're writing a program that requires a birth date. Getting date information from the user can be an especially messy problem because so many variations exist. Users might use numbers for the month, month names, or abbreviations. Some people use month/day/year, and others use day/month/year. They may enter the year as two or four characters. (That silly Y2K thing hasn't really died yet. I still have the bunker in the backyard.) Worse, it's really hard to pick a date without a calendar in front of you.

The datepicker dialog box is one of the coolest elements in the entire jQuery UI library. When you add datepicker() functionality to a textbox, that textbox becomes a datepicker. When the user selects the date box, a calendar automatically pops up, as shown in Figure 5-6.

9781118289389-fg4106.tif

Figure 5-6: The datePicker element turns any text field into a calendar!

The user can select a date on the calendar, and it will be placed in the textbox in a standard format. You have no better way to get date input from the user. Building a datepicker can't be much easier:

1. Begin with a jQuery UI page.

You need jQuery, jQuery UI, and a theme to use the datepicker.

2. Build a form with a text field.

Any standard text input element will do. Be sure to give the element an ID so that you can refer to it in JavaScript:

<div id = "datePickerTab">
<h2>date picker</h2>
<input type = "text"
id = "datePicker" />
</div>

3. Isolate the text input element with jQuery.

Build a standard jQuery node from the input element.

4. Add the datepicker()functionality.

Use the datePicker() method to convert the text node into a date-picker. This is usually done in some type of init() function. The rest is automatic!

$("#datePicker").datepicker();

5. Retrieve data from the form element in the normal way.

When the user has selected the date, it is 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 in the ordinary way.

The datepicker 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 much more.

Picking numbers with the slider

Numeric input is another significant usability problem. When you want users to enter numeric information, it can be quite difficult to ensure that the data really is a number and that it's in the range you want. Traditional programmers often use sliders (sometimes called scroll bars) to simplify accepting numeric input. Figure 5-7 shows a slider.

9781118289389-fg4107.tif

Figure 5-7: The user can choose a number with the mouse using a slider.

The slider is (like many jQuery UI objects) very easy to set up. Here's the relevant chunk of HTML code:

<div id = "sliderTab">
<h2>slider</h2>
<div id = "slider"></div>
<div id = "slideOutput">0</div>
</div>

The Slider tab is a basic div. It contains two other divs:

· The slider div is actually empty. It will be replaced by the slider element when the jQuery is activated.

· The other div (slideOutput) in this section will be used to output the current value of the slider.

Create the slider element in the init() function with some predictable jQuery code:

$("#slider").slider();

The slider() method turns any jQuery element into a slider, replacing the contents with a visual slider.

Note that you can add a JSON object as a parameter to set up the slider with various options. See rgbSlider.html on this book's website for an example of sliders with customization. For more on how to access this book's website, see the Introduction.

You can set up a callback method to be called whenever the slider is moved. In my example, I chained this to the code that created the slider in the first place:

$("#slider").slider()
.bind("slide", reportSlider);

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:

function reportSlider(){
var sliderVal = $("#slider").slider("value");
$("#slideOutput").html(sliderVal);
} // end reportSlider

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 the user to choose from a list of elements. The selectable widget is a great way to create this functionality from an ordinary list. The user can drag or Ctrl+click items to select them. Special CSS classes are automatically applied to indicate that the item is being considered for selecting or selected. Figure 5-8 illustrates the selection in process.

9781118289389-fg4108.tif

Figure 5-8: Selectable items are easily chosen with the mouse.

Follow these steps to make a selectable element:

1. Begin with an unordered list.

Build a standard unordered list in your HTML. Give the ul an ID so that it can be identified as a jQuery node:

<div id = "selectableTab">
<h2>selectable</h2>
<ul id = "selectable">
<li>alpha</li>
<li>beta</li>
<li>gamma</li>
<li>delta</li>
</ul>
</div>

2. Add CSS classes for selecting and selected states.

If you want the selectable items to change appearance when the items are being selected or have been selected, add CSS classes as shown. Some special classes (ui-selecting and ui-selected) are predefined and will be added to the elements at the appropriate times:

<style type = "text/css">
h1 {
text-align: center;
}

#selectable .ui-selecting {
background-color: gray;
}
#selectable .ui-selected {
background-color: black;
color: white;
}
</style>

3. In the init()function, specify the list as a selectable node.

Use the standard jQuery syntax: selectable().

$("#selectable").selectable();

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 you won't be able to 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:

var selectedItems = $(".ui-selected");

Building a sortable list

Sometimes you want the user to be able to change the order of a list. This is easily done with the sortable widget. Figure 5-9 shows the sortable list in its default configuration. Of course you'll probably want to indicate somehow that the list is sortable, because this feature is not obvious to the user.

9781118289389-fg4109.tif

Figure 5-9: This looks like an ordinary list.

The user can grab members of the list and change their order, as shown in Figure 5-10.

9781118289389-fg4110.tif

Figure 5-10: The user can drag the elements into a different order.

Making a sortable list is really easy. Follow these steps:

1. Build a regular list.

Sortable elements are usually lists. The list is a regular list, but with an ID:

<div id = "sortableTab">
<h2>sortable</h2>
<ul id = "sortable">
<li>alpha</li>
<li>beta</li>
<li>gamma</li>
<li>delta</li>
</ul>
</div>

2. Turn it into a sortable node.

Add the following code to the init() method:

$("#sortable").sortable();

Creating a custom dialog box

JavaScript supplies a few dialog boxes (the alert and prompt dialog boxes), but these are 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 is resizable and movable. Figure 5-11 shows a dialog box.

9781118289389-fg4111.tif

Figure 5-11: This dialog box is actually a jQuery UI node.

warning.eps Building the dialog box is not difficult, but you need to be able to turn it on and off with code, or it will not act like a proper dialog box (which mimics a window in the operating system):

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 in the dialog box's title bar.

<div id = "dialog"
title = "my dialog">
<p>
The dialog class allows you to have a movable, sizable
customized dialog box consistent with the installed
page theme.
</p>
</div>

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:

$("#dialog").dialog();

3. Hide the dialog box by default.

tip.eps Usually you don't want the dialog box visible until some sort of event happens. In this particular example, I don't want the dialog box to appear until the user clicks a button. I put some code to close the dialog box in the init() function so that the dialog box will not appear until it is summoned.

4. Close the dialog box.

To close a 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 will immediately close:

//initially close dialog
$("#dialog").dialog("close");

5. Clicking the X automatically closes the dialog box.

The dialog box has a small X that looks like the Close Window icon on most windowing systems. The user can close the dialog box by clicking this icon.

6. You can open and close the dialog box with code.

My Open Dialog and Close Dialog buttons call functions that control the behavior of the dialog box. For example, here is the function attached to the Open Dialog button:

function openDialog(){
$(“#dialog").dialog(“open");
} // end openDialog