Submit your widget

jQuery Collapse - A lightweight jQuery plugin that enables expanding and collapsing content

Created 11 years ago   Views 24499   downloads 7907    Author Author
jQuery Collapse - A lightweight jQuery plugin that enables expanding and collapsing content
View DemoDownload
95
Share |

 

jQuery Collapse

A lightweight and flexible jQuery plugin that allows you to collapse content. A feature also known as 'progressive disclosure'.

NOTICE: As of August 2012 this plugin has been rewritten from scratch. The old version is no longer maintained or supported.

jQuery Collapse requires jQuery 1.7 or newer.

Enjoy!

 

Features

  • WAI ARIA compliant
  • Lightweight (~1.2kb minified and gzipped)
  • Cross Browser compliant (Tested in >= IE6, Firefox, Safari, Chrome, Opera)
  • Accordion behaviour can be enabled.
  • Persistence to remember open sections on page reload!

 

 

Usage

Load jQuery and the jQuery Collapse plugin into your document:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="jquery.collapse.js"></script>

Here's some sample HTML markup:

<div id="demo" data-collapse>
  <h2>Fruits</h2>
  <ul>
    <li>Apple</li>
    <li>Pear</li>
    <li>Orange</li>
  </ul>
  <h2>Info</h2>
  <div>
    <p>You can use any container you like (in this case a div element)</p>
  </div>
</div>

That's it! The data-collapse attribute will automatically trigger the script.

 

Open/Collapse section by default

The standard behaviour is to collapse all the sections on page load. If you want to show a section to the user on page load you can achieve this by adding an 'open' class to the section heading

<div id="demo" data-collapse>
  <h2 class="open">I'm open by default</h2>
  <p>Yay</p>
</div>

 

JavaScript usage

If you'd rather omit the 'data-collapse' attribute in the HTML and load the plugin via jQuery, you can:

$("#demo").collapse({
  // options...
});

If you don't want to use the jQuery ($) wrapper, you can also access the plugin with vanilla JavaScript:

new jQueryCollapse($("#demo"), {
  // options...
});

 

Using custom markup

By default the plugin will look for groups of two elements. In real life™ your markup may vary and you'll need to customize how the plugin interprets it. For example

<div id="demo">
  <div>
    <h2>Summary</h2>
    <div>details...</div>
  </div>
  <div>
    <h2>Summary</h2>
    <div>details...</div>
  </div>
</div>

In order for the plugin to understand the above markup, we can pass a 'query' option specifying where to find the header/summary element of a section:

new jQueryCollapse($("#demo"), {
  query: 'div h2'
});

Read the full documentation for more info.