jQuery UI 1.6: The User Interface Library for jQuery

By Dan Wellman
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Introducing jQuery UI

About this book

Modern web application user interface design requires rapid development and proven results. jQuery UI, a trusted plugin for the jQuery JavaScript library, gives you a trusted platform on which to build rich and engaging interfaces with maximum compatibility, stability, and a minimum of time and effort.

jQuery UI has a series of ready-made, great-looking user interface widgets and a comprehensive set of core interaction helpers designed to be implemented in a consistent and developer-friendly way. With all this, the amount of code that you need to write personally to take a project from conception to completion is drastically reduced.

This book has been written to maximize your experience with the library by breaking down each component and walking you through examples that progressively build upon your knowledge, taking you from beginner to advanced usage in a series of easy to follow steps.

In this book, you'll learn how each component can be initialized in a basic default implementation and then see how easy it is to customize its appearance and configure its behaviour to tailor it to the requirements of your application. You'll look at the properties and methods exposed by each component's API and see how these can be used to bring out the best in each component.

Events play a key role in any modern web applications if it is to meet the expected minimum requirements of interactivity and responsiveness, and each chapter will show you the custom events fired by each component and how these events can be intercepted and acted upon.

Publication date:
February 2009
Publisher
Packt
Pages
440
ISBN
9781847195128

 

Chapter 1. Introducing jQuery UI

Welcome to jQuery UI 1.6: The User Interface Library for jQuery. This resource aims to take you from the first steps to an advanced usage of the JavaScript library of UI widgets and interaction helpers built on top of the awesome jQuery.

jQuery UI extends the underlying jQuery library to provide a suite of rich and interactive widgets, and code-saving interaction helpers, built to enhance the user interfaces of your websites and applications.

Because jQuery UI runs on top of jQuery, the syntax used to initialize, configure, and manipulate the different components is in the same comfortable, easy-to-use, and short-hand style that we've all come to know and love through using jQuery. Therefore, getting used to it is incredibly easy.

You also automatically get all of the great jQuery functionality at your disposal when using jQuery UI. So when you implement any particular component, your code will usually be a mixture of jQuery and jQuery UI specific code, as well as some traditional JavaScript occasionally.

We won't be looking at any code in this chapter. There are just a few points that I would like to mention before we break out the text editors and get down to some coding. In this chapter, we'll be looking at the following subjects:

  • Who this book is written for

  • How to obtain a copy of the library

  • How to set up a development environment

  • The structure of the library

  • Theme Roller

  • The format of the API

  • Browser Support

  • How the library is licensed

 

Is this book for me?


This book is for developers who want to quickly and easily build engaging, highly interactive interfaces for their web applications, or less commonly, for embedded applications. I mention embedded applications because jQuery UI is suitable for other mediums than just the Internet.

Nokia was the first mobile phone company to announce that they were adopting jQuery to power parts of their cell phone operating system. I'm sure that by the time this book is published there will be more companies adapting the library for their own needs, and wherever jQuery goes, jQuery UI can follow.

People that are comfortable with HTML, JavaScript, and CSS, and have at least some experience with jQuery itself will get the most benefit from what this book has to offer. However, no prior knowledge of the UI library itself is required.

Consider the following code:

$("#myEl").click(function() { 
  $("<p>").attr("id, "new").css({
    color:"#000000"
  }).appendTo("#target");
)};

If you cannot immediately see, and completely understand, what this simple code does, you would probably get more from this book after first learning about jQuery itself. Consider reading Karl Swedberg and Jonathan Chaffer's excellent Learning jQuery, also by Packt, or visit http://www.learningjquery.com and then come back to this book.

Each jQuery UI specific method or property that we work with will be fully covered in the explanatory text that accompanies each example, and where it is practical, some of the standard jQuery code will also be discussed.

Basic concepts of using jQuery itself won't be covered. Therefore, you should already be familiar with advanced DOM traversal and manipulation, attribute and style getting and setting, and making and handling AJAX calls. You should be comfortable with the programming constructs exposed by jQuery such as method chaining and using callback functions.

Note

