New Revised CSS Library Forums Web Tools
FAQs Awards Usage Terms Contact

Categories
Other Sections
Sweet Ads
Compatibility
Bookmark online:


FF1+ IE6+ Opera 9+

Accordion Content script (v2.0)

Author: Dynamic Drive

Feb 16th, 12' (v2.0): Added option ("scrolltoheader") to scroll to the expanded header in question after it expands (useful if a header contains long content).

Description: Group contents together and reveal them on demand when the user clicks on their associated headers, with Accordion content script! Specify whether only one content within the group should be open at any given time, style the headers depending on their content state, and even enable persistence so the state of the contents is preserved within a browser session. The script enlists the help of the jQuery library for its engine. There are lots of configurable options, so lets get to them:

  • Headers and their contents to expand/collapse on the page are identified through the use of shared CSS class names for easy set up.
  • Ability to specify which contents should be expanded by default when the page first loads.
  • Specify whether only one content should be open at any given time (collapse previous before expanding current.
  • Ajax content support added, so a given header's content can be dynamically fetched from an external file and only when requested. New in v1.9
  • Specify whether at least one header should be open at all times (so never all closed).
  • Set whether the headers should be activated "click" or "mouseover". If the headers themselves are hyperlinked and set to activate via "click", you can optionally have the browser go to that URL upon expanding the content, instead of doing nothing. New in v1.7
  • Ability to scroll to the expanded header in question after it expands, which is useful if the header contains a lot of content and expanding it changes the scroll position of the document. New in v2.0
  • When headers are set to be activated "mouseover", set delay (in millisec) before this happens. New in v1.6
  • Enable optional persistence so when the user expands a header then returns to the page within the same browser session, the content state is preserved.
  • Style the two states of the headers easily by setting two different CSS classes to be added to the header depending on whether its content is expanded or collapsed. You can also add additional HTML to the beginning or end of each header, such as an icon image that reflects the current state of the content.
  • Two event handlers oninit() and onopenclose() can be used to run custom code when an Accordion Content first loads and whenever a header is opened/closed, respectively.
  • Arbitrary links can be defined elsewhere on the page performing the same functions as if the user had directly clicked on a header, such as expand a particular header, toggle a header, or expand all headers within a group.
  • A link from another page linking to the target page can cause the desired headers on the later to expand when loaded, via the URL parameter string.

You don't have to be an accordion player to appreciate this script!

Note: See also Horizontal Accordion script.

Demos:

Mouseover example:

Expand 1st header | Collapse 1st header | Toggle 2nd header

Dogs

The dog is a domestic subspecies of the wolf, a mammal of the Canidae family of the order Carnivora. The term encompasses both feral and pet varieties and is also sometimes used to describe wild canids of other subspecies or species. The domestic dog has been (and continues to be) one of the most widely-kept working and companion animals in human history, as well as being a food source in some cultures.

Cats

The Cat, also known as the Domestic Cat or House Cat to distinguish it from other felines, is a small carnivorous species of crepuscular mammal that is often valued by humans for its companionship and its ability to hunt vermin. It has been associated with humans for at least 9,500 years.

Rabbits

Rabbits are small mammals in the family Leporidae of the order Lagomorpha, found in several parts of the world. There are seven different genera in the family classified as rabbits, including the European rabbit (Oryctolagus cuniculus), cottontail rabbit (genus Sylvilagus; 13 species), and the Amami rabbit (Pentalagus furnessi, endangered species on Amami O-shima, Japan). There are many other species of rabbit, and these, along with cottontails, pikas, and hares, make up the order Lagomorpha. Rabbits generally live between four and twenty years.

 
  • Headers activated onMouseover, with 200 millisec delay.
  • 1st content open by default.
  • Only one content allowed open at any time.
  • Persist state of opened contents within browser session
  • Headers of opened contents get a CSS class of "openpet" applied.
  • Reload page and select the 3rd content using a URL parameter
Ajax contents example:

Langkawi
Japan
Thailand

 
  • All contents defined inside external files and fetched the 1st time each header is expanded.
  • Script scrolls to the expanded header after it's explicitly opened by the user.
  • Headers of opened contents get a CSS class of "openplace" applied.
  • Animation duration set to 500 milliseconds.
 
onClick example with icon indicators:

Collapse all | Expand all

What is JavaScript?
JavaScript is a scripting language originally developed by Netscape to add interactivity and power to web documents. It is purely client side, and runs completely on the client's browser and computer.
Difference betwen Java & JavaScript?
Java is completely different from JavaScript- the former is a compiled language while the later is a scripting language.
What is Ajax?
Ajax is a group of inter-related web development techniques used for creating interactive web applications. A primary characteristic is the increased responsiveness and interactiveness of web pages achieved by exchanging small amounts of data with the server "behind the scenes" so that the entire web page does not have to be reloaded each time the user performs an action. This is intended to increase the web page's interactivity, speed, functionality, and usability.
  • Headers activated onClick.
  • No contents open by default.
  • Multiple contents can be open at the same time.
  • Script scrolls to the expanded header after it's explicitly opened by the user.
  • Headers of opened and closed contents each get a CSS class of "openlanguage" and "closedlanguage" applied, respectively.
  • Headers of opened and closed contents each get a different icon image added in front of it (arbitrary HTML).
  • Reload page and select the 1st, 2nd, and 3rd contents using a URL parameter

Directions: Developer's View

Step 1: Insert the following code in the HEAD section of your page

Select All

Note the "doctype" code at the very top- this script requires a valid doctype in order to work correctly. You can remove it if your page already has one declared. The code above references 1 external .js file and an image file, which you need to download below (right click/ select "Save As"):

  1. ddaccordion.js (customize "ajaxloadingmsg" variable near the top inside this file).
  2. loading2.gif (image used to indicate Ajax content is loading, if enabled)

By default, upload this file to the same directory as where your webpage resides.

Step 2: Insert the below sample code into the BODY section of your page:

Select All

It contains the HTML for two demos. That's it for installation!

Set up Information

Setting up this script on your site involves first identifying the headers and their corresponding contents on your page with two shared CSS class names, for example:

<h3 class="mypets">Dogs</h3>
<div class="thepet">
doggy content here...
</div>

<h3 class="mypets">Cats</h3>
<div class="thepet">
kitty content here...
</div>

<h3 class="mypets">Rabbits</h3>
<div class="thepet">
<a class="hiddenajaxlink" href="mycontent.htm">LangKawi</a>
</div>

<h3 class="mypets">Rabbits</h3>
<div class="thepet">
<a class="hiddenajaxlink" href="mycontent2.htm">Japan</a>
</div>

The element with the red CSS class in this case are your headers, and the green your sub content element containing the desired content to show and hide. This content can either be inline HTML markup, or ajax content that's defined inside an external file on your server and only loaded when the header is expanded. To specify ajax content for a header, inside the corresponding content container, just define a link that points to an external file on your server that houses this content using the syntax:

<a class="hiddenajaxlink" href="/path/content.htm">Link anchor text</a>

The link must carry a CSS class of "hiddenajaxlink" to give it special meaning. When such a link is detected the script will dynamically load the file specified inside this link and use it as the corresponding header's content the first time it is expanded, overwriting the link and everything else inside the content container.

FYI: For Ajax based Header Contents, the content is only fetched the first time the header is actually expanded, then subsequently cached from thereon. The content is also accessible to users with JavaScript disabled, since for those users, all the headers appear expanded by default, with the link to the ajax content visible and accessible.

Then, in the HEAD section of the script, call ddaccordion.init() with the appropriate options:

Option Description
headerclass Shared CSS class name of headers containers.
contentclass Shared CSS class name of contents containers.
revealtype Reveal content when user clicks or onmouseover the header? Valid values are: "click", "clickgo", or "mouseover".

The difference between "click" and clickgo" is only visible if your headers are hyperlinked. With "click", that link is disabled, so clicking each header will only expand the corresponding content. With "clickgo", the script will first expand the content, then navigate to the URL specified in the header afterwards.

mouseoverdelay If revealtype above is set to "mouseover", set delay in milliseconds before header expands onMouseover.
collapseprev Collapse previous content (so only one open at any time)? true/false.
defaultexpanded Index(es) of content(s) that should be open by default in the format [index1, index2, etc], where 0=1st content, 1=2nd content etc. [] denotes no content should be open by default.
scrolltoheader

v2.0 option

If set to true will scroll to the expanded header after its content has been revealed. It is only triggered when the user explicitly expands a header (either by clicking on a header or calling the expandone() method), and NOT when the page initially loads. Defaults to false.
onemustopen Collapse previous content (so only one open at any time)? true/false.
animatedefault Should contents that are open by default be animated into view? true/false.
persiststate Persist state of opened contents within a browser session, so returning to the page recalls the saved states? true/false.
toggleclass Specifies two CSS classes to be applied to the header when it's collapsed and expanded, respectively, in the form ["class1", "class2"]. Enter a blank string inside either of the two to denote no CSS class, for example: ["", "class2"].
togglehtml This option  lets you optionally add additional HTML to each header when it's expanded and collapsed, respectively. It accepts 3 parameters:
togglehtml: ["none", "", ""],

For the first parameter, 4 possible values supported: "none", "prefix", "suffix", or "src". The 2nd and 3rd parameters are the HTML to add to each header when it's collapsed and expanded, in that order. Here are a few possible scenarios:

  • togglehtml: ["none", "", ""], //no additional  HTML added to header
  • togglehtml: ["prefix", "[closed] ", "[open] "], //two text added in front of the header
  • togglehtml: ["suffix", " <img src='close.gif' />", " <img src='open.gif' />"], //two images added to the end of the header
  • togglehtml: ["src", "minus.gif", "plus.gif"], //assuming each header is an image itself, toggle between two images depending on state

Set the first parameter to "src" like in the last line above if your headers are images themselves, and you wish to update their "src" property depending on the content state. Here's an example:

JavaScript Reference
Welcome to our JavaScript Reference, a comprehensive listing of JavaScript objects, properties, and methods.
DOM Reference
The DOM (Document Object Model) gives you generic access to most elements, their styles and attributes in a document.
IE Filters reference
Multimedia Filters, supported in IE5.5+, allows you to easily add rich visual effects to your content.

Script setting:

headerclass: "myheader",
contentclass: "mycontent",
,
,
togglehtml: ["src", "minus.gif", "plus.gif"],

  The HTML:

<img src="minus.gif" class="myheader" /><a href="#">JavaScript Reference</a><br />
<div class="mycontent">
1st content here...
</div>

<img src="minus.gif" class="myheader" /><a href="#">DOM Reference</a><br />
<div class="mycontent">
2nd content here...
</div>

<img src="minus.gif" class="myheader" /><a href="#">IE Filters reference</a><br />
<div class="mycontent">
3rd content here...
</div>

In the above example, instead of using regular container headers like a H1 tag, I'm using images instead. In other words, clicking on the images will expand/collapse content. In such a case, I can get the script to dynamically update the image shown by setting "togglehtml": ["src", "minus.gif", "plus.gif"]

animatespeed Speed of sliding animation. Value should be an integer in milliseconds (ie: 200), or one of the keywords "fast", "normal", or "slow".
oninit Event handler that fires when the headers have initailized for the first time on the page. For more info, see: "Taking advantage of the oninit() and onopenclose() event handlers."
onopenclose Event handler that fires whenever a header is expanded or contracted. For more info, see: "Taking advantage of the oninit() and onopenclose() event handlers."

On the supplimentary page, lets see the methods you can call anywhere on your page to simulate a user clicking on a header.

Table Of Contents

This script consists of an index page plus several supplementary pages: