jQuery UI 1.8: The Accordion Widget

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

jQuery UI 1.8: 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 | September 2011 | Open Source

The accordion widget is a UI widget that allows you to group content into separate panels that can be opened or closed by visitor interaction. Therefore, most of its content is initially hidden from view, much like the tabs widget.

In this article by Dan Wellman, author of jQuery UI 1.8 The User Interface Library for jQuery, we are going to cover the following topics:

  • The structure of an accordion widget
  • The default implementation of an accordion
  • Adding custom styling
  • Using the configurable options to set different behaviors
  • Working with methods for controlling the accordion
  • The built-in types of animation
  • Custom accordion events

 

(For more resources on jQuery, see here.)

 

Each container has a heading element associated with it that is used to open the container and display the content. When you click on a heading, its content will slide into view (with an animation) below it. The currently visible content is hidden, while the new content is shown whenever we click on an accordion heading.

The accordion widget is a robust and highly configurable widget that allows you to save space on your web pages, by displaying only a single panel of content at any time. The following screenshot shows an example of an accordion widget:

jQuery UI 1.8 The User Interface Library for jQuery

It's easy for our visitors to use and easy for us to implement. It has a range of configurable options that can be used to customize its appearance and behavior, and exposes a series of methods that allow you to control it programmatically. It also comes with a rich set of interaction events that we can use to hook into key interactions between our visitors and the widget.

The height of the accordion's container element will be set automatically, so that there is room to show the tallest content panel in addition to the headers. Also, by default, the size of the widget will remain fixed, so that it won't push other elements on the page around it out of the way, when content panels open or close.

 

Accordion's structure

Let's take a moment to familiarize ourselves with the underlying markup that an accordion is made of. Within the outer container is a series of links. These links are the headings within the accordion and each heading will have a corresponding content panel that opens when the header is clicked.

It's worth remembering that only one content panel can be open at a time when using the accordion widget. In a blank page in your text editor, create the following page:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet"
href="css/smoothness/jquery-ui-1.8.9.custom.css">
<title>Accordion
</title>
</head>
<body>
<div id="myAccordion">
<h2>
<a href="#">Header 1
</a>
</h2>
<div>Lorem ipsum dolor sit amet, consectetuer adipiscing
elit. Aenean sollicitudin. Sed interdum pulvinar justo.
Nam iaculis volutpat ligula. Integer vitae felis quis
diam laoreet ullamcorper.
</div>
<h2>
<a href="#">Header 2
</a>
</h2>
<div>Etiam tincidunt est vitae est. Ut posuere, mauris at
sodales rutrum, turpis tellus fermentum metus, ut
bibendum velit enim eu lectus. Suspendisse potenti.
</div>
<h2>
<a href="#">Header 3
</a>
</h2>
<div>Donec at dolor ac metus pharetra aliquam.
Suspendisse purus. Fusce tempor ultrices libero. Sed
quis nunc. Pellentesque tincidunt viverra felis.
Integer elit mauris, egestas ultricies, gravida vitae,
feugiat a, tellus.
</div>
</div>
<script
src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="development-bundle/jquery-1.3.2.js">
</script>
<script
src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="development-bundle/ui/ui.core.js">
</script>
<script
src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="development-bundle/ui/ui.accordion.js">
</script>
<script>
$(function() {
$("#myAccordion").accordion();
});
</script>
</body>
</html>

Save the file as accordion1.html in the jqueryui folder, and try it out in a browser. The widget should appear as it did in the screenshot at the start of the article, fully skinned and ready for action.

The following list shows the required dependencies of the widget:

  • jquery.ui.all.css
  • jquery-x.x.x.js
  • jquery.ui.core.js
  • jquery.ui.accordion.js

Each widget also has its own source file, and may depend on other components as well. For example, we could include some effect files to use non-standard animations on the opening accordion panels.

The order in which these files appear is important. The jQuery library must always appear first, followed by the jquery.ui.core.js file. After these files, any other files that the widget depends upon, should appear before the widget's own script file. The library components will not function as expected if files are not loaded in the correct order.

