Chapter 5. Adding interaction to your interfaces
This chapter covers
- Building drag-and-drop interactions
- Sorting items in a list
- Resizing and selecting elements
- Building touch-friendly interactions
jQuery UI provides two types of widgets: the themeable widgets you’ve spent the last two chapters on, and a set of mouse-based widgets collectively known as interactions. Rather than changing the appearance of DOM elements, interactions let you perform various actions on DOM elements using the mouse. Applying the draggable widget to a DOM element, for example, lets the user drag the element around the screen using the mouse.
Despite being a different type of widget, interactions are still widgets implemented using the widget factory. The same conventions for options, methods, and events that you’ve learned still apply.
These mouse-based interactions are powerful tools when building interfaces. Suppose you need users to rank five movies from best to worst in a web form. You could provide text boxes to let users manually type in the rankings, but it’s far easier—and more intuitive—to use the mouse to rearrange the movies. The sortable widget makes this interaction possible.
One major limitation of these interactions is that they don’t currently support touch events; by default, the examples presented in this chapter don’t work on iOS or Android devices. We’ll explain why, and then look at a workaround to get touch events working in jQuery UI right now.
Let’s begin our look at the jQuery UI interactions with the most commonly used one: draggable.
Draggable elements are ubiquitous in modern computer interfaces. Your OS of choice undoubtedly lets you drag files to move them around in the filesystem.
Although draggable interfaces are common, implementing them on the web still isn’t easy. The HTML5 specification includes a draggable attribute that has now been implemented in all desktop browsers. Although the draggable attribute is great for dragging an element around the screen, it—like many native HTML5 features—suffers from limited customizability and extensibility.
The draggable widget shines because it makes it easy to perform complex interactions. To show how, let’s build a few. Because interactions are widgets, they follow the same initialization conventions you’ve learned. The following code creates a red box you can drag around the screen:
First of all, it’s pretty cool that one line of JavaScript is all you need to make an element draggable. But you can do more. The following code makes two draggables—one that can be moved only on the x-axis, and one that can be moved only on the y-axis:
It’s powerful to see what you can do with a small amount of code. Let’s look at one more example. Another common use case for draggable elements is constraining the area in which they’re draggable. The draggable element makes this easy to implement with the containment option, as shown in the following code:

Here, because the containment option is set to "parent", the draggable widget automatically prevents the draggable element from leaving its parent’s boundaries. This behavior is shown in figure 5.1.
Tip
The containment option also accepts a DOM element, the strings "parent", "document", and "window"—and even an array of coordinates in the document, such as in the form of ( x1, y1, x2, y2 ). For more details, see http://api.jqueryui.com/draggable/#option-containment.
There’s more to draggable than this, but before we delve too deep into draggable functionality, we need to introduce its sister widget: droppable.
Most UIs that use draggables also use droppables. Consider the OS’s file interface. When you start dragging files, you can move them to alternate directories, move them to the trash bin, move them to other applications, and more.
The jQuery UI droppable widget makes it seamless to create drop targets for draggable widgets. As a short example, the following code has two <div> elements, the first of which is turned into a draggable widget and the second into a droppable widget. A drop event is fired whenever a draggable is dropped onto a droppable. You use a drop event callback to change the droppable’s background to red, indicating that a drop occurred:

That’s all there is to detecting a drop. The widget handles all the complex mouse events and collision detection for you. Although this example shows what you can accomplish with a small amount of code, chances are you’ll need to build something more complex than a box that turns red. To build something more useful, and to show off what draggable and droppable make possible, let’s build something fun—a game.
Although drag and drop has many applications, one of the most prominent is in games. Dragging and dropping items on the screen builds a far more user-friendly experience than interacting with a series of form controls.
For the purpose of this example, let’s suppose you’re a company that develops web games for children. You’ll build a game in which kids have to match colors to words (matching a blue box to the word blue). Figure 5.2 shows the game you’ll build.
Figure 5.2. A game where children must match the colored boxes on the left to the word boxes on the right. To implement this, you convert the colored boxes to draggable widgets and the word boxes to droppable widgets.

