The Accordion widget is used to collapse data, so that the end user only sees some of the data on the page. This makes it easier to process the information for the end user.This is because instead of having a large page which scrolls for a long time, it will show only some of the page. It will hide most of the elements, only showing one at a time.
A good example of using the accordion is for a FAQ (Frequently Asked Question) page. This way, the questions are the header, the answers are the following div. This way only a single question is answered at a time.
Your users will click on a header. That will hide the other content, and display the selected content.
It also makes your pages more SEO friendly as the information is easily seen by the search spiders who read and index the pages. Nothing is “hidden” from a search engine perspective because it can all be easily made visible by the user, so there is no reason for the penalty.
Similar to the tabs widget, accordion relies upon proper layout of the HTML structure to ensure it works properly.
HTML Structure
The HTML structure requires a containing div. This div will enclose all of the elements within the accordion.
Within the div you will find another set of structures. This is will be a header tag (h2) immediately followed by a div. The div will contain what will be shown when the header is clicked on.
The containing div can contain any legal and valid HTML element. This includes of course paragraphs, lists, images, and other divs. The content of course can be styled.
JavaScript
The initial JavaScript is fairly simple. Assuming the containing div has an id of “accordion”.
$( "#accordion" ).accordion();
This simple script will hide all of the unselected sections, however, by default, it will show the first section.
If you want to be able to hide a section you need to pass in a parameter to the widget’s method. The collapsible section will allow you click on an open section’s header, and close that whole header.
$( "#accordion" ).accordion({ collapsible: true });
You can apply icons to the headers. The icons come from the name of the icons that are available in the theme. To do so, you can choose to either pass in a variable of icons to choose, or use another JavaScript object. There are two required states that you need to set.
- header
- activeHeader
If you want to set a variable to simplify the writing of your code you would do something like.
// definition of variable var iconSet = { header: 'ui-icon-circle-arrow-e', activeHeader: 'ui-icon-circle-arrow-s' };
$( "#accordion" ).accordion({ icons: iconSet });
If you want to define the icons directly you would do something like:
$( "#accordion" ).accordion({ icons: { header: 'ui-icon-circle-arrow-e', activeHeader: 'ui-icon-circle-arrow-s' } });
Note that these to examples perform the same result.
jQuery UI – Using Accordion to Focus on Content was originally found on Access 2 Learn