The underlying markup required for the accordion is flexible, and the widget can be constructed from a variety of different structures. In this example, the accordion headings are formed from links wrapped in <h2> elements, and the content panels are simple <div> elements.

For the accordion to function correctly, each content panel should appear directly after its corresponding header. All of the elements for the widget are enclosed within a container <div> that is targeted with the accordion() widget method.

After the required script dependencies from the library, we use a custom <script> block to transform the underlying markup into the accordion.

To initialize the widget, we use a simple id selector $("#myAccordion"), to specify the element that contains the markup for the widget, and then chain the accordion() widget method after the selector to create the accordion.

In this example, we used an empty fragment (#) as the value of the href attribute in our tab heading elements, such as:

<h2><a href="#">Header 1</a></h2>

You should note that any URL supplied for accordion headers will not be followed, when the header is clicked in the default implementation.

Similar to the tabs widget, the underlying markup that is transformed into the accordion has a series of classnames added to it, when the widget is initialized.

A number of different elements that make up the widget are given role and aria- attributes. ARIA stands for Accessible Rich Internet Applications and is a W3C recommendation for ensuring that rich-internet applications remain accessible to assisted technologies.

The accordion panels that are initially hidden from view are given the attribute aria-expanded="false" to ensure that screen readers don't discard or cannot access content that is hidden using display:none. This makes the accordion widget highly accessible.

 

Styling the accordion

ThemeRoller is the recommended tool for choosing or creating the theme of the accordion widget, but there may be times when we want to considerably change the look and style of the widget beyond what is possible with ThemeRoller. In that case, we can just style our own accordion.

In a new page in your text editor add the following code:

#myAccordion {
width:400px; border:1px solid #636363; padding-bottom:1px;
}
.ui-accordion-header {
border:1px solid #fff;
font-family:Georgia; background:#e2e2e2 none;
}
.ui-widget-content { font-size:70%; border:none; }
.ui-corner-bottom {
-moz-border-radius:4px 4px 0 0;
-webkit-border-radius:4px 4px 0 0;
border-radius:4px 4px 0 0;
}
.ui-corner-all {
-moz-border-radius:0; -webkit-border-radius:0;
border-radius:0;
}
.ui-accordion .ui-accordion-header { margin:0 0 -1px; }
#myAccordion .ui-state-active, #myAccordion .ui-widget-content
.ui-state-active { background:#fff; } .ui-state-hover,
.ui-widget-content .ui-state-hover { background:#d2d2d2;
}

Save this file as accordionTheme.css in the css folder, and link to it after the jQuery UI style sheet in the <head> of accordion1.html:

<link rel="stylesheet" href="css/accordionTheme.css">

Save the new file as accordion2.html in the jqueryui folder and view it in a browser. It should appear something like this:

jQuery UI 1.8 The User Interface Library for jQuery

As you can see from this screenshot, we've disabled the built-in rounded corners that are added by the theme file and have set alternative fonts, background colors, and border colors.

We haven't changed the widget much, but we haven't used many style rules. It would be easy to continue overriding rules in this way to build a much more complex custom theme.

 

Configuring an accordion

The accordion has a range of configurable options that allow us to change the default behavior of the widget. The following table lists the available options, their default values, and gives a brief description of their usage:

Option Default value Used to...
active first child (the first panel is open) Set the active heading on page load.
animated slide Animate the opening of content panels.
autoHeight true Automatically set height according to the biggest drawer.
clearStyle false Clear the height and overflow styles after a panel opens.
collapsible false Allow all of the content panels to be closed at the same time.
disabled false Disable the widget.
event click Specify the event on headers that trigger drawers to open.
fillSpace false Allow the accordion to fill the height of its container instead of sizing itself according to the content within it.
header > li >:first-child,>:not(li):even Specify the selector for header elements. Although it looks complex, this is a standard jQuery selector that simply targets the first-child within every odd <li> element.
icons 'header': 'ui-icon-triangle-1-e', 'headerSelected': 'ui-icon-triangle-1-s' Set the icons for the header elements and the selected state.
navigation false Enable navigation mode for accordion.
navigationFilter location.href Change the function used to obtain the ID of the content panel that should be open when the widget is initialized.

Changing the trigger event

Most of the options are self-explanatory, and the values they accept are usually Booleans, strings, or element selectors. Let's put some of them to use, so that we can explore their functionality. Change the final <script> element in accordion2.html so that it appears as follows:

<script>
(function($) {
var accOpts = {
event:"mouseover"
}
$("#myAccordion").accordion(accOpts);

})(jQuery);
</script>

Save these changes as accordion3.html. First, we create a new object literal called accOpts that contains the key event and the value mouseover, which is the event we wish to use to trigger the opening of an accordion panel. We pass this object to the accordion() method as an argument and it overrides the default option of the widget, which is click.

The mouseover event is commonly used as an alternative trigger event. Other events can also be used, for example, we can set keydown as the event, but in order for this to work, the accordion panel that we wish to open, must already be focused.

You should note that you can also set options using an inline object within the widget method, without creating a separate object. Using the following code would be equally as effective, and would often be the preferred way of coding:

<script>
(function($) {
$("#myAccordion").accordion({
event:"mouseover"
});
})(jQuery);
</script>

 

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

 

(For more resources on jQuery, see here.)

 

Changing the default active header

By default, the first header of the accordion will be selected when the widget is rendered, with its content panel open. We can change which header is selected on page load using the active option. Change the configuration object in accordion3.html, so that it appears as follows:

var accOpts = {
active: 2
};

Save this version as accordion4.html. We set the active option to the integer 2 to open the last content panel by default, and like the tab headers, accordion's headers use a zero-based index. Along with an integer, this option also accepts a jQuery selector or raw DOM element.

We can also use the Boolean value of false to configure the accordion, so that none of the content panels are open by default. Change the configuration object once again to the following:

var accOpts = {
active: false
};

Save this as accordion5.html. Now when the page loads, all of the content panels are hidden from view:

jQuery UI 1.8 The User Interface Library for jQuery

The widget will only remain closed until one of the headers is selected, and then one panel will remain open at all times. This behavior can be changed by employing the collapsible option in the configuration object:

var accOpts = {
active: false,
collapsible: true
};

Save this as accordion6.html. Now, not only is the accordion closed when the page loads, but also clicking an active header will close its associated content panel as well. As expected, when a closed header is clicked, it will show its content panel in the usual way. For usability, it is best to avoid configuring both this and the mouseover event option together in the same implementation, as the open panels would close even when the user inadvertently moused off-and-back over them.

Filling the height of its container

If the fillSpace option is set, it will override autoHeight, and force the accordion to take the full height of its container. In our examples so far, the container of the accordion has been the body of the page, and the height of the body will only be the height of its largest element. We'll need to use a new container element with a fixed height to see this option in action.

In the <head> of accordion6.html, add the following <style> element:

<style>
#container { height:600px; width:400px; }
</style>

Then wrap all of the underlying markup for the accordion in a new container element as follows:

<div id="container">
<div id="myAccordion">
<h2>
<a href="#">Header 1
</a>
</h2>
<div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Aenean sollicitudin. Sed interdum pulvinar justo. Nam iaculis
volutpat ligula. Integer vitae felis quis diam laoreet ullam
corper.
</div>
<h2>
<a href="#">Header 2
</a>
</h2>
<div>Etiam tincidunt est vitae est. Ut posuere, mauris at
sodales rutrum, turpis tellus fermentum metus, ut bibendum
velit enim eu lectus. Suspendisse potenti.
</div>
<h2>
<a href="#">Header 3
</a>
</h2>
<div>Donec at dolor ac metus pharetra aliquam. Suspendisse
purus. Fusce tempor ultrices libero. Sed quis nunc.
Pellentesque tincidunt viverra felis. Integer elit mauris,
egestas ultricies, gravida vitae, feugiat a, tellus.
</div>
</div>
</div>

Finally, change the configuration object to use the fillSpace option:

var accOpts = {
fillSpace: true
};

Save the changes as accordion7.html. The new container is given a fixed height and width using the CSS specified in the <head> of the page.

This is not the best way to add style to our pages. But when we only have a single selector and two rules, it seems excessive to create a new style sheet.

The fillSpace option forces the accordion to take the entire height of its container, and restricting the width of the container naturally reduces the width of the widget too. This page should appear as follows:

jQuery UI 1.8 The User Interface Library for jQuery

Accordion animation

The accordion widget comes with the built-in slide animation that is enabled by default, and has been present in all of our examples so far. Disabling this animation is as easy as supplying false as the value of the animated option. Remove the <style> tag from the <head> of the page in accordion7.html, and remove the additional container <div>, then change the configuration object so that it appears as follows:

var accOpts = {
animated: false
};

Save this as accordion8.html. This will cause each content panel to open immediately instead of sliding-open nicely whenever a header is clicked.

An alternate animation has also been built into the widget—the bounceslide animation. However, to use this alternate animation, we need to add a link to the jquery.effects.core.js file.

Directly after the link to ui.accordion.js at the bottom of the <body>, add the following line of code:

<script
src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="development-bundle/ui/jquery.effects.core.js">
</script>

Now, change the configuration object in our custom <script> element so that it appears like this:

var accOpts = {
animated: "bounceslide"
};

Save these changes as accordion9.html. Although the accordion panels close in exactly the same way as they did in previous examples, when they open they bounce a few times at the end of the animation. It's a great effect, and as we saw in this example, it's easy to use.

In addition to the two preconfigured animations, we can also use any of the different easing effects defined within the jquery.effects.core.js file, including the following:

  • easeInQuad
  • easeInCubic
  • easeInQuart
  • easeInQuint
  • easeInSine
  • easeInExpo
  • easeInCirc
  • easeInElastic
  • easeInBack
  • easeInBounce

Each of these easing methods is complimented by easeOut and easeInOut counterparts. For the complete list, see the jquery.effects.core.js file.

See the jQuery UI demo site for some great examples of the accordion effects: http://jqueryui.com/demos/accordion/

The easing effects don't change the underlying animation, which will still be based on the slide animation. But they do change how the animation progresses. For example, we can make the content panels bounce both on opening and closing animations, by using the easeOutBounce easing effect in our configuration object:

var accOpts = {
animated: "easeOutBounce"
};

Save this file as accordion10.html and view it in a browser. Most of the easing effects have opposites, for example, instead of making the content panels bounce at the end of the animation, we can make them bounce at the start of the animation using the easeInBounce easing effect.

Another option that has an effect on animations is the clearStyle property, which resets height and overflow styles after each animation. Remember that animations are enabled by default, but this option isn't. Change the configuration object in accordion10.html to the following:

var accOpts = {
clearStyle: true,
animated: "easeOutBounce"
};

Save this as accordion11.html. Now when the page is run, the accordion will not keep to a fixed size; it will grow or shrink depending on how much content is in each panel. It doesn't make much of a difference in this example, but the property really comes into its own when using dynamic content, when we may not always know how much content will be within each panel when the panel content changes frequently.

 

Accordion events

The accordion exposes three custom events, which are listed in the following table:

Event Triggered when...
change The active header has changed.
changestart The active header is about to change.
create The widget has been created.

The change event is triggered every time the active header (and its associated content panel) is changed. It fires at the end of the content panel's opening animation, or if animations are disabled, immediately (but still after the active panel has been changed).

The changestart event is fired as soon as the new header is selected, that is before the opening animation (or before the active panel has changed, if animations are disabled). The create event is fired as soon as the widget has been initialized.

Using the change event

Let's see how we can use these events in our accordion implementations. In accordion11.html, change the configuration object so that it appears as follows:

var accOpts = {
change: function(e, ui) {
$(".notify").remove();
$("<div />", {
"class": "notify",
text: ([
ui.newHeader.find("a").text(),
"was activated,",
ui.oldHeader.find("a").text(),
"was closed"].join(" ")
)
}).insertAfter("#myAccordion").fadeOut(2000, function(){
$(this).remove();
});
});
$("#myAccordion").accordion(accOpts);
});