Knowing and understanding how jQuery works is important if you want to learn how to leverage the full potential of jQuery UI. Using jQuery promotes writing code in a particular style that is easily recognizable. Code written for jQuery UI naturally assumes this same style, and you should be comfortable enough with it to be able to easily see what is going on with different bits of code in the examples.

 

Downloading the library


There are several different options for downloading the library. You can choose to download a personalized package tailored to your individual needs using the download builder, download the full development bundle containing all library files including full, packed, and minified versions of each script file, or download individual files from the online SVN repository.

Once you've mastered jQuery UI, and are regularly using selected widgets in different projects that you're involved in, using the download builder to quickly put together the files and their dependencies that you require will be an effective way of minimizing the library's footprint within your applications.

As we'll be looking at each of the lower-level interaction components and the higher-level widgets that make up the library, we'll be working mostly with the full development bundle throughout the book. At this point, you should probably download a copy of the library, which can be obtained from the jQuery home page at http://www.jquery.com.

There are two versions of the full development bundle. The latest version and the most stable version. We'll be working with the latest version in our examples to make sure we get to see the newest, most cutting-edge features.

There are bugs in the code with a couple of the library components, or certain features that we want to use that aren't currently available. This is where the SVN nightlies come in, as we can link to or download the latest, most bug-free versions of each file. These are the actual working files which developers who build the library use, and have brand new fixes and patches in place.

In addition to the library itself, the jQuery UI project site is home to an extensive range of examples of different library components which are presented in a beautiful carousel-type format, with support information as seen here:

 

Setting up a development environment


We'll need a location to unpack the jQuery UI library in order to easily access the different parts of it within our files. We should first create a project folder, into which all of our example files, as well as all of the library and other associated resources such as stylesheets and images, can be kept.

Create a new directory on your C: drive, or in your home directory, and call it jqueryui. This will be the root folder of our project and will be the location where we store all of the files that we're going to create.

To unpack the library, open it in a compression program, such as Winzip, and drag the jqueryui1.6rc2 folder into the directory we just created. We also need to create img and styles This will give us the correct folder structure to work from. The folder structure should be as follows:

  • jqueryui

    • jqueryui1.6rc2

      • _MACOSX

      • demos

      • tests

      • themes

      • ui

    • img

    • styles

 

The structure of the library


Let's take a moment to look at the structure of the unpacked library. This will give us a feel for its composition and where the different resources that we'll be working with reside. Open up the jqueryui1.6rc2 folder where we extracted the archived library. The contents of this folder should be as follows:

  • _MACOSX directory

  • demos directory

  • tests directory

  • themes directory

  • ui directory

  • GPL-License file

  • MIT-License file

  • the jQuery library

  • a version file

The _MACOSX folder can safely be ignored, even by Mac users. It exists only because the current version of the library was opened by someone using a Mac, and I have mentioned it here solely because it exists in the unpacked structure of the library. Don't even worry about removing this folder as it's only a couple of bytes in size.

The contents of the demos directory shows you a series of functional, as well as real-world examples of how the different UI components can be used. Each of the components has its own demo page which is designed to work as is from its current location.

The functional example pages show a basic implementation of each component, as well as exposing some of the more common configurations that can be set. These pages are an exact mirror of their online-equivalents.

The real-world examples highlight one particular feature of a component, and demonstrate this feature by itself on the page with little or no explanatory text. While these are the same examples found on the jQuery UI project page, they are presented much better online.

Unit testing

The tests folder is similar to the demos folder in that it contains a series of pages that highlight different features of the components found in the library. The important difference is that components which are still in beta stage, under full development, are also included. By taking a look into this folder, you can get a very good idea of what is about to be released. These examples can be found in the visual folder within the tests folder.

If you're concerned with the size of the library on your web server, or the bandwidth that uploading it would take, the demos and tests folders can safely be deleted. However, they do only take up a few megabytes of space.

Several other important resources can also be found in the tests folder. The qunit folder contains jQuery's unit testing environment. Some of you may have heard of, or used, the popular JUnit. This is a Java-based unit testing environment. QUnit is the same, but is tailored specifically for use when writing jQuery plugins or jQuery UI widgets.