The source for this example is shown in the following listing. Don’t worry about the details; we’ll go over each part individually.
Note
Some of the visual CSS is omitted from this example for clarity. You can check out the full source and play with this example live at http://jsfiddle.net/tj_vantoll/S7pdy/.

This first thing to note in this example is the list of colors . To ensure all games are different, you define a randomize() function that sorts this array in a random order.
Next, for each color in your array, you create a new <div> and set its id and background to that color, such as <div id="red" style="background: red;">. You then append the newly created <div> to the colors container (<div id="colors">) and convert it to a draggable widget .
In doing so, you set two options: revert to false and zIndex to 2. The zIndex option controls the zIndex CSS property applied to the element being dragged. By setting it to 2, you ensure that the dragged element always displays on top of all other elements (because no elements have zIndex rules applied).
The revert option controls whether a draggable element returns to its starting position when dragging stops. When set to false (the default), the element never reverts; when set to true, it always reverts. You set it to "invalid"—which means the draggable reverts when not dropped on a droppable. This behavior is advantageous for your game, as the reversion provides visual feedback to the user that the selection was invalid.
Tip
You can control the duration of the revert animation using the revertDuration option. If you were to set revertDuration to 2000, invalid draggable elements would take two full seconds to return to their starting positions.
Now that you’ve created the draggables, you have to create the droppable areas. You again randomize the list of colors . If you didn’t do this, the draggables would always be aligned with their appropriate droppable, which wouldn’t be much of a challenge for your users!
After this, you again create a new <div> for each color. This time, though, you append the newly created elements to the drop zone container (<div id="drop-zones">) and set each color as their text .
The last step is to convert these new drop zones to droppable widgets. You set an accept option and a drop event callback. The droppable widget’s accept option controls which draggable widgets should be accepted. It supports two types of arguments. The first is a CSS selector—for example, "*" allows all draggables and "#foo" only allows draggables with an id of "foo". The second, and the one you use , is a function that must return a Boolean indicating whether the draggable should be accepted. Your version is shown here:
The context of the accept option (this) is set to the droppable element and is passed the draggable element as an argument. Recall that you set both the content of the droppables and the id of the draggables equal to the color’s name. With that in mind, this function is saying, “when the text of the droppable matches the id of the draggable, the draggable should be accepted; otherwise, it should be rejected.”
Because the accept option enforces the color section, your drop event is called only after the user makes valid selections. The drop event’s ui parameter contains a reference to the draggable object in its draggable property. You grab the background-color from the draggable element and set it as the background of the droppable one as shown in the following code and at . A "filled" class name is also added; you’ll use that later to determine when the game is complete:
Note
The background change gives the user a visual indication that the drop was successful, and because it was, you also no longer need the draggable. Therefore, you hide it :
You use one of the jQuery UI effects—puff—to add a small effect that makes the draggable grow slightly as it fades away. We’ll look more at how these effects can be configured in chapter 6.
The last thing you need to do is determine when the game is complete. Recall that you added a "filled" class name to each droppable in the drop event. Therefore, when the number of filled droppables matches the number of colors ($( ".filled" ).length === colors.length), the game is complete. At this point you show the user a congratulatory message then refresh the page to restart the game.
And with that, you have a fully functional matching game! Although there’s a decent amount of code here, think about all the code the draggable and droppable widgets save you. You didn’t have to write any code to implement dragging, detect collisions, or animate the draggables on invalid selections. Also, because you wrote this in a manner that looped over the colors, it’s easy to alter the number of colors in this game to adjust the difficulty level. Try adding to the colors array, and note how the game still functions fine.
Although this is cool, you may be “I don’t build children’s games; how is this useful to me?” Dragging and dropping elements has all sorts of practical use cases, including a common feature on most e-commerce sites: the shopping cart.
If you’ve ever shopped online, you’ve almost certainly used a shopping cart. In this section, let’s imagine that you need to build an online shopping cart for a local grocery store. Due to the nature of grocery shopping, users tend to end up with a nontrivial number of items in their cart. Due to the number of transactions, you want to give the user an easy and intuitive way to add items. Therefore, you’ll add a twist to the normal online shopping cart experience and let the users drag and drop available items to their cart.
We’ll use this cart to explain a few more of the common configuration options in the draggable and droppable widgets. Figure 5.3 shows the cart that you’ll build with the draggable helper and cursor options annotated.
The following listing shows the implementation of the shopping cart.
Note
A live demo of this example is available at http://jsfiddle.net/tj_vantoll/PUVXn/
.

You use CSS to position the cart in the top-right corner of the screen and the list of grocery items on the left. In JavaScript, you convert the items to draggable widgets and the cart to a droppable widget.
When converting the grocery list items to draggables, the first option you set is the cursor option to "move" . This tells the widget to set the CSS cursor property to "move" while the draggable is dragged by the user. Although the cursor property has many potential values (see https://developer.mozilla.org/en-US/docs/Web/CSS/cursor for a list), "move" is the most appropriate choice for draggable elements. Because the cursor option only determines the cursor during a move, you also set { cursor: move; } on #items li in CSS. This provides the move cursor for users when they hover before they begin dragging. Setting these properties is important as the cursor change helps the user discover that the element in question can be dragged.
Next, you set the revert option to "invalid" as you did in the previous example. This is a common selection as it provides feedback to users that they missed the intended target.
Last, you set the helper option, which controls the element that the user drags. By default, helper is set to "original", which means the element converted to a draggable widget is used as the helper. You used this behavior in your matching game in the previous section. But in this case, you want to give the user the ability to drop multiple items of the same type in the cart; therefore, you leave the original draggable element in place. When the helper option is set to "clone" , the draggable widget automatically clones the draggable when a drag starts, and removes the clone after a drag completes.
Tip
You can also pass a function for the helper option that returns a DOM element to use as a helper while dragging. This is useful when the original element is large or complex, and you only want to show a simplified representation while dragging.
Now that the items are draggables, you need to turn the cart into a droppable widget. The first two options you set are activeClass to "active" and hoverClass to "hover"
. These options represent CSS class names to apply to the droppable element whenever an acceptable draggable is being dragged or hovered over the droppable, respectively. In this case, because you didn’t specify an accept option, all draggable elements are considered acceptable. Like the cursor option, you use these class names to provide feedback to users. The display of the cart name under the various states is shown in figure 5.4.
If the feedback provided by these class names is so important, why didn’t you use it in the matching game? Because activeClass and hoverClass apply class names only to acceptable droppables, they would affect only the correct color droppable in the matching game. Styling with these options would give away the correct answer!
The last option you set is tolerance , which determines which algorithm the widgets should use for determining whether a draggable is indeed over a droppable. It has four possible values:
- "fit" —Drop is valid if the draggable overlaps the droppable completely.
- "intersect" —Drop is valid if the draggable overlaps the droppable by at least 50% vertically and horizontally. This is the default setting.
- "pointer" —Drop is valid if the mouse cursor is over the droppable.
- "touch" —Drop is valid if the draggable overlaps the droppable in any amount.
For your cart you want to make it as easy as possible for users to add items, so you set tolerance to the most permissive value: "touch".
And that’s it for this example. In a few lines of code, you created a simple drag-and-drop shopping cart. Because it requires so little code, this functionality can easily be added to just about any existing shopping cart application.
With that, our look at the draggable and droppable widgets is complete, but we’re just getting started with jQuery UI interactions. Next, we’ll look at a close relative of the draggable and droppable widgets: sortable.
One of the more common applications of draggable interfaces is the ability to sort items in a list. Although common, the sortable interaction is shockingly difficult to implement. You have to implement the logic to enable the mouse events for dragging, and then the collision detection from droppable, and then you need to reposition the items in the list to account for the rearranged list. Because of this, the sortable widget is the most complex widget in jQuery UI.
Fortunately, this complexity has all been abstracted to an easy-to-use widget. To create sortables, you call the plugin on an unordered list:
That’s all it takes to make the items in a list sortable by the user.
Tip
Although <ul> elements are the most common, you can turn any element into a sortable widget. The widget element’s immediate children are converted to sortable items. This can be customized using the items option.
This interaction leads to all sorts of possibilities. Recall your movie site that you worked on in the last chapter. Let’s suppose that the owners of this site contact you with a new feature in mind. They want to conduct a poll and have their users rank five popular movies from best to worst.
Think for a moment about how you’d implement this. Radio buttons are often used for polls, but they can gather only one selection, not capture the order of five items. You could use text boxes, but that’s not user friendly. Let’s see how you can build this poll using the sortable widget.
Figure 5.5 shows the poll that you’ll build.
Figure 5.5. A poll that asks users to rank five movies from best to worst. The poll is implemented with the sortable widget; meaning, the user can rearrange movies with the mouse.

The implementation of this poll is shown in the following listing.
Note
Some visual CSS is not shown in the listing. The full source is available online at http://jsfiddle.net/tj_vantoll/5N6h9/.

You start with a list of movies that you rearrange in a random order . You do this so the initial ordering of the list doesn’t influence your users’s selections.
Next you set one of the sortable’s most common options: placeholder . While a sortable item is being dragged, the sortable widget adds a filler element to the list. The sortable adds the filler where the item would be if it were dropped. This filler element is known as a placeholder and is far easier to show in a picture. Figure 5.6 shows the display of the placeholder during a sort.
The placeholder option specifies a class name to apply to this element so it can be styled with CSS. In your example you apply a movie-placeholder class name with an associated border: 1px dotted black CSS rule so your placeholder in figure 5.6 displays with a dotted border.
The last thing you do is attach a click event handler to your Submit button to gather the results. In the handler, you loop over each list item sequentially ($( "#movies li" ).each( ... )) and push each item’s innerHTML—which is the name of the movie—to an array. At the end of the handler, you alert the user to show the results were collected successfully . In a more realistic scenario, you’d send this data to a server that would aggregate these rankings and show the totals to the user.
This example shows how to use the sortable widget to build a practical UI control with a limited amount of code. Think of how painful and user unfriendly it would be to build a ranking control with regular HTML form elements. Next, we’ll show a more powerful use of the sortable widget: connecting multiple lists.
Draggable vs. sortable
Even though much of the functionality is the same, the draggable and sortable widgets are not dependent on each other; but they do share a similar API. The sortable widget uses the following options that are also in draggable: axis, cancel, containment, cursor, cursorAt, delay, disabled, distance, grid, handle, helper, opacity, revert, scroll, scrollSensitivity, scrollSpeed, and zIndex.
The sortable widget’s tolerance option is similar to the droppable widget’s; however, droppable offers four choices—"fit", "intersect", "pointer", and "touch"; sortable offers only "intersect" and "pointer".
A common requirement of sortable lists is to connect multiple lists to each other. Consider a scheduling application where people or supplies need to be divided into multiple groups, or a to-do app that lets users move items from To Do to Done (and, unfortunately, vice versa). The jQuery UI sortable widget makes it easy to connect lists with the connectWith option.
To show how to do this, let’s build another children’s game with a different twist. This time you’ll present the user with two lists with mismatched items—in this case, fruits and vegetables. The user’s job is to move each item to the appropriate list.
To start, you create lists and connect them with the connectWith option. The following example builds two connected lists:
The connectWith option takes a selector of sortable elements that the current list should be connected to. Therefore, $( "ul" ).sortable({ connectWith: "ul" }) converts all <ul> elements to sortable widgets and connects them all. The user can then drag items from the fruits list to the vegetables list and vice versa. Let’s see how you can take this basic functionality and turn it into a complete game.
To create a game, you need to do more than build lists. You need to validate the correctness of the lists, and ideally add a bit of randomness so the user isn’t playing the same game every time. The sortable widget gives you the hooks to make this possible.
As with previous examples, we’ll show an implementation of the game, and then walk through it step by step. Figure 5.7 shows the display of the game, and the implementation is shown in listing 5.4.
Figure 5.7. A fruit and vegetable sorting game implemented with the sortable widget. The user must move all fruits into the fruits list and all vegetables into the vegetables list to win.

Note
The CSS for this example is omitted here for brevity. You can view it in the book’s downloadable code samples, or view this example live at http://jsfiddle.net/tj_vantoll/nCjwc/.

You start with an array of fruits and vegetables, and loop over them to create the sortable items. You wrap the addition of each fruit and vegetable with a Math.random()< 0.6 call . Because Math.random() returns a number between 0 and 1, each fruit and vegetable is present in the game 60% of the time. This adds randomness so that users aren’t bored after their first play.
For each fruit and vegetable that passes your check, you then create a list item as shown in the following code :
Two interesting things are going on here. First, you store the type of the list item (fruit or vegetable) in a data-type attribute. You use that later when you verify that the user’s selections are correct. Next, you call Math.random() again. Because this call uses 0.5, there’s a 50% chance you’ll append this new list item to the fruits list and a 50% chance you’ll append it to the vegetables list.
Now that the lists are populated, you turn them into widgets. The cursor and placeholder options should look familiar from the previous example, but the helper option is new. Whenever a drag starts on a sortable item, the element being dragged is referred to as a helper element, and is given a class name of ui-sortable-helper for styling purposes. By default, the helper is the sortable element itself, which corresponds to a helper option of "original". The helper option also accepts "clone", which clones the element and uses it as a helper, or a function that returns a new element to use as a helper. In this example, you use this option and create a new helper <div> :
Why did you do this? Because these sortable elements are <li> elements, by default they’re displayed with bullets next to them in the list—for example, • Banana. Dragging an element with the bullet looks a little odd, and creating a new <div> to use as a helper works around this.
Note
A cleaner solution would’ve been to apply list-style-type: none to the ui-sortable-helper class name in CSS. But the function-based helper works just as well and serves as a nice introduction to the option.
You’ve now completed all setup needed for the game, so the last thing to do is to check when the user has successfully sorted all items. The sortable widget’s stop event is called when any sort completes; it’s the perfect place to check whether the user has finished . The implementation of this check is in the isValid() function, which you call immediately. Don’t worry too much about the implementation of isValid(). All it does is use the data-type attribute you set on each list item to determine whether all items are in the correct list. If isValid() returns true, you display a confirmation dialog to the user and refresh the page to start a new game.
With that, you have a functioning sorting game in a few dozen lines of JavaScript. Think about how hard this would’ve been to set up without any help from jQuery UI. You’d have to recreate the draggable items, the collision detection, helper and placeholder management, and more. It’s no wonder the sortable widget is the most complex widget in the library.
Building sortable tables
One little-known feature of the sortable widget is that you can use it to make table rows sortable. There’s one small caveat, though: you need to convert the table’s <tbody> to a sortable widget rather than the <table> itself, as shown in the following code:
Let’s move on to another common, yet tricky, interaction that jQuery UI makes easy: resizing elements.
Resizable elements are another common desktop interaction. Resizable elements have two use cases. The first is to give the user control over the size of the display. Consider the windows in a desktop OS; users can change the size of each individual window to meet their needs. The other use case for resizable elements is to add additional functionality. Most calendar applications, as an example, let you resize entries to increase the duration of an appointment in either direction.
The jQuery UI resizable widget makes it easy to create resizable elements on the web, with several options that make advanced and tricky use cases possible. Like all the jQuery UI widgets, to create a resizable element you invoke the widget’s plugin. The following code creates a resizable <div>:
This displays as shown in figure 5.8.
Figure 5.8. A 100 × 100 <div> element converted to a resizable widget. By default the element can be resized to the south, east, and southeast.

The resizable widget automatically adds an icon to the bottom right-hand side of the element. By default, resizable elements can be resized to the south, east, and southeast. The handles option lets you configure this behavior.
Tip
If the icon in the bottom corner is undesirable, you can remove it by adding .ui-resizable-se { background: none; }. After you do this, the functionality remains, but the icon is gone.
The handles option is set to "e, s, se" by default, which explains the behavior you see. You can set the option to a comma-delimited string containing any of the following in any order: n, e, s, w, ne, se, sw, nw. You can also pass the string "all" to make an element that can be resized in any direction. The handles are shown in figure 5.9.
Figure 5.9. The resizable widget lets you configure the directions the element can be resized with the handles option. The eight potential handles are shown on an element. The handles option also accepts "all", which uses all eight handles.

The final version of the handles option lets you specify your own DOM elements to use as the handles. This allows you to build custom resizable interactions. Figure 5.10 shows a resizable element with a custom east handle.
Figure 5.10. A resizable element with a custom resizing handle on its east side. You build this by explicitly providing markup for the east handle, as shown in listing 5.5.

The following listing shows the code used to build this element.

The first thing to notice here is the class names on your custom handle . The resizable widget requires that a custom handle have class names ui-resizable-handle and ui-resizable-{direction}—in this case, ui-resizable-e.
To tell the resizable widget about your custom handle, you pass an object in as the handles option . The keys of the object are the directions in which the user can resize. In this case, you specify "e" because the user should only be able to resize to the east. The value of each handle can be a selector that matches a child element of the resizable element, a DOM element, or a jQuery object. In this case, your handle is a child of the resizable element, so you pass a selector that matches it.
As a last step, you set the minWidth option to 50 . This prevents the user from resizing the element to a size smaller than 50 pixels. The resizable widget also provides maxWidth, minHeight, and maxHeight options for similar constraining functionality.
With custom handles you can build a highly customized display for your resizable controls. To see at what the resizable widget makes possible, let’s look at a common use of resizable UI elements: a calendar control.
Most desktop calendar programs give you the ability to drag and resize appointments using the mouse. Although writing a full-featured web-based scheduler is a complex topic well out of the scope of this book, let’s look at how the resizable and draggable widgets make building the grid portion of the calendar easy. Figure 5.11 shows the calendar grid you’ll build.
Figure 5.11. A scheduler for creating appointments. The black box represents an appointment, and the vertical lines represent half-hour time slots. The user can drag the appointment to different days and times—and resize the appointment to change its length.

In this grid the black box represents an appointment and each column represents a day of the workweek. The vertical gray lines are spaced 50 pixels apart and are used to represent half-hour time slots. To build this scheduler, suppose you have the following requirements:
- The appointment can resize only in the north and south directions.
- The appointment can resize only in certain intervals, corresponding to a half hour (50 pixels).
- Appointments can be dragged anywhere within a day or into other days.
- The appointment can’t be dragged or resized outside of the calendar.
Consider how tricky these requirements are to meet without the help of any widgets or plugins. With the jQuery UI interactions, you can meet these requirements with nine lines of JavaScript! The following listing shows an implementation of this grid.
Note
This example is available online at http://jsfiddle.net/tj_vantoll/yUs44/.

Warning
The grid lines are drawn using CSS gradients. Although most browsers now support CSS gradients, they’re not supported in Internet Explorer versions 9 and earlier. In these browsers, the grid doesn’t appear. For a full list of browsers that support CSS gradients, see http://caniuse.com/#feat=css-gradients. For more information on how this grid works, as well as how to create other cool patterns with CSS gradients, see http://lea.verou.me/2010/12/checkered-stripes-other-background-patterns-with-css3-gradients/.
Let’s look at how this example meets all your criteria. First, by setting the appointment’s handles option to "n, s" , you enforce the requirement that the resizable element can only be resized vertically, not horizontally or diagonally.
Your next criterion was to allow the user to resize the appointment only in a set interval. You want to let the user resize appointments by the hour or half hour, rather than by minutes or seconds.
To implement this, you use the resizable widget’s grid option . The grid option takes an array of pixels, with the x and y values as the resizing increments. The x value of the array is irrelevant, as the user can’t resize the appointment horizontally. By setting the y value to 50, the resizable widget allows the appointment’s height to be changed only by increments of 50 pixels—50 pixels, 100 pixels, 150 pixels, and so on—which corresponds to half hours, per the example’s convention.
Next, you prevent the user from resizing an appointment outside of the calendar itself. This is easy as the resizable widget has the same containment option as the draggable widget. By setting containment to "parent", the resizable widget automatically contains all resizing actions in its parent widget—the calendar . As with the draggable widget, the resizable widget’s containment option can also be set to a selector or a DOM element to contain the element within.
This takes care of your resizable criteria. Next, you make the appointment draggable .
Tip
A DOM element can be initialized with multiple widgets. Although some combinations make no sense—for instance, an element that’s a dialog and a datepicker—some, such as draggable and resizable, can be quite useful.
To keep draggable in sync with resizable, you also set the draggable grid option. Unlike resizable, the x value of the grid is relevant here, as you want to let the user drag appointments horizontally to different columns. You specify an x value equal to the width of the columns: 100. For the y value, you use the same value as resizable (50) so the user can drag appointments to reschedule by the half hour.
That’s all there is to it. You built a powerful appointment scheduler that met your criteria with a few lines of configuration for the draggable and resizable widgets. This brings us to the last of the jQuery UI interactions: selectable.
Dialog, resizable, and draggable
Whether or not you realized it, you saw the draggable and resizable widgets in action before this chapter. The dialog widget uses these interactions to make dialog elements draggable and resizable by default. Whether dialog elements are draggable and resizable can be configured using the draggable and resizable options, respectively. The following code shows how to create a dialog that’s neither draggable nor resizable:
Selectable elements should be familiar to anyone who has used a file browser GUI in any OS. Almost invariably the OS lets you select a file by clicking on it, select additional files by clicking with a modifier key held down (Control on Windows, Command on OS X), and select multiple files simultaneously by dragging your mouse to create a box or lasso.
The jQuery UI selectable widget brings this paradigm to the web. Selectable is one of the simplest widgets of jQuery UI. Although it has options, methods, and events like other widgets, for the vast majority of use cases the default behavior is all you need. Therefore, we’ll only be looking at a single example that replicates the file GUI behavior in the browser.
Like sortable, when the selectable’s plugin is called on an element, its immediate children are converted to selectable items. The following code converts a list to a selectable widget:
Although this does create a selectable widget, it gives no visual indication of what files are selected. This is because instead of styling the selectable elements directly, the widget adds CSS class names to the appropriate items and the author is responsible for styling them. The following four class names are applied by the selectable widget:
- ui-selectee —Applied to all selectable elements, regardless of state
- ui-selecting —Applied to elements selected by the lasso before the user releases the mouse
- ui-selected —Applied to selected elements
- ui-selectable-helper —Applied to the lasso created by the mouse
To see how these class names work, you’ll add a little CSS to your example. You’ll also add a Remove button to make the example a bit more useful. Figure 5.12 shows the updated display of your example.
Figure 5.12. A browser representation of an OS’s file GUI implemented with the selectable widget. The user can add new files and remove any selected files. The selectable widget’s helper is styled with a dotted line, and files selected with the lasso are styled with a background in color.

The following listing shows the final code of this example.
Note
Some CSS is omitted from this example to focus on the selectable interaction. You can view the full source and play with this example at http://jsfiddle.net/tj_vantoll/Bd57U/.
You style selectables as hot pink during mouse selection and red with white text after they have been selected
. You don’t touch the ui-sortable-helper class name, leaving it as its default display defined by the widget (border: 1px dotted black).
After creating the selectable widget, you convert the Add button to a button widget and attach a click handler to it. The click event handler adds a new <li> element to the list —and that’s it. There’s no refresh() method call or any call that tells the widget of the new element. How does the widget know that a new element was added?
The selectable widget is unique because it checks for new elements in the list whenever a select operation begins. Because this is a potentially expensive operation, the widget exposes an autoRefresh option that you can set to false to disable it. If you set autoRefresh to false, the widget has a refresh() method you can call after adding and removing elements. Because you have only a handful of items here, it makes sense to leave autoRefresh set to true.
The last thing you do is convert the Remove button to a button widget and attach a click event handler to it as well. In the click handler, you select all elements with the ui-selectable-selected class name and remove them from the DOM .
If you run this example, you’ll notice that you can perform all the actions that you’re used to with a desktop OS with this small amount of code.
Before we end our discussion of jQuery UI interactions, there’s one last thing we need to discuss. If you’ve happened to test any of the examples in this chapter to this point on an iOS or Android device, you may have noticed that they don’t work. In the next section we’ll discuss why that is, and what you can do to make them work.
Unless you have been living under a log, you’re likely aware of the mobile explosion that has taken the web development industry by storm. Despite this, the latest release of jQuery UI still doesn’t support touch events out of the box.
Why is this?
The answer is complicated and requires a short history lesson. In 2007 the iPhone was released and with it came touch events: a new event model for handling interactions on the web. Android soon followed with an implementation, and Firefox for Android, Chrome for Android, BlackBerry, and Opera Mobile would soon follow as well.
Despite the number of implementations, Apple’s model has two major problems. First, it forces web developers to explicitly handle two types of events: mouse-based ones and touch-based ones. Unfortunately, the two event models have subtle differences that make this a nontrivial task.
The second issue is that Apple owns a number of patents related to its touch event implementation. These patents have (thus far) prevented touch events from becoming a W3C standard.
Because of these issues, the Internet Explorer team came up with a new approach known as pointer events, which shipped in Internet Explorer 10. Microsoft submitted this model to the W3C, and it’s now a candidate recommendation spec—http://www.w3.org/TR/pointerevents/.
Note
The candidate recommendation status means that the major features of the spec are locked down and the spec authors are waiting for feedback on the finer points before the spec enters its next state: proposed recommendation.
The pointer event model addresses the single largest problem with the touch event model: it handles multiple input types. If you’re on a Windows touch screen tablet, you can handle mouse, touch, and stylus-based input, all with a single set of pointer events.
The jQuery UI team feels this model is the best way to move forward with events on the web; the team is currently working with others to create a polyfill of pointer events for browsers that don’t natively support them, which will make the interactions work on any device. Expect it to be included in the library in a future release of jQuery UI.
Note
You can read a more thorough history of touch events at http://blog.jquery.com/2012/04/10/getting-touchy-about-patents/.
Although this history lesson provides background, you’re likely interested in getting the jQuery UI widgets to work for you now. Fortunately, there’s a quick workaround to make that possible.
jQuery UI Touch Punch is a tiny script that adds touch event support to all the jQuery UI widgets. It listens for touch events, then uses a DOM specification known as custom events to fire the corresponding mouse events that the jQuery UI widgets are looking for.
Tip
Custom events allow you to trigger native events (click, keypress, mousemove, touchstart, and so on) as if the user had taken that action. To read more about custom events, see https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Events/Creating_and_triggering_events.
What’s nice about Touch Punch is it requires no configuration to make it work. You download Touch Punch’s script from http://touchpunch.furf.com/ and include it after jquery-ui:
That’s it. This approach adds touch support for the jQuery UI widgets in any browser that supports the touch event model (iOS Safari, Android, Chrome for Android, Firefox for Android, Opera Mobile, and BlackBerry).
Although having to include an external plugin isn’t ideal, Touch Punch provides an elegant stopgap solution until true pointer event support is released in jQuery UI.
Interactions on Windows 8 touch devices
Even though the jQuery UI interactions do not support pointer events, as of version 1.11, the interactions do support Windows 8 touch devices running Internet Explorer 10 and Internet Explorer 11. How? When you apply an interaction widget to an element, the widget sets the element’s touch-action CSS property to "none", which makes Internet Explorer 10+ fire the mouse events that make the interactions work—even on touch screens. You can read more about what the touch-action property does at http://msdn.microsoft.com/en-us/library/windows/apps/hh767313.aspx.
To summarize, the jQuery UI interactions work in all desktop browsers, as well as Windows 8 devices. The interactions do not work on mobile browsers that use the touch event model, but you can use Touch Punch to add support for those browsers. Between the two you get comprehensive device coverage.
In this chapter, you looked at the five interaction widgets provided by jQuery UI. You used them to create a number of practical UIs—from children’s games to a shopping cart to an appointment scheduler.
Currently, these interactions don’t work on mobile browsers that use the touch event model, such as iOS Safari and Chrome for Android. The jQuery UI team is working on creating a polyfill for pointer events that will bring support to all browsers, but in the meantime, you can use jQuery UI Touch Punch to make sure the interactions work on all devices today.
With this chapter, we’ve now completed our look at all the jQuery UI widgets. Although we’ll continue to explore the inner workings of widgets throughout the book, for now we’ll switch our focus to the jQuery UI animation components, collectively known as effects.