Save this as accordion12.html. In this example, we use the change configuration option, to specify an anonymous callback function that is executed every time the active panel is changed. This function will automatically receive two objects as arguments. The first object is the event object, which contains the original browser event object.

The second argument is an object, which contains useful information about the widget, such as the header element that was activated (ui.newHeader) and the header that was deactivated (ui.oldHeader). The second object is a jQuery object, so we can call jQuery methods directly on it.

In this example, we navigate down to the <a> element within the header and display its text content in an information box, which is appended to the page and then removed after a short interval with a fading animation.

For reference, the ui object also provides information on the content panels in the form of ui.newContent and ui.oldContent properties.

Once a header has been activated, and its content panel shown, the notification will be generated:

jQuery UI 1.8 The User Interface Library for jQuery

The changestart event

The changestart event can be used in exactly the same way, and any callback function we specify using this event also receives the e and ui objects to use. Change the configuration object from the last example to as follows:

var accOpts = {
changestart: function(e, ui) {
$("<div />", {
"class": "notify",
text: ([ui.newHeader.find("a").text(),
"was activated,", ui.oldHeader.find("a").text(),
"was closed"].join(" "))
}).insertAfter("#myAccordion").fadeOut(2000, function(){
$(this).remove();
});
};

Save this as accordion13.html. All that's changed, is the property that we're targeting with our configuration object. When we run the page, we should find that everything is exactly as it was before, except that our notification is produced before the content panel animation instead of after it.

There are also events such as accordionchange and accordionchangestart for use with the standard jQuery bind() method, so that we can specify a callback function to execute outside of the accordion configuration.

 

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

 

(For more resources on jQuery, see here.)

 

Accordion navigation

Along with a standard content accordion, the widget can also be put to good use as a navigation menu through the simple addition of some proper href attributes and the navigation option. We'll need to create two new pages to fully appreciate the effect of this option. In accordion13.html, change the underlying markup for the accordion to the following:

<div id="container" class="ui-helper-clearfix">
<div id="navCol">
<h2>
<a href="#me" title="About Me">About Me
</a>
</h2>
<div>
<a href="accordionMe.html#me" title="Bio">My Bio
</a>
<a href="accordionMe.html#me" title="Contact Me">Contact Me
</a>
<a href="accordionMe.html#me" title="Resume">My Resume
</a>
</div>
<h2>
<a href="#js" title="JavaScript">JavaScript
</a>
</h2>
<div>
<a href="accordionJS.html#js" title="Tutorials">Tutorials
</a>
<a href="accordionJS.html#js" title="AJAX">AJAX
</a>
<a href="accordionJS.html#js" title="JavaScript
Apps">JavaScript Apps
</a>
</div>
</div>
<div id="contentCol">
<h1>Page 1
</h1>
</div>
</div>

Then change the configuration object, so that it appears as follows:

var accOpts = {
navigation: true
};

Save this file as accordion14.html, then save it again as accordionMe.html and accordionJS.html, to give us the two extra example pages we need for this example. In the <body> of the page, we've added a new outer container to hold all the page content and have added two inner containers within this—one for the accordion widget that will appear as a navigation menu, and the other for content. In this example, the two pages just have <h1> elements denoting which page is open.

The underlying markup that the accordion is built from has also changed. We've added classnames and href attributes to the links within the accordion headers that include fragment identifiers. Adding the href is critical to the functioning of the navigation accordion.

In the final <script> element, we set the navigation option to true. The navigation option changes how the widget appears when the page is initially loaded.

Instead of activating the first header when the accordion is initialized, it instead looks at the location.href property of the window. If the contents of the location.href property match the href attribute of one of the accordion headers, that header will be activated.

When we run accordion14.html in a browser, and select one of the links in the second content panel, the page will navigate to accordionJS.html and the second header will automatically be activated. The navigation property gives us a great way of maintaining state between pages for the widget.

We also need some additional styles in order to make sure that the accordion and the page appear correctly. In a new page in your text editor, create the following file:

#navCol { width:250px; float:left; }
#contentCol { float:left; }
#contentCol h1 { text-indent:20px; font-family:Georgia; }
#navCol .ui-accordion-header {
display:block; padding-left:40px;
}
.ui-accordion-content a {
font-size:70%; text-decoration:none; display:block;
}
.ui-accordion-content a:hover { text-decoration:underline; }

