jQuery effects and plug-ins
After completing this chapter, you will be able to
■
■ Understand how to install jQuery UI.
■
■ See how to create a sample jQuery UI page.
You’ve seen how jQuery is used to help JavaScript programming by alleviating many of the mun- dane tasks and helping to make some of the more difficult tasks easy. jQuery has a strong and active plug-in community as well. These plug-ins work alongside jQuery to provide specialized functional- ity to help solve specific problems. For example, there are plug-ins for helping with form validation, plug-ins for photo slide shows, and plug-ins to create enhanced visual effects. It’s the enhanced visual effects that will be the focus of this chapter. The jQuery UI plug-in will be examined in this chapter.
Installing jQuery UI
jQuery UI is a set of customizable JavaScript and CSS files that enable advanced visual and behavioral effects on a webpage. Using jQuery UI, you can create enhanced drag-and-drop-like effects, sliders, and much more, all through an interface that operates just like other jQuery functions.
Because jQuery UI is a set of JavaScript and CSS files, installing it is a bit more involved than just installing jQuery, which is a single JavaScript file. That said, the installation is still relatively easy, and in this section you’ll see just how to do it.
Obtaining jQuery Ui
jQuery UI is downloaded from http://jqueryui.com. At the jQuery UI home page, you’ll see a link to download. Inside that link you have the opportunity to build a custom download. You’d do this so
choosing a theme (UI Lightness will be the theme used in this chapter), and selecting Download.
When you do so, the jQuery UI site will build a zip file containing the effects and widgets that you’ve specified, along with the theme that you specified.
installing jQuery Ui
Unzipping the downloaded file reveals three folders: css, development-bundle, and js. The CSS files for jQuery UI are included in the css folder, and the JavaScript, including a version of jQuery itself, is included in the js folder. The development-bundle folder contains samples, documentation, and other ancillary files for jQuery UI. When deploying jQuery UI to a live or production environment, the development-bundle directory doesn’t need to (and probably shouldn’t) be included.
The files for jQuery UI should be placed appropriately on your web server. This means that you place them in your document root or within your project. For example, Figure 17-1 shows the folder hierarchy for the default download of jQuery UI.
FIGURE 17-1 The folders within the jQuery UI download.
Adding the appropriate directories and files to a project in Microsoft Visual Studio typically involves the following steps:
1. Right-click within Solution Explorer, select Add, and then select Existing Item.
2. In the Add Existing Item dialog box, navigate to the file (for example, the jQuery or jQuery UI file) and select Add. You might need to select Script or All Files from the file type drop-down to see the appropriate file types.
3. Select the js and css folders to add all the files.
Building a jQuery Ui demonstration page
jQuery UI has a number of different effects, widgets, and interface enhancements—enough that it’s difficult to try to describe all of them in words. It’s more effective to show you how to build a dem- onstration page that enables you to experiment with the various things that jQuery UI can do. The index. html page included with jQuery UI provides a good sample page as well, but implementing one for yourself will help you to learn the structure and usage pattern for jQuery UI.
With that in mind, the following exercise helps build a jQuery UI demonstration page. To com- plete this exercise, you should already have jQuery UI installed. This exercise assumes that jQuery and jQuery UI are installed in the js folder within your current folder or project and that the jQuery UI CSS is installed in a css folder within your current folder or project.
Building a demonstration page
1. Within Visual Studio, Eclipse, or another editor, open the file test.html in the Chapter17 com- panion content.
2. Inside test.html, add the code shown in bold, noting particularly to change the version num- bers of jQuery UI’s css and js file and the main jQuery JavaScript file’s version, too.
<!DOCTYPE html>
<html>
<head>
<title>jQuery UI Test Page</title>
<link type="text/css" rel="stylesheet"
href="css/ui-lightness/jquery-ui-1.8.22.custom.css" />
<link type="text/css" rel="stylesheet"
href="css/style.css" />
<script type="text/javascript"
src="js/jquery-1.7.2.min.js">
</script>
<script type="text/javascript"
src="js/jquery-ui-1.8.22.custom.min.js">
</script>
<script type="text/javascript"
src="js/custom.js">
</script>
</head>
<body>
<div id="mainContainer">
<div id="mainHeadingContainer">
<div id="header">
<h1>jQuery UI Test Page</h1>
Here's some text!
</div>
</div>
<form action="#" method="POST">
<select name="effect">
<option value="bounce">Bounce</option>
<option value="drop">Drop</option>
<input type="submit" name="submit" value="Run Effect">
<input type="button" name="reset" value="Reset Page">
<span id="trash"></span>
</form>
</div> <!-- end mainContainer -->
</body>
</html>
3. Save test.html.
4. Create a new CSS file. If you’re using an editor or integrated drive electronics (IDE) like Visual Studio that requires you to add a new file to the project, add it within the css folder.
5. Inside the CSS file, place the following contents:
body {
font-family: arial, helvetica, sans-serif;
}
#mainContainer {
border: 3px solid black;
padding: 10px;
}
#mainHeadingContainer { width: 300px;
background: #999999;
text-align: center;
}
#header {
width: 300px;
height: 200px;
background: #CCCCCC;
margin-bottom: 25px;
}
.transfer {
border: 2px solid black;
}
6. Save the file as style.css (within your css folder). This file can be found as style.css in the css folder of the Chapter 17 companion content.
7. Create a new JavaScript file. If you’re using an editor or IDE like Visual Studio that requires you to add a new file to the project, add the file within the js folder.
8. Inside the JavaScript file, place the following JavaScript. This file can also be found as custom.js in the Chapter 17 companion content.
$(document).ready(function () {
$("form").on('submit', function () {
var effect = $(":input[name=effect]").val();
var options = {};
var effectTime = 1000;
if (effect === "transfer") {
options = { to: "#trash", className: "transfer" };
effectTime = 500;
}
$("#header").effect(effect, options, effectTime);
return false;
});
$(":input[name=reset]").on('click', function () { $("#header").removeAttr("style");
});
});
9. Save the file as custom.js in your js folder.
10. View test.html in your browser. You should see a page like that shown here:
11. Use the drop-down menu to select different effects, and note how each interacts with the page.
If you don’t receive the page shown, here are some troubleshooting tips:
■
■ Make sure that you have the right versions of jQuery UI’s CSS and JS files, as well as the correct version of jQuery itself. The version numbers shown in the example will be out of date by the time you read this.
■
■ Make sure the paths to the files are correct. You should have the file test.html in your project or document root, and there should also be a css and js folder in the same directory. Inside the css folder are the jQuery UI CSS files as well as your own style.css created in this exercise.
The js folder contains the main jQuery file as well as the jQuery UI JavaScript file and your
Within the ready() function, a submit event handler was added to the form:
$("form").on('submit', function () {
Within the submit event handler’s function, the name of the effect being requested was obtained using the :input[name=effect] selector’s val() function:
var effect = $(":input[name=effect]").val();
Many of the jQuery UI effects accept options as well as the amount of time (in milliseconds) to perform the effect. These variables are set up next:
var options = {};
var effectTime = 1000;
The “transfer” effect looks better with a quicker effectTime value and requires some additional options, such as the destination for the transfer effect. Therefore, a conditional tests whether the effect was transfer and if it was, the options and effectTime values were set accordingly:
if (effect === "transfer") {
options = { to: "#trash", className: "transfer" };
effectTime = 500;
}
With all the initial setup out of the way, the jQuery UI effect() function is called, using the name of the effect, any options, and the time to run the effect.
$("#header").effect(effect, options, effectTime);
The remaining area within the code sets a click event handler onto the reset button found on the page. This reset button removes any styles applied to the area of the page used by the jQuery UI effect function.
$(":input[name=reset]").on('click', function () { $("#header").removeAttr("style");
});
Creating a jQuery UI calendar
A common widget when building a webpage is a calendar to enable the visitor to select a date rather than having to type the date into the form manually. jQuery UI includes a type of calendar known as a datepicker. The jQuery UI datepicker lets you create a calendar that displays when the visitor clicks within the form field on the page, like the one shown in Figure 17-2.
FIGURE 17-2 A jQuery UI datepicker.
Adding the jQuery UI datepicker is just about as easy as anything you’ll do in JavaScript, assuming that you have jQuery UI and jQuery installed and ready to go. Assume that you have a text field in a form, like this:
<input type="text" name="cal" id="cal">
You turn this input into a datepicker by using one line of jQuery in your JavaScript:
$('#cal').datepicker();
Example 17-1 shows the HTML to create the page shown in Figure 17-2. You can also find this code in the file cal.html in the companion content.
EXAMPLE 17-1 HTML to create a basic datepicker page
<!DOCTYPE html>
<html>
<head>
<title>jQuery UI Datepicker</title>
<link type="text/css" rel="stylesheet"
href="css/ui-lightness/jquery-ui-1.8.22.custom.css" />
<link type="text/css" rel="stylesheet"
src="js/cal.js">
</script>
</head>
<body>
<div id="mainContainer">
<form action="#" method="POST">
<input type="text" name="cal" id="cal">
</form>
</div> <!-- end mainContainer -->
</body>
</html>
The JavaScript used to create the page (saved as cal.js in the js folder) is shown in Example 17-2.
EXAMPLE 17-2 JavaScript to create a datepicker
$(document).ready(function () { $('#cal').datepicker();
});
The CSS, which is really used only to create the border, to make it easier to see in the book, is shown in Example 17-3.
EXAMPLE 17-3 CSS to add a border for the example
#mainContainer {
border: 3px solid black;
padding: 10px;
}
Customizing the calendar
The datepicker widget is highly customizable. You can change the format of the date, show the week of the year, show drop-down lists for the month and year for quicker navigation, show multiple months at once, and much more. Customizations are added by placing options (as an array) within the call to the datepicker function.
This section examines a few of the customizations. For more information about others, see the datepicker demo page at http://jqueryui.com/demos/datepicker/.
adding buttons
You can add buttons for quick access to the current date and also to indicate that the visitor is done choosing a date. This is accomplished with the showButtonPanel option. The JavaScript shown in Example 17-2 to add the showButtonPanel option looks like this (note the addition of opening and closing braces within the datepicker() function):
$('#cal').datepicker({
showButtonPanel: true });
The result is a calendar that looks like Figure 17-3.
FIGURE 17-3 A datepicker with a button panel.
Displaying multiple months
For certain applications, it can be helpful to display multiple months at once. This is accomplished with the numberOfMonths option, which is then further configured to determine the number of months to display.
$('#cal').datepicker({
showButtonPanel: true, numberOfMonths: 2 });
The resulting calendar looks like Figure 17-4.
FIGURE 17-4 A calendar displaying multiple months and buttons.
adding month and year drop-down lists
You can add drop-down lists for the month and/or the year to make navigation across large date ranges easier. This is accomplished with the changeMonth and changeYear options, respectively:
$('#cal').datepicker({
changeMonth: true, changeYear: true });
The resulting calendar looks like Figure 17-5.
FIGURE 17-5 A calendar with drop-down lists for month and year.
Limiting the date range
If you attempt to use the year drop-down list from the previous example, you’ll notice that you can choose dates from 10 years ago. However, calendars are frequently used in forward-looking mode only, where, for example, people can pick a date for a reservation in the future.
You can limit the date range for the calendar, both backward and forward. Doing so is a bit more complex than merely setting an option because you need to choose the date range from a number of formats.
To solve the immediate problem identified, where a date well into the past can be chosen, the minDate option is used with -0D as the option’s value, to exclude dates previous to today. The code looks like this:
$('#cal').datepicker({
changeMonth: true, changeYear: true, minDate: "-0D"
});
The resulting calendar looks just like the one in Figure 17-6. Notice that dates previous to today are no longer available for selection.
FIGURE 17-6 Excluding dates in the past with minDate.
Both the minDate and maxDate options accept values of D to indicate days, M to indicate months, and Y to indicate years. For example, allowing dates beginning with today (as you saw) and no later than one year and one day in the future looks like this:
$('#cal').datepicker({
changeMonth: true, changeYear: true, minDate: "-0D", maxDate: "+1Y +1D"
});
Adding a dialog box
jQuery UI has various dialog boxes available through its dialog() function. The default dialog is an overlaid dialog with a title bar and main window for content. The default dialog is resizable and can
EXAMPLE 17-4 HTML to create a dialog with jQuery UI
<!DOCTYPE html>
<html>
<head>
<title>jQuery UI Dialog</title>
<link type="text/css" rel="stylesheet"
href="css/ui-lightness/jquery-ui-1.8.22.custom.css" />
<script type="text/javascript"
src="js/jquery-1.7.2.min.js">
</script>
<script type="text/javascript"
src="js/jquery-ui-1.8.22.custom.min.js">
</script>
<script type="text/javascript"
src="js/dialog.js">
</script>
</head>
<body>
<div id="dialog" title="My Dialog">
<p>Here's a dialog</p>
</div>
</body>
</html>
The JavaScript used to create the dialog is shown in Example 17-5.
EXAMPLE 17-5 JavaScript to create a dialog with jQuery UI
$(document).ready(function () { $('#dialog').dialog();
});
When viewed in a browser, the result is shown in Figure 17-7.
FIGURE 17-7 Creating a basic dialog.
Like the datepicker from the previous section, the dialog() function can also take advantage of options that customize its behavior and appearance.
Creating a modal dialog
A modal dialog is one that prevents the user from interacting with the parent window until the dialog is dismissed. Creating a modal dialog is accomplished using the modal option, as in this example:
$(document).ready(function () { $('#dialog').dialog({
modal: true });
});
When added as an option, the resulting page and dialog are shown in Figure 17-8. Notice the effect applied to the background, graying it out to indicate that no input is allowed in that area of the page.
FIGURE 17-8 A modal dialog with jQuery UI.
adding buttons
Buttons can be added to the dialog. This might be done to obtain a confirmation from the user.
Consider this JavaScript:
$('#dialog').dialog({
resizable: false, modal: true, buttons: {
"Confirm": function() {
// Perform actions here based on // receiving confirmation // Then close the dialog:
$(this).dialog("close");
},
"Cancel": function() { $(this).dialog("close");
}
} //end buttons option });
This JavaScript uses the buttons option, which accepts an array of the buttons to add. When viewed through a browser, Figure 17-9 is the result.
FIGURE 17-9 Creating a confirmation dialog with jQuery UI.
When viewed in a browser, the dialog opens immediately. A more likely scenario is that the dialog will be opened when a visitor clicks an element within a page. The dialog() function can be opened and closed on a click of another element. Example 17-6 shows the HTML to create this scenario.
EXAMPLE 17-6 HTML for opening a dialog when a page element is clicked
<!DOCTYPE html>
<html>
<head>
<title>jQuery UI Dialog</title>
<link type="text/css" rel="stylesheet"
href="css/ui-lightness/jquery-ui-1.8.22.custom.css" />
<script type="text/javascript"
src="js/jquery-1.7.2.min.js">
</script>
<script type="text/javascript"
src="js/jquery-ui-1.8.22.custom.min.js">
</script>
<script type="text/javascript"
src="js/dialog-open.js">
The JavaScript for this scenario is where the bulk of the additional work is needed. In JavaScript, the dialog is first told not to automatically open through its autoOpen option. Next, a click event handler is created and added to the “opener” <DIV> section on the page. This click event, when fired, sets up the dialog and then opens it. The JavaScript is shown in Example 17-7.
EXAMPLE 17-7 Opening a dialog with a click event
$(document).ready(function () {
$("#dialog").dialog({ autoOpen: false,
resizable: false, modal: true });
$('#opener').on('click', function() {
$("#dialog").dialog("open");
});
});
When viewed through a browser, the page looks like Figure 17-10.
FIGURE 17-10 Creating a page to hold a dialog that displays with a click event.
Clicking anywhere within the text “Click here to open the dialog” shows the dialog, like that in Figure 17-11.
FIGURE 17-11 The dialog opened after clicking the text message.
note This code can be found as dialog-open.html and dialog-open.js in the companion content.
More JQuery UI
There’s quite a bit more to jQuery UI than this chapter could convey. For example, jQuery UI has an autocomplete function and several other widgets, with more being added all the time.
A good place to start for more information about jQuery UI, with a special focus on how to make things work, is on the jQuery UI demo site at http://jqueryui.com/demos/.
Exercises
1. Create a jQuery UI datepicker on a webpage and allow the date range to be from 1 month prior to the current date up to 12 months ahead of the current date.
2. Refer to the jQuery UI documentation and implement a page with at least one widget not