Tabs in jQuery UI 1.7

Exclusive offer: get 50% off this eBook here
jQuery UI 1.7: The User Interface Library for jQuery

jQuery UI 1.7: The User Interface Library for jQuery — Save 50%

Build highly interactive web applications with ready-to-use widgets from the jQuery User Interface library

$26.99    $13.50
by Dan Wellman | November 2009 | MySQL Open Source PHP Web Development

In this article by Dan Wellman, we will look at the tabs component of jQuery UI; a simple but effective means of presenting structured content in an engaging and interactive widget.

In this article, we will discuss the following topics:

  • The default implementation of the widget
  • How the CSS framework targets tab widgets
  • How to apply custom styles to a set of tabs
  • Configuring tabs using their options
  • Built-in transition effects for content panel changes

The UI tabs widget is used to toggle visibility across a set of different elements, each element containing content that can be accessed by clicking on its heading which appears as an individual tab. The tabs are structured so that they line up next to each other, whereas the content sections are layered on top of each other, with only the top one visible. Clicking a tab will highlight the tab and bring its associated content panel to the top of the stack. Only one content panel can be open at a time.

The following screenshot shows the different components of a set of UI tabs:

jQuery UI 1.7: The User Interface Library for jQuery

A basic tab implementation

The structure of the underlying HTML elements, on which tabs are based, is rigid and widgets require a certain number of elements for them to work.

The tabs must be created from a list element (ordered or unordered) and each list item must contain an <a> element. Each link will need to have a corresponding element with a specified id that it is associated with the link's 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:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<link rel="stylesheet" type="text/css"
href="development-bundle/themes/smoothness/ui.all.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>jQuery UI Tabs Example 1</title>
</head>
<body>
<div id="myTabs">
<ul>
<li><a href="#a">Tab 1</a></li>
<li><a href="#b">Tab 2</a></li>
</ul>
<div id="a">This is the content panel linked to the first tab,
 it is shown by default.</div>
<div id="b">This content is linked to the second tab and
will be shown when its tab is clicked.</div>
</div>
<script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="development-bundle/jquery-1.3.2.js"></script>
<script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="development-bundle/ui/ui.core.js"></script>
<script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="development-bundle/ui/ui.tabs.js"></script>
<script type="text/javascript">
$(function(){
$("#myTabs").tabs();
});
</script>
</body>
</html>

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:

  • ui.all.css
  • jquery-1.3.2.js
  • ui.core.js
  • ui.tabs.js

A tab widget consists of several standard HTML elements arranged in a specific manner (these can be either hardcoded into the page, or added dynamically, or can be a mixture of both depending on the requirements of your implementation).

  • An outer container element, which the tabs method is called on
  • A list element( <ul> or <ol>)
  • An <a> element for each tab
  • An element for the content of each tab

The first two elements within the outer container make the clickable tab headings, which are used to show the content section that is associated with the tab. Each tab should include a list item containing the link.

The href attribute of the link should be set as a fragment identifier, prefixed with #. It should match the id attribute of the element that forms the content section, with which it is associated. The content sections of each tab are created by the elements. The id attribute is required and will be targeted by its corresponding element. We've used elements in this example as the content panels for each tab, but other elements, such as elements can also be used. The elements discussed so far, along with their required attributes, are the minimum that are required from the underlying markup.We link to several <script> resources from the library at the bottom of the <body> before its closing tag. Loading scripts last, after stylesheets and page elements is a proven technique for improving performance. After linking first to jQuery, we link to the ui.core.js file that is required by all components (except the effects, which have their own core file). We then link to the component's source file that in this case is ui.tabs.js.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() widget method on the jQuery object, representing our tabs container element (the <ul> with an id of myTabs).When we run this file in a browser, we should see the tabs as they appeared in the first screenshot of this article(without the annotations of course).

Tab CSS framework classes

Using Firebug for Firefox (or another generic DOM explorer) we can see that a variety of class names are added to the different underlying HTML elements that the tabs widget is created from, as shown in the following screenshot:

jQuery UI 1.7: The User Interface Library for jQuery

Let's review these briefly. To the outer container < div> the following class names are added:

Class name

Purpose

ui-tabs

Allows tab-specific structural CSS to be applied.

ui-widget

Sets generic font styles that are inherited by nested elements.

ui-widget-content

Provides theme-specific styles.

ui-corner-all

Applies rounded corners to container.

The first element within the container is the < ul> element. This element receives the following class names:

Class name

Purpose

ui-tabs-nav

Allows tab-specific structural CSS to be applied.

ui-helper-reset

Neutralizes browser-specific styles applied to <ul> elements.

ui-helper-clearfix

Applies the clear-fix as this element has children that are floated.

ui-widget-header

Provides theme-specific styles.

ui-corner-all

Applies rounded corners.

The individual < li> elements are given the following class names:

Class name