Save this in the css folder as accordionTheme2.css. We don't need many styles for this example; we just need to arrange the containers and set some basic aesthetics for the accordion and the links within it.

The following screenshot shows how the page will appear when navigating from accordion14.html to accordionJS.html:

jQuery UI 1.8 The User Interface Library for jQuery

When going back to the first page from the second page, the first header should once again be activated.

 

Accordion methods

The accordion includes a selection of methods that allow you to control and manipulate the behavior of the widget programmatically. Some of the methods are common to each component of the library, such as the destroy method that is used by every widget. The following table lists the unique methods for the accordion widget:

Method Use
activate Programmatically activate a header. This is analogous to the header being selected by the visitor.
resize Resize of the accordion when the fillSpace option is set to true and when the contents on an accordion has changed.

In addition to the accordion-specific activate and resize methods, the destroy, enable, disable, option, and widget methods are also available.

Header activation

The activate method can be used to programmatically show or hide different drawers. We can easily test this method using a textbox and a new button. In accordion15.html, add the following new markup directly after the accordion:

<label for="activateChoice">Enter a header index to activate
</label>
<input id="activateChoice">
<button type="button" id="activate">Activate</button>

Now change the final <script> element so that it appears as follows:

<script>
(function($) {
$("#myAccordion").accordion();
$("#activate").click(function() {
$("#myAccordion").accordion("activate",
parseInt($("#activateChoice").val(), 10));
});
})(jQuery);
</script>

