Using the jQuery User Interface Toolkit (Javascript And Ajax)

In This Chapter

Exploring the jQuery user interface
• Installing the UI and templates
• Adding date pickers, dialog boxes, and icons Dragging and dropping
Working with scrollbars Building a sorting mechanism Creating an accordion page Building a tab-based interface
The jQuery library is an incredible tool for simplifying JavaScript programming. The library is so popular and powerful that developers began adding new features to make it even more useful. Among the most important of these is the jQuery UI (user interface) framework. This tool adds these welcome features to Web development:
New user interface elements: As a modern user interface tool, HTML is missing some important tools. Most modern visual languages include built-in support for devices such as scrollbars, dedicated date pickers, and multiple tab tools. jQuery UI adds these features and more.
Advanced user interaction: The jQuery widgets give users new and exciting ways to interact with your page. Using the UI toolkit, you can easily let users make selections by dragging and dropping elements and expanding and contracting parts of the page.
Flexible theme templates: jQuery UI includes a template mechanism that controls the visual look and feel of your elements. You can choose from dozens of prebuilt themes or use a tool to build your own particular look. You can reuse this template library to manage the look of your other page elements, too (not just the ones defined by the library).
A complete icon library: The jQuery UI has a library of icons for use in your Web development. It has arrows and buttons and plenty of other doodads that you can change to fit your template.
A clean, modern look: You can easily build forward-looking visual designs with jQuery UI. It supports rounded corners and plenty of special visual effects.
The power of jQuery: As an extension of jQuery, the jQuery UI adds to the incredible features of the jQuery language.
Open source values: The jQuery UI (like jQuery itself) is an open-source project with quite an active community. You can modify its free library to suit your needs.


Looking Over the ThemeRoller