Purpose

ui-state-default

Applies theme-specific styles.

ui-corner-top

Applies rounded corners to the top edges of the elements.

ui-tabs-selected

This is only applied to the active tab. On page load of the default implementation this will be the first tab. Selecting another tab will remove this class from the currently selected tab and apply it to the new tab.

ui-state-active

Applies theme-specific styles to the currently selected tab. This class name will be added to the tab that is currently selected, just like the previous class name. The reason there are two class names is that ui-tabs-selected provides the functional CSS, while ui-state-active provides the visual, decorative styles.

The < a> elements within each < li> are not given any class names, but they still have both structural and theme-specific styles applied to them by the framework.

Finally, the elements that hold each tab's content are given the following class names:

Class name

Purpose

ui-tabs-panel

Applies structural CSS to the content panels

ui-widget-content

Applies theme-specific styles

ui-corner-bottom

Applied rounded corners to the bottom edges of the content panels

All of these classes are added to the underlying elements automatically by the library, we don't need to manually add them when coding the page.

As these tables illustrate, the CSS framework supplies the complete set of both structural CSS styles that control how the tabs function and theme-specific styles that control how the tabs appear, but not how they function. We can easily see which selectors we'll need to override if we wish to tweak the appearance of the widget, which is what we'll do in the following section.

jQuery UI 1.7: The User Interface Library for jQuery Build highly interactive web applications with ready-to-use widgets from the jQuery User Interface library
Published: November 2009
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

Applying a custom theme to the tabs

In the next example, we can see how to change the tabs' basic appearance. We can override any rules used purely for display purposes with our own style rules for quick and easy customization without changing the rules related to the tab functionality or structure.

In a new file in your text editor, create the following very small stylesheet.

#myTabs {
border:1px solid #636363; width:400px;
background:#c2c2c2 none; padding:5px;
}
.ui-widget-header {
border:0; background:#c2c2c2 none; font-family:Georgia;
}
#myTabs .ui-widget-content {
border:1px solid #aaaaaa; background:#ffffff none;
font-size:80%;
}
.ui-state-default, .ui-widget-content .ui-state-default {
background:#a2a2a2 none; border:1px solid #636363;
}
.ui-state-active, .ui-widget-content .ui-state-active {
background:#ffffff none; border:1px solid #aaaaaa;
}

This is all we need. Save the file as tabsTheme.css in your css folder. If you compare the class names with the tables on the previous pages you'll see that we're overriding the theme-specific styles. Because we're overriding the theme file, we need to meet or exceed the specificity of the selectors in theme.css. This is why we target multiple selectors sometimes.

In this example we override some of the rules in ui.tabs.css. We need to use the ID selector of our container element along with the selector from ui.theme.css (.ui-widget-content) in order to beat the double class selector .ui-tabs .ui-tabs-panel.

Don't forget to link to the new stylesheet from the < head> of the underlying HTML file, and make sure the custom stylesheet we just created appears after the ui.tabs.css file:

<link rel="stylesheet" type="text/css" href="css/tabsTheme.css">

The rules that we are trying to override will be not overridden by our theme file if the stylesheets are not linked to in the correct order. Save the altered file as tabs2.html in the jqueryui folder and view it in a browser. It should look like the following screenshot:

jQuery UI 1.7: The User Interface Library for jQuery

Our new theme isn't dramatically different from the default smoothness. However, we can tweak its appearance to suit our own needs and preferences by adding just a few additional styles.

Configurable options

Each of the different components in the library has a series of different options that control which features of the widget are enabled by default. An object literal can be passed in to the tabs widget method to configure these options.

The available options to configure non-default behaviors when using the tabs widget are shown in the following table:

Property

Default value

Usage

ajaxOptions

 

{}

 

When using AJAX tabs and importing remote data into the tab panels, additional AJAX options are supplied via this property. We can use any of the options exposed by jquery's $.ajax method such as data, type, url, and so on.

cache

 

 

false

 

Load remote tab content only once
(lazy-load).

collapsible

 

false

Allows an active tab to be unselected if it is clicked.

cookie

 

null

 

Show active tab using cookie data on
page load.

disabled

 

 

[]

 

Disable specified tabs on page load. Supply an array of index numbers to disable specific tabs.

event

 

 

"click"

 

The tab event that triggers the display of content.

fx

 

 

null

 

Specify an animation effect when
changing tabs. Supply a literal object or an array of animation effects.

idPrefix

 

"ui-tabs-"

 

Used to generate a unique ID and fragment identifier when a remote tab's link element has no title attribute.

panelTemplate

"<div></div>"

A string specifying the elements used for the content section of a dynamically created tab widget.

selected

 

0

The tab selected by default when the
widget is rendered (overrides the cookie property).

spinner

 

"Loading&#B230"

Specify the loading spinner for remote tabs.

tabTemplate

 

 

