If you're a traditional desktop application developer making the move to developing web applications, you probably have no trouble at all picking up HTML and CSS. But coming up with a good-looking visual design for your application can be a challenge. jQuery UI and various jQuery plug-ins can help a great deal in quickly putting together web applications with minimum time spent on GUI design.
JavaScript has always been an inherent part of building any web page if you want the page to have any degree of dynamic content or interactivity. Without JavaScript, anything you want to do at run time to update your page would require a page refresh, which makes the interface unwieldy. In recent years, the importance of JavaScript has skyrocketed, as more is done with it and web applications become more powerful. JavaScript is even finding a place on the server side through technologies like Node.js, a server-side JavaScript engine. See Resources for links to more information on Node.js and JavaScript in general, if you want to brush up.
jQuery is a library primarily used with client-side JavaScript code. It can vastly speed up the time needed to write UI code, providing shortcuts for many day-to-day actions. It also includes a flexible Ajax library that's useful in creating dynamic interfaces and is already browser cross-compatible. See Resources for links to more information, including a download link to both development and production copies of the library. The production code has been "minified," meaning that all unnecessary white space and comments have been removed. The development copy is easier to read if you're exploring the library's internals, which is highly recommended. Before using any third-party library, it pays to inspect it to ensure that you understand and like both its quality and its functionality.
jQuery UI is a set of UI widgets and CSS styles that come prepackaged to
accomplish common tasks, such as setting up a custom window that prompts a
user for information, through JavaScript and CSS, rather than as an
old-style pop-up window. When you visit the jQuery UI website (see Resources for a link), you'll see there is no
straight download option. Rather, the site presents a Build custom
download link. Click on this link to assemble your own
personalized package in which you can clear any components you know you
aren't going to use (such as the Accordion or
Datepicker widgets) to reduce the library size.
When you download your jQuery UI package, you will notice that there are quite a few files. The development-bundle directory contains demonstrations and documentation, which are useful but not necessary for deployment in production. The files in the css and js directories do need to be deployed to your web application, however. The js directory includes both the jQuery and jQuery UI libraries; the css directory includes the CSS files and all imagery used to produce the widgets and styles.
The jQuery UI download you assemble from the main page also gives you the choice of using a particular theme. The jQuery UI page provides a tool to view the various themes available right on the site to save time, or you can use the website to build your own theme by specifying preferred colors. Doing so basically automatically assembles the necessary CSS settings for you, saving some time. For example, Figure 1 shows the Humanity theme (top) compared to the Start theme (bottom). Each theme includes a full set of matching icons.
Figure 1. The Humanity theme compared to the Start theme
Themes provide an easy way to get a full set of UI components that are nice-looking without spending a huge amount of time tinkering with CSS values or working in an image editor to produce static image elements. The examples in this article use the Humanity theme. However, using a skin does not mean that you can't use your own CSS to accompany or override jQuery UI CSS. Listing 1 provides a basic HTML template that pulls in jQuery and jQuery UI, and includes a custom CSS file—app.css—that overrides the amount of padding displayed around text in buttons. It also includes app.js, which is where you place the application-specific JavaScript code.
Listing 1. A basic HTML template that loads jQuery UI
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<link rel="stylesheet" type="text/css" href="css/humanity/jquery-ui-1.8.10.custom.css" />
<link rel="stylesheet" type="text/css" href="css/app.css" />
<script src="js/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.8.10.custom.min.js" type="text/javascript"></script>
<script src="js/app.js"></script>
<body>
</body>
</html>
app.css:
body {
font-size: smaller;
}
/* Override jQuery UI theme's padding on buttons: */
.ui-button-text-only .ui-button-text {
padding: 0.2em 0.5em;
}
|
Interface improvement: The Dialog widget
Many web developers are fans of the alert or
confirm functions for getting a message to (or
from) a visitor. These messages are at best tacky, especially since they
usually include a caption like, "The page at www.yoursite.com says...,"
which doesn't really shine. Another common approach is to open a pop-up
window. This method is losing ground because of problems caused by pop-up
blockers, but it also has some degree of tackiness.
Using the jQuery UI Dialog functionality, you
can show arbitrary content or a predefined
<div> tag hidden with
display: none when you need to interact with a
visitor. Figure 2 shows the difference this functionality makes
in overall look and feel.
Figure 2. Comparing a plain alert window to a jQuery UI Dialog widget
Using the Dialog widget is easiest when you have
a separate <div > tag within your
document holding the content to be displayed. In general, it works well to
have one empty <div> tag that gets reused
for dialog boxes. First, set the content, and then show the dialog box, as
Listing 2 shows:
Listing 2. Displaying a jQuery UI Dialog widget
<div style="display: none;" id="dialogHolder"><p id="dialogContent"></p></div>
in JavaScript code:
$('#dialogContent').html('Isn\'t this <b>cooler</b>?<br /><br />By setting
modal to true, you can require the user to dismiss this before interacting
with more of the page.');
$('#dialogHolder').dialog({
autoOpen: true,
title: 'Hello!',
modal: true,
buttons: {
"Go Away": function() {
$(this).dialog("close");
}
}
})
|
Interface improvement: Accordions and tabs
jQuery UI introduces a widget called Accordion,
which allows you to have multiple sections of content where, generally,
only one section is visible (by default). Clicking on a different section
causes the visible section to be hidden with an animation and the new
section to be shown. One advantage of an accordion is the ability to have
virtually unlimited sections because additional sections are arranged
vertically. This functionality provides a fluid and simple interface.
Many website visitors will be more familiar with a traditional tab-style
layout. Here, the currently selected tab is visible, while other tabs are
hidden, effectively limiting the number of tabs because you're constrained
by horizontal width. Figure 3 shows an
Accordion widget (top) and a
Tab widget (bottom).
Figure 3. jQuery Accordion and Tab widgets
Accordions are built using a containing
<div>, followed by a sequence of
sections. Each section begins with an
<h3> and an
<a> tag, followed by a subcontainer
<div> that holds your content for each
accordion section. Similarly, for the tab controls, a containing
<div> is used, followed by the definition
of the tabs themselves using a <ul> tag.
In each <li>, an anchor
(<a>) is used to tie the tab to the
content's <div>. Next, a sequence of
<div> elements, with IDs matching those
defined in the unordered list (<ul>)
defines the actual content. This is easier to see in Listing 3. Once the content has been defined, the accordion or tab
functionality is initialized by calling
.accordion(); or
.tab(); on the jQuery selector for the
appropriate <div> element.
Listing 3. Setting up an Accordion widget and a Tab widget
<div id="accordionDemo" style="width: 50%; margin-left: auto; margin-right: auto;">
<h3><a href=#">Top Section</a></h3>
<div>
<p>Initial content for the first "tab" of the accordion goes here.</p>
</div>
<h3><a href=#">Next Section</a></h3>
<div>
<p>More content...</p>
</div>
<h3><a href=#">Last section</a></h3>
<div>
<p>You can have as many accordion sections as needed.</p>
</div>
</div>
<div id="tabDemo" style="width: 50%; margin-left: auto; margin-right: auto;">
<ul>
<li><a href="#t1">First Tab</a></li>
<li><a href="#t2">Middle Tab</a></li>
<li><a href="#t3">Last Tab</a></li>
</ul>
<div id="t1">
<p>First tab content goes here. The anchor href for the tab titles must
match the div for the content.</p>
</div>
<div id="t2">
<p>Second Tab Content</p>
<br />
<img src="http://www.google.com/images/logos/ps_logo2.png" />
</div>
<div id="t3">
<p>As with the Accordion, you can have as many tabs as you want, although
horizontal width places some practical limit there.</p>
</div>
</div>
in JavaScript code:
$(document).ready(function() {
$('#accordionDemo').accordion();
$('#tabDemo').tabs();
}
|
jQuery UI also provides a progress bar widget, which can be useful for
long-running operations. This widget is quite simple to use. Define a
<div> with an ID and no content, and then
call the progressbar function on it; for
example, $('#yourDiv').progressbar();. In
practice, this widget can be combined with Ajax techniques to reflect an
operation's progress.
A website that has strict requirements of entering a date in a particular format is annoying, particularly if its visitors are from a variety of countries (with their own date formats). It's also dangerous to leave a free-form input field, which would require back-end validation and a means of notifying the visitor if the date entered could not be parsed. One easy solution is to use a date picker widget, like the one jQuery UI provides. It has extensive functionality, including the ability to limit date ranges, rename the days on the calendar (for internationalization), and other features. Using it is simple. Create a standard text input field, such as:
<input type="text" id="dateDemo" size="10"> |
And then turn it into a calendar using the following code:
$('#dateDemo').datepicker({ 'maxDate': '+4m'});
|
The above code defines a maximum date of four months from the current date (5 March 2011, as it happens). The screen shot in Figure 4 reflects this.
Figure 4. The jQuery UI Datepicker widget
jQuery itself provides the ability to use
animate to perform animations that transition
any attribute from one value to another. This functionality is useful when
defining your own animations. But always writing your own animations takes
time. jQuery UI adds predefined animations, including the stand-alone
effects Bounce, Highlight, Pulsate, Shake, Size, and Transfer, and the
additional Show and Hide effects of Blind, Clip, Drop, Explode, Fade,
Fold, Puff, Slide, and Scale. These effects are used in the usual jQuery
show and hide
functions; for example,
$('#googleLogo').show('slide', {}, 1000); or
$('#googleLogo').hide('explode', {}, 2000);.
Dozens of plug-ins have been developed for jQuery by third parties. These plug-ins are generally independent of jQuery UI and do not require it, although they do require jQuery itself. Let's take a look at some of the particularly useful plug-ins.
Ever since Microsoft® Windows® Explorer first made its appearance, tree-based menus have been popular. They are an easy way to navigate a complex set of resources, such as documentation. The jQuery Simple Tree plug-in makes it easy to implement tree menus, with any JavaScript action taken on click. If desired, the plug-in also makes it possible to drag and drop tree items, reorganizing them, also with a function fired on drop. (See Resources for a download link; all the required components are also available in the sample code in the Download section.) Figure 5 shows the Simple Tree plug-in in use.
Figure 5. The Simple Tree jQuery plug-in
The tree content is defined with a single outer
<ul> element, which has an ID identifying
the tree and CSS settings styling it. Inside this, a root item is defined
with an <li> element. Inside this
element, another <ul> element is placed,
with tree items inside this (each one in its own
<li> element). Listing 4 illustrates this layout. When complete, the
simpleTree function is called to activate tree
functionality.
Listing 4. Setting up a tree menu with Simple Tree
<head>
<link rel="stylesheet" type="text/css" href="css/jquery.simple.tree.css" />
<script src="js/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="js/jquery.simple.tree.js" type="text/javascript"></script>
</head>
<body>
<ul id="treeDemo" class="simpleTree">
<li class="root"><span>Here are some items.</span>
<ul>
<li class="open" id="TopmostBranch"><span>Top Branch</span>
<ul>
<li id="SubItem1"><span>Sub items</span></li>
<li id="SubItem2"><span>are in another</span></li>
<li class="open" id="SubItem3"><span><ul> level.</span>
<ul>
<li id="SubSubItem1"><span>like this!</span></li>
</ul>
</li>
</ul>
</li>
<li id="AnotherBranch"><span>Another Branch</span></li>
<li id="LastBranch"><span>Last Branch</span></li>
</ul>
</li>
</ul>
</body>
in JavaScript code:
$(document).ready(function() {
$('#treeDemo').simpleTree({
autoclose: true,
afterClick: function(node) {
alert($('span:first',node).parent().attr('id') + " was clicked.");
},
animate: true,
drag: false
});
});
|
The Uploadify jQuery plug-in allows you to upload files to your site
without having to do a POST operation to a new
page and shows a progress indicator as files are being uploaded. The
upload itself is handled with an Adobe® Flash® component. The
tool allows a great deal of customization, including specifying what file
extensions are allowed, size limits, and whether multiple files can be
selected at once. When each file is finished uploading, the
onComplete function is called; the
onAllComplete function is called when all files
are finished. The default upload handler that comes with Uploadify
responds by echoing back the name of the uploaded file, but this upload
handler can easily be customized to fit your needs (for example, posting a
file into a forum or taking some other action). Listing 5 shows
how to set up a file upload with Uploadify.
Listing 5. Converting a standard file input to an Uploadify uploader
<head>
<script src="js/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="uploadify/swfobject.js" type="text/javascript"></script>
<script src="uploadify/jquery.uploadify.v2.1.4.min.js" type="text/javascript"></script>
</head>
<body>
<div style="margin-left: auto; margin-right: auto; width: 200px">
<b>Upload a file to test:</b> <input id="uploadifyDemo"
name="uploadifyDemo" type="file" />
</div>
</body>
in JavaScript code:
$(document).ready(function() {
$('#uploadifyDemo').uploadify({
'auto': true,
'folder': 'tmp',
'cancelImg': 'uploadify/cancel.png',
'script': 'uploadify/uploadify.php',
'uploader': 'uploadify/uploadify.swf',
onComplete: function(evt, id, file, resp, data) {
alert('The file "' + file['name'] + '" with size "' + file['size'] +
'" was uploaded. (It will be deleted in a few minutes
automatically.)' + "\n\nThe upload script returned: " + resp);
}
});
});
|
It's good practice to make sure that your upload directory is either
inaccessible to the public or well-protected. Failure to do so can allow
attackers to upload their own code and execute it on your server. In this
example, files are written to tmp/ in the article example directory, so
you simply forbid all visitors from accessing tmp/ with an
.htaccess rule. It's also important to ensure
that the user your web server is running as (for example, www-data or
apache) has write permission to the upload directory.
Any application, whether on a desktop or web-based, needs to be
self-documenting for users to find it truly easy to use. Tooltips are one
quick way to do this. After decades of tooltip use, most people are
instinctively trained to let their mouse dwell over an item on screen if
they are unsure pf what it is, waiting for some pop-up help. The Simpletip
plug-in makes this easy to do. With Simpletip, you can create basic
tooltips or use additional options to control placement. Effects for
displaying and hiding the tooltips are supported, including custom
animations as defined by a JavaScript function. Content for the tooltip
can come from hard-coded text or from any other page content, such as a
hidden <div> element, using
$('#elementId').html(). You could also
programmatically fetch content using Ajax or get it from another source in
the document, using something like
$('#simpleTip3').simpletip({ content: getToolTip()});.
Listing 6 illustrates a few different styles of tooltip
appearing on words in a sentence.
Listing 6. Setting up a tooltips with Simpletip
<head>
<script src="js/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="js/jquery.simpletip-1.3.1.min.js" type="text/javascript"></script>
</head>
<body>
<p>
SimpleTip lets you add <a id="simpleTip1">simple tooltips</a>,
including <a id="simpleTip2">more advanced</a> tooltips or even
<span id="simpleTip3">tooltips with effects</span> with a minimum of fuss.
</p>
<div id="simpleTip2Content" style="display: none;">
<div class="ui-state-highlight ui-corner-all" style="padding: 5px;">
<b>Fancy</b> content can be defined in a separate div.
</div>
</div>
</body>
in JavaScript code:
$(document).ready(function() {
$('#simpleTip1').simpletip({
content: 'A basic tooltip.',
fixed: false
});
$('#simpleTip2').simpletip({
content: $('#simpleTip2Content').html(),
fixed: true,
position: ['100', '0']
});
$('#simpleTip3').simpletip({
content: 'Some content to animate',
hideEffect: 'slide',
showEffect: 'custom',
showCustom: function() {
$(this).css({
display: 'block',
fontSize: '0.3em',
color: '#0000ff',
backgroundColor: '#ffffff'
});
$(this).animate({
color: '#ff0000',
fontSize: '1em'
}, 400);
}
});
});
|
Using the tools described in this article allows you to quickly create the visual components of your web application, leaving you free to focus on actual functionality in your site. You still need to think carefully about natural page flow and the usability of each page you write in an application, and jQuery UI and these plug-ins do not negate the need for careful page design. However, they do speed up development and make implementation easier. See the Download section for a complete web page that includes all the discussed sample code. You are welcome to use this as a starting point for your own projects.
| Description | Name | Size | Download method |
|---|---|---|---|
| Source code for examples | jQueryUIPluginsExamples.zip | 234KB | HTTP |
Information about download methods
Learn
- JavaScript
tutorial (w3schools): Start here if you're new to JavaScript.
-
jQuery website: Find downloads and
documentation for the jQuery library required by jQuery UI.
-
jQuery UI website: Build your custom
download, including only the tools you need. The site also has great
documentation and examples.
- jQuery UI ThemeRoller: Build your own themes, and preview
predefined themes. The site also makes a handy reference for a quick example of
common components.
- developerWorks Web
development zone: Find articles covering various Web-based solutions.
- Stay current with developerWorks' technical events and webcasts.
-
developerWorks on-demand demos: Watch demos ranging from product
installation and setup for beginners to advanced functionality for
experienced developers.
- Follow developerWorks on
Twitter.
Get products and technologies
-
Node.js: Download this fascinating server-side
JavaScript engine.
-
Simple Tree:
Download this jQuery plug-in, which makes it less trivial to build tree-structure menus,
optionally with drag-and-drop support.
-
Simpletip:
Download this
jQuery plug-in that simplifies adding tooltip-style pop-up windows to any
element on your web page.
-
Uploadify: Handle file uploads in
a clean manner, including progress display, removing the need for a
POSTand page reload.
Discuss
- Create your developerWorks profile today and setup a watchlist on jQuery. Get connected and stay connected
with the developerWorks community.
- Find other developerWorks members interested in web development.
- Join one of our developerWorks groups focused on web
topics: Share what you know.
- Roland Barcia talks about Web 2.0 and middleware in his blog.
- Follow developerWorks' members' shared bookmarks on web topics.
- Web 2.0 Apps forum: Get answers quickly.
- Ajax forum: Get answers quickly.

Christopher Michaelis is a developer specializing in web hosting, web applications, and GIS programming. He received his education at Utah State University and Idaho State University, studying computer science and geographic information science. His experience covers a wide range of development, including applications for environmental modeling, education, diabetes data analysis, systems administration tools, web hosting, platform integration, and location-based services.