For those of you who haven't done any unit testing before, this refers to the practice of writing tailored code which tests the functionality of the smallest unit available for testing within an application. In a language like JavaScript, the unit, or smallest possible abstraction of functionality, is typically a single method.

We could argue that a variable is the smallest unit within a JavaScript application, but as functions, and therefore methods, can be assigned to a variable, this wouldn't always be a viable argument.

We won't be using QUnit in any of our book examples because we won't be creating any plugins or widgets of our own. Some excellent documentation of QUnit is provided on the jQuery site for those of you who can envisage yourself doing this at some point in the future.

The simulate folder contains a plugin written by Eduardo Lundgren and Richard D. Worth that is used to assist unit testing with jQuery. It adds a set of methods to your toolkit that allows you to simulate common mouse and keyboard events from your code. This is useful for checking actions like drag-and-drop when this behavior is included in your widgets or plugins.

Widget theming

The library ships with two themes. The default theme is light-grey and neutral looking. The flora theme consists of pleasant light-green and orange tones. Both provide styling for each of the higher-level widgets and can be used completely out-of-the-box without modification if desired.

Some of the CSS found in these themes go beyond mere aesthetics and instead relates to how the widget functions. Therefore, if we want to provide a custom skin for any particular widget we have two options. First, we can omit the widget's skin file completely and use our own CSS file instead of the corresponding theme file. Or second, we can simply override the rules that deal specifically with appearance.

The first method, while equally viable, creates much more work for us and essentially means we have to reinvent the wheel. By this I mean we would have to spend time writing styling code related to functionality which has already been written. The second option is much more efficient and allows us to focus on writing the barest, minimum styling code, building on the foundation already provided by the existing themes.

Minified and packed components

The ui folder contains all of the un-minified versions of the code files for each component and effect, several subdirectories containing the minified and packed versions of the components, and the i18n folder.

The full-sized versions of each library component and effect are useful for development purposes. These can be opened up and read to get a better feel for how a particular component works. These files are complete with comments that advise us how particular sections of code work.

The minified versions of each component are excellent for production use, where downloading and interpretation of the files matters the most. JavaScript can easily be minified using a growing number of tools.

Minified files have all comments, whitespace, and line breaks removed from them. Most minification tools also obfuscate the code which shortens object, variable, and function names to just one character where possible. The code in the file is not changed in the way that it works.

The packed versions of each file are the smallest form of each component, but they are not actually minified in the above sense. Instead, these files are compressed, which is what makes them smaller than the minified files. The code within packed files is changed however, and it takes some additional client-side code to uncompress them. This means that although smaller, packed files will generally take longer to interpret.