The jQuery UI Web site (http://jqueryui.com) is a helpful place to find the latest information about jQuery, and it also features the marvelous Theme Roller tool. Figure 12-1 shows the main Web page, which demonstrates many of the excellent jQuery features.
Before you use ThemeRoller to change themes, use it to become acquainted with the UI elements. Several useful tools are visible in the figure:
Accordion: The upper-left segment of the page has three segments (Section 1, Section 2, and Section 3). By clicking a section heading, the user can expand that section and collapse others.
Slider: Sliders (or scrollbars) are an essential user interface element that lets a user choose a numeric value by using an easy visual tool. You can adjust jQuery sliders in many ways to allow easy and error-free input.
Date picker: Ensuring that users enter dates properly is difficult. The phenomenally useful date picker control automatically pops a calendar onto the page and lets the user manipulate the calendar to pick a date.
Progress bar: Always design your code so that little delay occurs, but if a part of your program takes some time to complete, a progress bar is a useful reminder that something is happening.
Tabs: The accordion technique is one way to hide and show parts of your page, and tabs are another popular technique. You can use this mechanism to build a powerful multi-tab document without having to do much work.
ThemeRoller lets you look over many jQuery UI elements and modify their look.
Figure 12-1:
ThemeRoller lets you look over many jQuery UI elements and modify their look.
Scrolling down the page, you see even more interesting tools. Figure 12-2 shows some of these widgets in action.
These widgets demonstrate even more of the power of the jQuery UI library:
Dialog: Pressing the Open Dialog button pops up what appears to be a dialog box. It acts much like the JavaScript alert, but it’s much nicer looking and has features that make it much more advanced.
Formatting tools: The jQuery UI includes special tools for setting apart certain parts of your page as warnings, as highlighted text, or with added shadows and transparency.
Icons: jQuery UI ships with a large collection of icons you can use in your page. Hover the mouse over each icon on the ThemeRoller to see a description. You can easily use these icons to allow various user interactions.
Even more exciting widgets.
Figure 12-2:
Even more exciting widgets.

Visiting the Theme Park

Impressive as all the jQuery UI widgets are, they’re just a part of the story. jQuery supports the concept of themes, which are simply visual rule sets. A theme is essentially a complex CSS document (and some associated graphics files) designed to be used with the UI library. Go back to the top of the Theme Roller page and look at the left column. If you click the Gallery tab (yes, it’s using a jQuery UI tab interface), you can see a list of prebuilt themes. Figure 12-3 shows the ThemeRoller page with an entirely different theme in place.
The built-in themes are impressive, but of course you can make your own. Though you’re always free to edit the CSS manually, the whole point of the ThemeRoller application is to make this process easier.
Now, ThemeRoller is using the Le Frog theme.
Figure 12-3:
Now, ThemeRoller is using the Le Frog theme.
If you go back to the Roll Your Own tab, you see an accordion selection that you can use to pick various theme options. You can change fonts, choose rounded corners, select various color schemes, and much more. You can mess around with these options all you want and create your own visual style. You can then save that theme and use it in your own projects.

Wanna Drag? Dragging and Dropping Elements

It’s time to build something. The first example I show you is a simple application that lets someone use the mouse to pick up a page element and move it. Although I tell you how to use JavaScript and the document object model (DOM) to do this in Chapter 8, you’ll find that you can quite easily create the same effect by using jQuery UI. Figure 12-4 shows this page in action.
The user can simply drag the box anywhere on the page.
Figure 12-4:
The user can simply drag the box anywhere on the page.
This example is a good starting place for using the jQuery UI library because it’s easy to get the project working. Often, the hardest part of writing jQuery UI applications is making the connections to the library. After you do that (and it’s not that hard), the rest of the programming is ridiculously easy. Take a look at the following chunk of code to see what I’m talking about:
tmp16318_thumb_thumbtmp16319_thumb_thumb
The basic idea of this program is completely consistent with the jQuery concepts I describe in Chapter 13. The page uses simple HTML code. An initialization function creates a special jQuery node and gives it functionality. That’s all there is to it.

Here are the basic steps:

1. Create a basic HTML document.
You can use a standard document. I created one div with the ID dragMe, which is the div I want to make draggable. (You can, of course, apply dragging functionality to any element you can select with jQuery.)
2. Add the standard jQuery library.
The first <script> tag imports the standard jQuery library. The UI library requires jQuery to be loaded first.

A ThemeRoller example

ThemeRoller gives you a good overview of the jQuery UI library and also serves as a great example of where the Web is going. It’s not really a Web page as much as it’s an application that happens to be written in Web technologies. Notice that the functionality of the page (changing styles dynamically) uses many jQuery and jQuery UI tricks: tabs, accordions,
and dialog boxes, for example. This kind of programming, which is almost certainly the direction in which Web development is heading, might indeed be the primary form of application in the future. Certainly, it appears that applications using this style of user interface, and AJAX, for data communication and storage will be important for quite some time.
3. Add a link to the jQuery UI library.
A second <script> tag imports the jQuery UI library. (See the section called “Downloading the Library” for details on how to obtain this library.)
4. Create an initialization function.
Use the standard jQuery techniques to build an initialization function for your page. (As usual, I named mine init().)
5. Build a draggable node.
Use standard jQuery selection techniques to isolate the elements you want to make draggable. Use the draggable() method to make the element draggable.
6. Test.
Believe it or not, that’s all there is to it. As long as everything is set up properly, your element can be dragged! A user can drag it with the mouse and place it anywhere on the screen.

Downloading the Library

Writing jQuery UI code isn’t difficult, but getting access to the parts of the library you need can be a bit confusing. The jQuery UI library is much larger than the standard jQuery package, so you might not want to include the entire package if you don’t need it. Previous versions of jQuery UI let you download the entire package but stored each of the various elements in a separate JavaScript file. You would commonly have a half-dozen different script tags active just to put the various elements in place. Worse, there were some dependency issues, so you had to ensure that certain packages were installed before you could use other packages — all of which made a simple library quite complex to use.
Fortunately, the latest versions of the jQuery UI make this process quite a bit simpler. Whenever you begin to work on a project, you pick (or create) a visual theme, choose the widgets and tools you want, and download a custom form of the library that’s tailored to your exact needs. Using this mechanism, you have much simpler code because you link only one JavaScript library for the UI no matter how many interface tools and gadgets you use (though you still need to link the standard jQuery library first).
Use this technique also to build in multiple themes so that you can easily switch the look of your program by changing the theme files.

Resizing on a Theme

This section demonstrates two important ideas in the jQuery UI package:

Resizable elements: The user can drag an element’s bottom or right border to change its size. Making an element resizable is similar to making it draggable.
Themes: jQuery features a series of customized visual styles.
You can see in Figure 12-5 that the page has a definite visual style. The elements have distinctive fonts and backgrounds, and the headers are in a particular visual style. Though these styles aren’t earth-shattering (after all, it’s just CSS), the exciting news is that they’re defined by the theme. You can easily select another theme (created by hand or by using ThemeRoller), and the visual look of all these elements will reflect the new theme. Themes provide a further level of abstraction to your Web site that makes changing the overall visual style much easier than modifying the CSS by hand.
A user can change the size of this lovely element.
Figure 12-5:
A user can change the size of this lovely element.
Figure 12-6 shows the page after the Resize Me element has changed sizes, and you can see that the rest of the page reformats itself to fit the newly resized element.
When the element is resized, the remainder of the page adjusts.
Figure 12-6:
When the element is resized, the remainder of the page adjusts.
The following chunk of code reveals that most of the interesting visual effects in Figure 12-6 are simple CSS coding, and the resizing is just more jQuery UI magic:
tmp16322_thumb_thumbtmp16323_thumb_thumbtmp16324_thumb_thumb

Examining the HTML and standard CSS

As usual, the HTML used in the code example in the preceding section is the foundation of the entire page. It’s clean, and it shows the general structure of the page. The HTML consists of only three primary elements: a heading and two divs. Each div contains its own Level 2 heading and a paragraph. The divs are given IDs to make them easier to style.
I also included a basic CSS section in the example to handle the general layout of the page. Because I wanted the widgets to have specific initial sizes, I used ordinary CSS to create this effect.

Importing files

jQuery applications require the importation of JavaScript code libraries. In this (and most) jQuery UI applications, I import these three files:
The main jQuery library: This essential jQuery base library is imported as described in Chapter 11, as an ordinary JavaScript file.
The jQuery UI library: This file is also a standard JavaScript library. To obtain a custom version of this file, see the section “Downloading the Library,” earlier in this chapter.
The theme CSS file: When you create a theme with ThemeRoller, you’re provided with a CSS file. This file is your theme. Because it’s a CSS file rather than a chunk of JavaScript code, use the link tag to attach it to your page.
Not all jQuery UI examples require a theme, but most do. As you see in this example, themes provide some other excellent effects too, so it’s worthwhile to include a theme CSS file whenever you want to use jQuery UI.

Making a resizable element

Surprisingly, the easiest part of the project is making the resizable element take on the resizable behavior, as shown in this example:
tmp16325_thumb_thumb

It’s a standard jQuery UI trick. Follow these steps:

1. Begin with an initialization function.
Like all good jQuery code, this example begins with standard initialization.
2. Make an element resizable.
Identify the resizeMe div as a jQuery node, and use the resizable() method to make it resizable. That’s all there is to it.
3. Call a second function to add theming to the elements.
Though the resizable method doesn’t require the use of jQuery themes, the themes improve the look of the element.

Adding themes to your elements

The jQuery Theme tool helps you quite easily decorate your elements by using CSS. The outstanding feature of jQuery themes is that they’re semantic: You specify the general purpose of the element and then let the theme apply the appropriate specific CSS. You can use the ThemeRoller application to easily create new themes or modify existing ones. In this way, you can create quite a sophisticated look and feel for your site and write a minimal amount of CSS on your own. Many jQuery interface elements (such as the Accordion and Tab tools, described elsewhere in this chapter) automatically use the current CSS theme. You can also apply the theme to any of your own elements, of course, to create a consistent look.
Themes are simply a set of predefined CSS classes. To apply a CSS theme to an element, you can just add a special class to the object. For example, you can make a paragraph look like the current definition of the ui-widget by adding this bit of code to it:
tmp16326_thumb_thumb
Of course, adding classes into the HTML violates one principle of semantic design, so you can more efficiently do the work in JavaScript by using jQuery:
tmp16327_thumb_thumb
The themify() function adds all the themes to the elements on my page, using the CSS defined by the theme. I use jQuery tricks to simplify the process.
1. Identify all divs by using jQuery.
To style all divs in your page as widgets, use jQuery to identify all div elements.
2. Add the ui-widget class to all divs.
This class is defined in the theme. All jQuery themes have this class defined, but the specific characteristics (colors and font sizes, for example) vary by theme. In this way, you can swap out a theme to change its appearance and the code still works. The ui-widget class defines an element as a widget.
3. Add ui-widget-content.
The divs need two classes attached, so I use chaining to specify that divs should also be members of the ui-widget-content class. This class indicates that the contents of the widget (and not just the class itself) should be styled.
4. Specify rounded corners.
Rounded corners have become a standard feature of Web 2.0 visual design. This effect is extremely easy to achieve by using jQuery: Just add the ui-corner-all class to any element that you want to have rounded corners.
Rounded corners use CSS3, which isn’t yet supported by all browsers. Your page won’t show rounded corners in most versions of Internet Explorer, but the page will still work fine otherwise.
5. Make all headlines conform to the widget-header style.
The jQuery themes include an attractive headline style. You can easily make all heading tags (from <h1> to <h6>) follow this theme. Use the :header filter to identify all headings, and apply the ui-widget-header and ui-corner-all classes to these headers.
The jQuery UI package supports a number of interesting classes, as described in Table 12-1.

Table 12-1 Classes Supported by the jQuery UI Package
Class Used On What It Does
ui-widget Outer container of widget Makes the element look like a widget
ui-widget-
header
Heading element Applies a distinctive heading appearance
ui-widget-content Widget Applies widget content style to an element and its children
ui-state-default Clickable elements Displays standard (unclicked) state
ui-state-hover Clickable
elements
Displays hover state
ui-state-focus Clickable elements Displays focus state when element has keyboard focus
ui-state-active Clickable elements Display active state when mouse is clicked on element
ui-state-highlight Any widget or element Specifies that element is highlighted
ui-state-error Any widget or element Specifies that an element contain an error message or a warning message
ui-state-error text Text elements Allows error highlighting without changing other elements (mainly used in form validation)
ui-state-disabled Any widget or element Demonstrates that widget is disabled
ui-
corner-all,
Any widget or element Adds current corner size to element; corners specified by using tl, tr, bl, br, top, bottom, left, right
ui-corner-
tl (etc)
ui-widget-shadow Any widget Applies shadow effect to widget

Note there a few other classes are defined in UI themes, but the ones in this table are the most commonly used. Please see the current jQuery UI documentation for more details.

Adding an icon

Note the small star that appears inside the resizeMe element in Figure 12-6. This element is an example of a jQuery UI icon. All jQuery themes support a standard set of icons, which are small images (16 pixels square). The icon set includes standard icons for arrows as well as images commonly used in menus and toolbars (Save and Load or New File, for example). Some jQuery UI elements use icons automatically, but you can also add them directly.

To use an icon in your programs, follow these steps:

1. Include a jQuery UI theme.
The icons are part of the theme package. Include the CSS style sheet that corresponds with the theme (as you did if you followed the instructions in Chapter 10).
2. Ensure that the images are accessible.
When you download a theme package, it includes a directory of images. The images included in it are used to create custom backgrounds as well as icons. The CSS file expects a directory named images to be in the same directory as the CSS. This directory should contain several images that begin with ui-icons. These images contain all necessary icons. If the icon image files aren’t available, the icons aren’t displayed.
3. Create a span where you want the icon to appear.
Place an empty span element wherever you want the icon to appear in the HTML. You can place the span directly in the HTML or add it by using jQuery. I prefer to add UI elements by using jQuery, to keep the HTML as pristine as possible.
4. Attach the ui-icon class to the span.
This step tells jQuery to treat the span as an icon. The contents of the span are hidden and the span is resized to hold a 16-pixel-square icon image.
5. Attach a second class to identify the specific icon.
Look at the ThemeRoller page to see the available icons. When you hover the mouse over an icon on this page, you see the class name associated with the icon.

You can add the code directly in your HTML:

tmp16328_thumb_thumb
Or, you can use jQuery to add the appropriate code to your element:
tmp16329_thumb_thumb

Dragging, Dropping, and Calling Back

JQuery elements look good, but they also have interesting functionality. Most jQuery UI objects can respond to specialized events. As an example, look over the dragDrop.html page shown in Figure 12-7.
The page has a group of draggable elements and a target.
Figure 12-7:
The page has a group of draggable elements and a target.
When you drop an element on the target, the color and content of the target change, as shown in Figure 12-8.
The target "knows" when something has been dropped on it.
Figure 12-8:
The target “knows” when something has been dropped on it.
The program demonstrates how jQuery simplifies the task of working with a number of elements.
Take a look at the entire program before you see its smaller segments:
tmp16332_thumb_thumbtmp16333_thumb_thumbtmp16334_thumb_thumb

Building the basic page

As is typical with jQuery, the HTML code on this page is misleadingly simple. It has, strikingly, only a single dragMe element, for example. It’s simpler to build a single element in HTML and then use jQuery and JavaScript to make as many copies as you need than it would be to build all the elements by hand in straight HTML. The page also has a single target element. I added basic CSS (borders) to make the elements easy to see and set all the elements as absolutely positioned so that I can control their initial positions. Note that I attached an ID to the target (as there will be a single target on the page), and made dragMe a class (as I want the capability to have several draggable elements on the page).

Initializing the page

The initialization process is somewhat elaborate, but it still isn’t too difficult to follow. The main addition is its capability to respond to some specialty events:
tmp16335_thumb_thumbtmp16336_thumb_thumb

Follow these steps:

1. Make copies of the dragme element.
This step isn’t critical. (In fact, I added it after testing a single element.) However, if you want to have multiple copies of the draggable element, use a method to encapsulate the process.
2. Make all dragme elements draggable.
Use the jQuery draggable() method on all elements with the dragMe class.
3. Establish the target as a droppable element.
The droppable() method sets up an element so that it can receive events whenever a draggable element is dropped on it. Note that making something droppable doesn’t have any particular effect on its own. The interesting part happens when you bind events to the element.
4. Bind a drop event to the target.
Droppable elements can have events attached to them, just like any jQuery object can. However, the mechanism for attaching an event to a user interface object is a little different from the standard jQuery event mechanism, which involved a custom function for each event. Use the bind method to specify a function to be called whenever a particular event occurs. When the user drops a draggable element on the target element (the drop event), call the changeTarget() function.
5. Bind a dropout event to the target.
You can bind another event, dropout, to occur whenever the user removes all draggable elements from the target. I told the sample program to call the resetTarget() function whenever this event is triggered.
You often see programmers using shortcuts for this process. Sometimes the functions are defined anonymously in the bind call, or sometimes the event functions are attached as a JSON object directly in the droppable() method assignment. Feel free to use these techniques if you’re comfortable with them. I chose my technique based on its being the clearest model to understand.

Handling the drop

When the user drags a dragMe element and drops it on the target, the target’s background color changes and the program reports the text of the element that was dragged. The code is easy to follow:
tmp16337_thumb_thumb

To respond to a drop event, follow these steps:

1. Create a function to correspond to the drop event.
The drop event is bound to the function changeTarget, so you need to create such a function.
2. Include two parameters.
Bound event functions require two parameters. The first is an object that encapsulates the event (much like the one in regular DOM programming) and a second element, named ui, which encapsulates information about the user interface. You use the ui object to determine which draggable element was dropped on the target.
3. Highlight the target.
You should signal that the target’s state has changed. You can change the CSS directly (using jQuery) or use jQuery theming to apply a predefined highlight class. I chose to use the jQuery theme technique to simply add the ui-state-highlight class to the target object.
4. Change the text to indicate the new status.
You normally want to do something to indicate what was dropped. If it’s a shopping application, for example, add the element to an array so that you can remember what the user wants to purchase. In this example, I simply changed the text of the target to indicate that the element has been dropped.
5. Use ui.draggable to gain access to the element that was dropped.
The ui object contains information about the user interface. The ui.draggable attribute is a link to the draggable element that triggered the current function. It’s a jQuery element, so you can use whatever jQuery methods you want on it. In this case, I extract the text from the draggable element and append it to the end of the target’s text.

Dropping out can be fun

Another function is used to handle the dropout condition, which occurs when draggable elements are no longer sitting on the target. I bound the resetTarget function to this event:
tmp16338_thumb_thumb
1. Remove the highlight class from the target.
The theme classes are easily removed. Remove the highlight class and the target reverts to its original appearance.
2. Reset the HTML text.
Now that the target is empty, reset its HTML so that it prompts the user to drop a new element.

Cloning the elements

You can simply run the program as-is (with a single copy of the dragMe class), but drag-and-drop is more often used with a number of elements. For example, you might allow users to drag various icons from your catalog to a shopping cart. The basic jQuery library provides all the functionality necessary to make as many copies of an element as you want. Copying an element is a simple matter of using the jQuery clone() method. The more elaborate code is used to ensure that the various elements display properly:
tmp16339_thumb_thumb

To build multiple copies of the draggable element, follow these steps:

1. Create a for loop.
Any time you’re doing something repetitive, a for loop is a likely tool for the job. To make four clones numbered 1 through 4, as shown in the example, you name a variable I, which varies from 1 to 4.
2. Create a zValue variable for the element.
The CSS zIndex property is used to indicate the overlapping of elements. Higher values appear to be closer to the user. In the example, I gave each element a zOrder of over 100, to ensure that each element appears over the target. (If you don’t specify zIndex, dragged elements might be placed under the target and become invisible. The zValue variable is mapped to zIndex.)
3. Determine the Y position of the element.
I want each successive copy of the dragMe element to be a bit lower than the previous one. Multiplying i by 20 ensures that each element is separated from the previous one by 20 pixels. Add 100 pixels to move the new stack of elements near the original.
4. Make a clone of the first element.
Use the clone() method to make a clone of the first div. (Use the :first filter to specify which div you want to copy.)
5. Remember to insert the newly cloned element.
The cloned element exists only in memory until it’s added somehow to the page. I chose to add the element right after the first element.
6. Set the top of the element with the yPos variable.
Use the yPos variable you calculated earlier in this function to set the vertical position of the newly minted element. Use the css() method to apply the yPos variable to the element’s left CSS rule.
7. Set zIndex.
As with the y position, the zValue variable you created is mapped to a CSS value. In this case, zValue is mapped to the zIndex property.
8. Add the index to the element’s text.
Use the append() method to add the value of i to the element’s HTML. This way, you can tell which element is which.

Next post:

Previous post: