23,27 €
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.
Create powerful front-end interfaces for your web applications with jQuery UI
An example-based approach leads you step-by-step through the implementation and customization of each library component and its associated resources in turn. To emphasize the way that jQuery UI takes the difficulty out of user interface design and implementation, each chapter ends with a 'fun with' section that puts together what you've learned throughout the chapter to make a usable and fun page. In these sections you'll often get to experiment with the latest associated technologies like AJAX and JSON.
This book is for front-end designers and developers that need to quickly learn how to use the jQuery UI User Interface Library. To get the most out of this book you should have a good working knowledge of HTML, CSS and JavaScript, and will need to be comfortable using jQuery, the underlying foundation of jQuery UI.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 431
Veröffentlichungsjahr: 2009
Copyright © 2009 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, Packt Publishing, nor its dealers or distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: January 2009
Production Reference: 1200109
Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN 978-1-847195-12-8
www.packtpub.com
Cover Image by Karl Swedberg (<[email protected]>)
Author
Dan Wellman
Reviewers
Akash Mehta
David Methvin
Mark Grabanski
Senior Acquisition Editor
Douglas Paterson
Development Editor
Ved Prakash Jha
Technical Editor
Dhiraj Bellani
Editorial Team Leader
Akshara Aware
Production Editorial Manager
Abhijeet Deobhakta
Projects Team Leader
Lata Basantani
Project Coordinators
Neelkanth Mehta
Brinell Lewis
Indexer
Hemangini Bari
Proofreaders
Joel Johnson
Camille Guy
Production Coordinator
Aparna Bhagat
Cover Work
Aparna Bhagat
Dan Wellman lives with his wife and children in his home town of Southampton on the south coast of England. By day, his mild-mannered alter-ego works for a small, yet accomplished, e-commerce production agency. By night, he battles the forces of darkness and fights for truth, justice, and less intrusive JavaScript.
Dan has been writing computer-related articles, tutorials, and reviews for around five years and is rarely very far from a keyboard of some description.
This is his second book.
I'd like to say a big, personal thank you to the Packt editorial team for their continued support and encouragement, and to the jQuery UI development team for producing such an incredible library. Special thanks also goes out to Eamon O'Donoghue for his invaluable graphic/imagery advice, and to Mike Newth for his equally invaluable printing assistance. Finally, I'd like to thank James Zabiela, Andrew Herman, Steve Bishop, Aaron Matheson, Dan Goodall, Mike Woodford, and John Adams; they contributed in no way towards this book, but are nevertheless the greatest bunch of dudes a guy could hang out with.
Akash Mehta is a web application developer, technical writer, and business consultant based in Brisbane, Australia. His past projects include brochure websites, e-learning solutions, and information systems. He has written web development articles for several publishers in print and online. He is a regular speaker at local conferences, and contributes to prominent PHP blogs.
As a student, Akash maintained PHP web applications and built user interfaces using the jQuery toolkit. While pursuing both a commerce and an IT degree, Akash develops web applications on PHP and Python platforms. After hours, he organizes his local PHP user group.
Akash develops applications on a wide range of open source libraries. His toolbox includes a number of application frameworks, including the Zend Framework, CakePHP, and Django; Javascript frameworks, including jQuery, Prototype and Mootools; platforms such as Adobe Flash/Flex; and the MySQL and SQLite database engines.
Currently, Akash provides freelance technical writing and web development through his website, http://bitmeta.org.
David Methvin is the Chief Technology Officer at PC Pitstop, and one of the founding partners of the company. He provides technical direction for the www.pcpitstop.com website, oversees software development, and serves as an editor for the site's content. David also serves as the site's chief investigator for new spyware and adware threats. Before joining PC Pitstop, David had an extensive career in computer journalism. He served as an Executive Editor at both Windows Magazine and PC Tech Journal, co-authored a book on Windows NT networking, and wrote articles for more than two dozen publications. David continues to write a monthly column, "The Well-Tuned PC," for pctoday.com magazine. David holds both Bachelor's and Master's Degrees in Computer Science from the University of Virginia. After graduation, he spent several years designing and developing software for robotics and telecommunications systems with companies such as General Electric.
Marc Grabanski runs a consulting company focused on user interface development and user experience. He believes firmly that open source is the fuel that helps a developer go from mediocre to excellent at what they do. His work with jQuery was no exception. By writing jQuery UI Datepicker, he met so many great people and is thankful for the experiences gained by doing this project.
I want to thank, of course, John Resig for writing jQuery and the whole jQuery UI team for carrying the library to new levels each day.
This book is dedicated to my supportive and understanding wife Tammy. Thanks babe.
jQuery has been a phenomenal success, with many newcomers to the world of JavaScript frameworks choosing it, and many developers moving to it from other frameworks. jQuery UI is tipped to follow suit, and has already seen massive growth and take-up, with more success to follow. By learning how to use it now, you can be a part of its success.
jQuery UI is a collection of engaging widgets and essential interaction-helpers that can help drastically reduce the amount of code you need to write and the amount of time you need to spend developing. Each component comes with a wide range of easy-to-use configurable properties and methods. The components all share a common programming interface that quickly becomes second nature to work with.
Development of the library is ongoing, with highly-skilled developers building it to ever greater levels. New components are being added between major releases, and bug fixes/updates are constantly being tested and applied. jQuery UI is very much a community-driven site, with the team relying on and building upon bug reports and feature requests submitted by the wider development community. Additionally, new components are often derived from the most useful jQuery plug-ins.
This book will give you a head start in learning jQuery UI; exposing the APIs behind the complete range of components as of version 1.5.4, and including much of the functionality of version 1.6 of the library. Each component is methodically and consistently looked at, with many functional examples. Each chapter ends with a full implementational example, looking at ways in which the components can be used in real-world scenarios.
Chapter 1 A general overview of jQuery UI. You'll find out exactly what the library is, where it can be downloaded from and where resources for it can be found. You'll look at the freedom the license gives you to use the library, and how the API has been simplified to give the components a consistent and easy-to-use programming model.
Chapter 2 We begin our journey through jQuery UI by looking at the high-level user interface widgets, focusing on the tabs component; a simple but effective means of presenting structured content in an engaging and interactive widget.
Chapter 3 Next, we take a look at the accordion widget. This is another component dedicated to the effective display of content. Highly engaging and interactive, the accordion makes a valued addition to any web page and its API is exposed in full to show exactly how it can be used.
Chapter 4 In this chapter, we focus on the dialog widget. The dialog behaves in the same way as a standard browser alert, but it does so in a much less intrusive and visitor-friendly manner. We look at how it can be configured and controlled to provide maximum benefit and appeal.
Chapter 5 The slider widget provides a less commonly used, but no less valued, user interface tool for collecting input from your visitors. We look closely at its API throughout this chapter to see the variety of ways in which it can be implemented.
Chapter 6 Next, we look at the date picker. This component packs a huge amount of functionality and appeal into an attractive and highly usable tool allowing your visitors to effortlessly select dates. We look at the wide range of configurations that its API makes possible as well as seeing how easy common tasks, such as skinning and localization, are made.
Chapter 7 The last widget we look at is the auto-complete; a highly professional and desired addition to any page. We'll look at the different data sources you can provide and how to customize the widget, in addition to seeing which properties and methods we have at our disposal. At the time of writing, the latest stable version of the UI library is 1.5.4, but this widget is part of 1.6 release, a sneak preview of what we've got to look forward to.
Chapter 8 We begin looking at the low-level interaction helpers in this chapter, tackling first the related draggable and droppable components. We look at how they can be implemented individually and how they can be used together for maximum effect.
Chapter 9 In this chapter, we look at resizing component and see how it is used with the dialog widget. We see how it can be applied to any element on the page to allow it to be resized in a smooth and attractive way.
Chapter 10 Next, we look at the selectable component, which allows us to add behavior to elements on the page and allow them to be selected individually or as a group. We see that this is one component that really brings the desktop and the browser together as application platforms.
Chapter 11 We look at the final interaction helper in this chapter – the sortable component. This is an especially effective component that allows you to create lists on a page that can be reordered by dragging items to a new position on the list. This is another component that can really help you to add a high level of professionalism and interactivity to your site with a minimum of effort.
Chapter 12 The last chapter of the book is dedicated solely to the special effects that are included with the library. We look at an array of different effects that allow you to show, hide, move, and jiggle elements in a variety of attractive and appealing animations. There is no 'fun with' section at the end of this chapter; the whole chapter is a 'fun with' section.
Very little is required in order to start using jQuery UI. Specifically, you will need the following environment:
This book is for front-end designers and developers who need to quickly learn how to use the jQuery UI User Interface Library. To get the most out of this book, you should have a good working knowledge of HTML, CSS, and JavaScript, and will need to be comfortable using jQuery, the underlying foundation of jQuery UI.
Feedback from our readers is always welcome. Let us know what you think about this book, what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply drop an email to <[email protected]>, making sure to mention the book title in the subject of your message.
If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or email <[email protected]>.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Visit http://www.packtpub.com/files/code/5128_Code.zip to directly download the example code.
The downloadable files contain instructions on how to use them.
Although we have taken every care to ensure the accuracy of our contents, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in text or code—we would be grateful if you would report this to us. By doing this you can save other readers from frustration, and help to improve subsequent versions of this book. If you find any errata, report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata added to the list of existing errata. The existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide the location address or website name immediately so we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
You can contact us at <[email protected]> if you are having a problem with some aspect of the book, and we will do our best to address it.
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:
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:
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.
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.
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:
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:
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:
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.
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.
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.
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 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 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:
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.
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:
The higher-level widgets, which often build upon the foundation provided by the lower level components, include:
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.
Like jQuery, jQuery UI supports all of the major browsers in use today including the following:
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.
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.
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.
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!
Now that we've been formally introduced to the jQuery UI library, we can move on to begin looking at the components included in the library. Over the next six chapters, we'll be looking at the widgets provided by the library. These widgets are a set of visually engaging, highly configurable user interface widgets built on top of the foundation provided by the low-level interaction helpers.
The UI tabs widget is used to toggle visibility across a set of different elements; each element containing content can be accessed by clicking on its heading which appears as an individual tab. Each element, or section of content, has a tab that it is associated with and only one of these content sections may be open at a time.
The following image shows the different components of a set of UI tabs:
In this chapter, we will look at the following subjects:
The structure of the underlying HTML elements, on which tabs are based, is fairly rigid and widgets require a certain number of elements for them to work.
The tabs themselves must be created from a list element, either ordered or unordered, and each list item should contain a <span> element and an <a> element. Each link will also need to have a corresponding <div> element that it is associated with via its href attribute. We'll clarify the exact structure of these elements after our first example.
In a new file in your text editor, create the following page:
Save the code as tabs1.html in your jqueryui working folder. Let's review what was used. The following script and CSS resources are needed for the default tab widget instantiation:
A set of tabbed panels consists of several standard HTML elements arranged in a specific manner (these can be either hardcoded into the page or added dynamically, or a mixture of both depending on the requirements of your implementation):
The first three elements make the clickable tab headings which are used to open the content section the tab is associated with. Each tab should include a list item containing the link, with a <span> element nested inside that link. The href attribute of the link should be set as a fragment identifier, prefixed with # and should match the id attribute of the <div> that forms the content section it is associated with.
The content sections of each tab are created by the <div> elements. The id attribute is required and will be targeted by its corresponding <a> element. The elements discussed so far, along with their required attributes, are the minimum that are required from the underlying mark-up.
After the three required script files from the library, we can turn to our custom <script> element in which we add the code that creates the tabs. We simply use the $(function(){}) shortcut to execute our code when the document is ready. We then call the tabs() constructor method on the jQuery object representing our tabs container element (the <ul> with an id of myTabs).
The following screenshot shows the default appearance of a tab object:
The flora or default stylesheets contain all of the style rules that will make the tabs both appear and function correctly. We could also supply our own stylesheet as long as we provide all of the required selectors. Or, we could produce our own theme using theme roller.
In the following example, we can see how to add basic aesthetic styling. We can override any rules used purely for display purposes with our own simple style rules for quick and easy customization without changing the rules related to the tab functionality.
In a new file in your text editor, create the following very small stylesheet:
This is all we need. Save the file as tabsTheme.css in your styles folder. Several class names are automatically added to the elements that make up the tabs and their associated content panels by the widget. We can make use of these class names to change particular features of the widget, such as the background image used to create the tab headings and the borders of the tab content panels.
We've specified a new image with our theme file – tab-sprite.gif. This file is used by the widget to give the tab headings the appearance of tab headings. The easiest way to create a new image is to open the existing image used by flora in an image editor and then change the colors of the various parts of the image. The original flora image can be found in the i folder, inside the themes folder, of the unpacked library.
Don't forget to link to the new stylesheet from the <head> of the underlying HTML file, and make sure the custom stylesheet appears after the flora.tabs.css file as shown here:
Once this has been added, save the altered file as tabs2.html and review it in a browser. It should look like the following screenshot (with blue instead of green styling):
By overriding just three of the rules defined by the flora theme, we can completely change the color scheme of the tabs widget, allowing us to easily integrate tabs into our existing site style.
An object can be passed to the tabs() constructor method to configure different properties of the tabbed interface. The following table provides the available properties to configure non-default behaviours when using the tabs widget:
Property
Default Value
Usage
ajaxOptions
{}
Options for remote AJAX tabs
cache
"false"