The i18n directory is where the language packs for the date picker widget reside. The date picker (which we'll look at in detail in chapter 6) is very easy to internationalize using these plugin language packs.

 

Theme Roller


Theme Roller is a custom tool written in jQuery that allows us to visually produce our own custom jQuery UI theme and package it up in a convenient, downloadable archive which we can drop into our project with no further coding (other than using the stylesheet in a HTML <link> element of course).

Theme Roller was created by Filament Group Inc and makes use of a number of jQuery plugins released into the open-source community. It can be found at http://ui.jquery.com/themeroller.

Theme Roller is certainly the most comprehensive tool available for creating your own jQuery UI themes. We can very quickly and easily create an entire theme comprised of all of the styles needed for targeting elements, including the images we'll need, which is compatible with all of the non-beta widgets.

The previous screenshot shows the Theme Roller interface and as you can see, it's remarkably simple to use. The top of the page, in the previous screenshot, shows a series of select boxes and input fields arranged in a tabular format.

Each column of fields represents an aspect of each widget. We can set the color and texture of the background, the border color, text color, and icon color. The icon setting refers to elements of each widget, such as the left or down icons shown on clickable areas.

Each row of settings corresponds to a state. There is the default state, the hover and active states, and the content area. The content area may be the panel of a set of tabs, or an accordion, for example. We can also set the global font-family, font-style, and the font-size too.

When you interact with the top half of the page, the bottom of the page, which contains a selection of example widgets, is automatically updated with your selections so you can quickly see how your theme will look.

If you're not feeling particularly inspired when creating a theme, there is also a gallery of pre-configured themes that you can instantly use. Aside from this convenience, the best thing about these preselected themes is that when you select one, it is loaded automatically into the first page of Theme Roller. Therefore, you can easily make little tweaks as you see fit.

Without a doubt, this is the best way to create a visually appealing custom theme that matches the UI widgets to your existing site. However, we won't be looking at this tool again for the remainder of this book. We'll be focusing instead on learning the style rules that we need to manually override to generate our desired skins.

 

The simplified API


The version 1.5 release of jQuery UI was a milestone in the library's history. This was the release in which the API for each component was significantly simplified, making the library both easier to use and more powerful.

Once you've worked with one of the components from the library, you'll instantly feel at home when working with other components since the methods of each component are called in exactly the same way.

Methods are consistently called throughout the components by passing the method name as a simple string to the component's constructor method, with any arguments that the method accepts passed as strings after the method name. For example, to call the destroy method of the tabs component, we would simply do this:

$("#someElement").tabs("destroy");

See how easy that was? Every single method exposed by all of the different components is called in this same simple way. Using jQuery UI feels just like using jQuery itself and having built up confidence coding with jQuery, moving on to jQuery UI is the next logical step to take.

Many of the components also share a similar method-set of exposed functionality. For example, every single component found in the library has destroy, enable, and disable methods, and many others expose similar functionality. This again makes each component exceptionally easy and intuitive to use.

 

Component categories


There are two types of components found within the jQuery UI library. Low-level interaction helpers that are designed to work, primarily, with mouse events, and there are the widgets, which produce visible objects on the page which are designed to perform a specific function.

The interaction-helpers category, which forms the underlying core of the library, includes the following components:

  • draggable

  • droppable

  • resizable

  • selectable

  • sortable

The higher-level widgets, which often build upon the foundation provided by the lower level components, include:

  • accordion

  • auto complete

  • date picker

  • dialog

  • slider

  • tabs

The ui.core.js file, which is required by all other library components, comes under neither category, but could nevertheless be seen as a component. This file sets up the construct that all widgets use to function and adds some core functionality which is shared by all of the library components. This file isn't designed to be used on its own, and exposes no functionality that can be used outside of another component.

Apart form these components, there is also a series of UI effects, which was once a completely separate sister library called Enchant. These effects produce different animations or transitions of targeted elements on the page. These are excellent for adding flair and style to your pages, in addition to the rock-solid functionality of the components. We'll be looking at these effects in the final chapter of the book.

I'd like to add here that the jQuery UI library is currently undergoing a rapid period of expansion and development. It is also constantly growing and evolving with bug-fixes and feature enhancements continually being added. It would be impossible to keep entirely up-to-date with this aggressive expansion and cover components that are literally about to be released.

The great thing about jQuery UI's simplified API is that once you have learned to use all of the existing components, as this book will show you, you'll be able to pick up any new components very quickly. As this book is being written, there are already a number of new components nearing release, with many more in the pipeline.

Due to its success in the development community, jQuery UI is sure to become a stalwart of modern web design and is therefore worth investing time and effort in.

 

Browser support


Like jQuery, jQuery UI supports all of the major browsers in use today including the following:

  • IE6, IE7 and IE8

  • Firefox 2 and Firefox 3

  • Opera 9

  • Safari 3

  • Chrome

This is by no means a comprehensive list, but I think that it includes the browsers that are most likely to be used by any average web surfer. The widgets are built from semantically correct HTML generated as needed by the components. Therefore, we won't see excessive or unnecessary elements being created or used.

I'm sure I needn't remind you that your own style of coding should follow the lead of jQuery UI. You should always strive to maintain an accessible inner core of content that has successive layers of presentation and functionality layered on top in the manner of progressive enhancement.

 

Book examples


The library is as flexible as standard JavaScript, and by this I mean that there is often more than one way of doing the same thing, or achieving the same end. For example, the callback properties used in the configuration objects for different components, can usually take either references to functions or inline anonymous functions, and use them with equal ease and efficiency.

In practice, it is usually advised to keep your code as minimal as possible (which jQuery really helps with anyway), but to make the examples more readable and understandable, we'll be separating as much of the code as possible into discrete modules. Therefore, callback functions and configuration objects will be defined separately from the code that calls or uses them.

To reduce the number of files that we have to create and work with, all of the JavaScript will go into the host HTML page on which it runs, as opposed to in separate files. This isn't necessary, or indeed recommended at all in fact, for production websites or applications.

I'd also just like to make it clear that the main aim throughout the course of this book is to learn how to use the different components that make up jQuery UI. If an example seems a little convoluted, it may simply be that this is the easiest way to expose the functionality of a particular method or property, as opposed to a situation that we would find ourselves coding for in a regular implementation.

Although the lower-level components provide a foundation which is built upon by the high-level widgets, we're going to be approaching the library from the opposite direction. First, we're going to look at the widgets, as these, for the most part, have smaller APIs and are therefore easier to learn and use. Once we have mastered the widgets, we're then going to peel away the outer layers to expose the inner core of functionality imparted by the interaction helpers.

At the time of writing the latest version of jQuery UI is 1.6rc2, so this is used throughout the examples. Release Candidate 3 is imminent however, and will no doubt be shortly followed by the full stable 1.6 release. So, by the time you read this, it will probably be available.

Please ensure that when working with the examples in the code download, or writing the examples yourself, you point to the correct path for the version of the library that you download.

 

Library licensing


Like jQuery, the jQuery UI library is dual licensed under the MIT and GPL open-source licences. These are both very unrestrictive licenses that allow the creators of the library to take credit for its production and retain intellectual rights over it, without preventing us as developers from using the library in any way that we like.

The MIT license explicitly states that users of the software (jQuery UI in this case) are free to use, copy, merge, modify publish, distribute, sublicense, and sell. This lets us do pretty much whatever we want with the library.

The only requirement imposed by this license is that we must keep the original copyright and warranty statements intact.

This is an important point to make. You can take the library and do whatever you like with it. Build applications on top of it and then sell those applications, or give them away for free. Put the library in embedded systems like cell-phone OSs and sell those. But whatever you do, leave the original text file with John Resig's name in it present. You may also duplicate it word for word in the help files or documentation of your application.

The MIT license is very lenient, but because it is not copyrighted itself, we are free to change it. We could therefore demand that users of our software give attribution to us instead of the jQuery team, or pass off the code as our own.

The GPL license is copyrighted, and offers an additional layer of protection for the library's creators and the users of our software. Because jQuery is provided free and open-source, the GPL license ensures that it will always remain free and open-source, regardless of the environment it may end up in, and that the original creators of the library are given the credit they deserve. Again, the original GPL license file must be available within your application.

 

Summary


jQuery UI removes the difficulty of building engaging and effective user interfaces. It provides a range of components that can quickly and easily be used out-of-the-box with little configuration. If a more complex configuration is required, they each expose a comprehensive set of properties and methods for integration with your pages or applications.

Each component is designed to be efficient, light-weight, and semantically correct, and makes use of the latest object-oriented features of JavaScript. When combined with jQuery, it provides an awesome addition to any web developer's toolkit.

So far, we've seen how the library can be obtained, how your system can be set up to utilize it, and how the library is structured. We've also looked at how the different widgets can be themed or customized, how the API simply and consistently exposes the library's functionality, and the different categories of component.

We've covered some important topics during the course of this chapter, but now, thankfully, we can get on with using the components of jQuery UI and get down to some proper coding!

About the Author

  • Dan Wellman

    Dan Wellman is an author and frontend engineer living on the South Coast of the UK and working in London. By day he works for Skype and has a blast writing application-grade JavaScript. By night he writes books and tutorials focused mainly on frontend web development. He is also a staff writer for the Tuts+ arm of the Envato network, and occasionally writes for .Net magazine. He's the proud father of four amazing children, and the grateful husband of a wonderful wife.

    Browse publications by this author
Book Title
Access this book, plus 7,500 other titles for FREE
Access now