Save the new file as accordion15.html. The activate method takes an additional argument. It expects to receive the index (zero-based) number of the header element to activate. In this example, we obtain the header to activate, by returning the value of the text input. We convert it to an integer using the parseInt() function of JavaScript because the val() jQuery method returns a string.

If an index number that doesn't exist is specified, nothing will happen. The first header will be activated if no index is specified. If a value other than an integer is specified, nothing will happen; the script will fail silently, without errors, and the accordion will continue to function as normal.

Resizing an accordion panel

Change the underlying markup for the accordion widget in accordion11.html, so that the third header points to a remote text file and the third panel is empty. The heading element should also be given an id attribute:

<div id="myAccordion">
<h2>
<a href="#">Header 1
</a>
</h2>
<div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Aenean sollicitudin. Sed interdum pulvinar justo. Nam iaculis
volutpat ligula. Integer vitae felis quis diam laoreet
ullamcorper.
</div>
<h2>
<a href="#">Header 2
</a>
</h2>
<div>Etiam tincidunt est vitae est. Ut posuere, mauris at sodales
rutrum, turpis tellus fermentum metus, ut bibendum velit enim
eu lectus. Suspendisse poten-ti.
</div>
<h2 id="remote">
<a href="remoteAccordion.txt">Remote
</a>
</h2>
<div>
</div>
</div>