<li><a href="#{href}"><span>#{label}
</span></a></li>

A string specifying the elements used when creating new tabs dynamically. Notice that both an <a> and a <span> tag are created when new tabs are added by the widget. The #{href} and #{label} parts of the string are used internally by the widget and are replaced with actual values by the widget.

Selecting a tab

Let's look at how these configurable properties can be used. For example, let's configure the widget so that the second tab is displayed when the page loads. Remove the < link> for tabsTheme.css in the < head> and change the final < script> element so that it appears as follows:

<script type="text/javascript">

$(function(){

var tabOpts = {
selected: 1
};

$("#myTabs").tabs(tabOpts);
});
</script>

Save this as tabs3.html. The different tabs and their associated content panels are represented by a numerical index starting at zero, much like a standard JavaScript array. Specifying a different tab to open by default is as easy as supplying its index number as the value for the selected property. When the page loads, the second tab should be selected.

jQuery UI 1.7: The User Interface Library for jQuery

We've switched to the default smoothness theme so that we can focus on how the properties work. Along with changing which tab is selected  we can also specify that no tabs should be initially selected by supplying null as the value for this property. This will cause the widget to appear as follows on page load:

jQuery UI 1.7: The User Interface Library for jQuery

Disabling a tab

You may want a particular tab to be disabled until a certain condition is met. This is easily achieved by manipulating the disabled property of the tabs. Change the configuration object in tabs3.html to this:

var tabOpts = {
disabled: [1]
};

Save this as tabs4.html in your jqueryui folder. In this example, we remove the selected property and add the index of the second tab to the disabled array. We could add the indices of other tabs to this array as well, separated by a comma, to disable multiple tabs by default.

When the page is loaded in a browser, the second tab has the class name ui-widget-disabled applied to it, and will pick up the disabled styles from ui.theme.css. It will not respond to mouse interactions in any way as shown in the following screenshot:

jQuery UI 1.7: The User Interface Library for jQuery

Transition effects

We can easily add attractive transition effects using the fx property. These are displayed when tabs are open and close. This property is configured using another object literal (or an array) inside our configuration object, which enables one or more effects. Let's enable fading effects using the following configuration object:

var tabOpts = {
fx: {
opacity: "toggle",
duration: "slow"
}
};

Save this file as tabs5.html in your jqueryui folder. The fx object that we created has two properties. The first property is the animation. To use fading, we specify opacity as this is what is adjusted. We would specify height as the property name instead to use opening animations. Toggling the opacity simply reverses its current setting. If it is currently visible, it is made invisible and vice-versa.

The second property, duration, specifies the speed at which the animation occurs. The values for this property are slow, normal (default value), or fast. We can also supply an integer representing the number of milliseconds the animation should run for.

When we run the file we can see that the tab content slowly fades out as a tab closes and fades in when a new tab opens. Both animations occur during a single tab interaction. To only show the animation once, when a tab closes for example, we would need to nest the fx object within an array. Change the configuration object in tabs5.html so that it appears as follows:

var tabOpts = {
fx: [{
opacity: "toggle",
duration: "slow"
},
null]
};

The closing effect of the currently open content panel is contained within an object in the first item of the array, and the opening animation of the new tab is the second. By specifying null as the second item in the array we disable the opening animations when a new tab is selected.

We can also specify different animations and speeds for opening and closing animations by adding another object as the second array item instead of null. Save this as tabs6.html and view the results in a browser.

Collapsible tabs

By default when the currently active tab is clicked, nothing happens. But we can change this so that the currently open content panel closes when its tab heading is selected. Change the configuration object in tabs6.html so that it appears as follows:

var tabOpts = {
collapsible: true
};

Save this version as tabs7.html. This option allows all of the content panels to be closed, much like when we supplied null to the selected property earlier on. Clicking a deactivated tab will select the tab and show its associated content panel. Clicking the same tab again will close it, shrinking the widget down so that only the header and tabs are displayed).

Summary

In this article, we have discussed the following topics:

  • The default implementation of the widget
  • How the CSS framework targets tab widgets
  • How to apply custom styles to a set of tabs
  • Configuring tabs using their options
  • Built-in transition effects for content panel changes

If you have read this article you may be interested to view :

 

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.

Books From Packt

jQuery 1.3 with PHP
jQuery 1.3 with PHP

Drupal 6 JavaScript and jQuery
Drupal 6 JavaScript and jQuery

Learning jQuery 1.3
Learning jQuery 1.3

PHP Team Development
PHP Team Development

ICEfaces 1.8: Next Generation Enterprise Web Development
ICEfaces 1.8: Next Generation Enterprise Web Development

Symfony 1.3 Web Application Development
Symfony 1.3 Web Application Development

JBoss AS 5 Development
JBoss AS 5 Development

JBoss RichFaces 3.3
JBoss RichFaces 3.3

Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software