Then change the final <script> element, so that it appears as follows:

(function($){
var accOpts = {
changestart: function(e, ui) {
if (ui.newHeader.attr("id") === "remote") {
$.get(ui.newHeader.find("a").attr("href"),
function(data) {
ui.newHeader.next().text(data);
});
}
},
change: function(e, ui) {
ui.newHeader.closest("#myAccordion").accordion("resize");
}
};
$("#myAccordion").accordion(accOpts);
})(jQuery);

Save this file as accordion16.html. In our configuration object, we use the changestart event to check whether the id of the element matches the id we gave to our remote accordion heading.

If it does, we get the contents of the text file specified in the <a> element's href attribute, using jQuery's get() method. If the request returns successfully, we add the contents of the text file to the empty panel after the header. This all happens before the panel opens.

We then use the change event to call the resize method on the accordion, after the panel has opened.

When we run the page in a browser, the contents of the remote text file should be sufficient to cause a scroll bar to appear within the content panel. Calling the resize method allows the widget to read just itself, so that it can contain all of the newly added content without displaying the scroll bar.

The widget will automatically display the configured spinner when loading remote content.

 

Accordion interoperability

Does the accordion widget play nicely with other widgets in the library? Let's take a look and see whether the accordion can be combined with the tabs widget.

Change the underlying markup for the accordion, so that the third content panel now contains the markup for a set of tabs, and the third heading no longer points to the remote text file:

<div id="myAccordion">
<h2>
<a href="#">Header 1
</a>
</h2>
<div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Aenean sollicitudin. Sed interdum pulvinar justo. Nam iaculis
volutpat ligula. Integer vitae felis quis diam laoreet
ullamcorper.
</div>
<h2>
<a href="#">Header 2
</a>
</h2>
<div>Etiam tincidunt est vitae est. Ut posuere, mauris at sodales
rutrum, turpis tellus fermentum metus, ut bibendum velit enim
eu lectus. Suspendisse potenti.
</div>
<h2>
<a href="#">Header 3
</a>
</h2>
<div>
<div id="myTabs">
<ul>
<li><a href="#0"><span>Tab 1</span></a></li>
<li><a href="#1"><span>Tab 2</span></a></li>
</ul>
<div id="0">This is the content panel linked to the first
ab, it is shown by default.
</div>
<div id="1">This content is linked to the second tab and
will be shown when its tab is clicked.
</div>
</div>
</div>
</div>

We should also link to the source file for the tabs widget, after the accordion's source file. Next, change the final <script> element so that it appears as follows:

<script>
(function($) {
$("#myAccordion").accordion();
$("#myTabs").tabs();
})(jQuery);
</script>

Save this file as accordion17.html. All we've done with this file is add a simple tab structure to one of the accordion's content panels. In the <script> at the end of the page, we just call the accordion and tab's widget methods. No additional or special configuration is required.

The page should appear as follows, when the third accordion heading is activated:

jQuery UI 1.8 The User Interface Library for jQuery

The widgets are compatible the other way round; that is we can have an accordion within one of the tab's content panels without any adverse effects as well.

Summary

We first looked at what the accordion does and how it is targeted by the CSS framework. We then moved on, to look at the configurable options that can be used with accordion. We saw that we can use these options to change the behavior of the widget, such as specifying an alternative heading to be open by default, whether the widget should expand to fill the height of its container, or the event that triggers the opening of a content drawer.

Along with configurable options, we saw that the accordion exposes several custom events. Using them, we can specify callback functions during configuration, or bind to them after configuration to execute additional functionality, in reaction to different things happening to the widget.

Next, we looked at the accordion's default animation and how we can add simple transition effects to the opening of content panels in the form of easing effects. We saw that to make use of non-standard animations or easing effects, the jquery.effects.core.js file needs to be included.

In addition to looking at these options, we also saw that there are a range of methods which can be called on the accordion to make it do things programmatically. Like the tabs widget, the accordion is a flexible and robust widget that provides essential functionality in an aesthetically pleasing format.


Further resources on this subject:


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 Mobile First Look
jQuery Mobile First Look

ASP.NET jQuery Cookbook
ASP.NET jQuery Cookbook

PHP jQuery Cookbook
PHP jQuery Cookbook

jQuery Plugin Development Beginner's Guide
jQuery Plugin Development Beginner's Guide

CMS Design Using PHP and jQuery
CMS Design Using PHP and jQuery

jQuery UI Themes Beginner's Guide
jQuery UI Themes Beginner's Guide

jQuery 1.4 Reference Guide
jQuery 1.4 Reference Guide

Learning jQuery 1.3
Learning jQuery 1.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