Table of Contents

2.1.2. Accordions

Purpose

Accordions are dynamic modules used to display multiple blocks of content on a single page without scrolling. Each block can be opened or closed (fold/unfold) through the heading or title above.

Basic HTML code

An example of the basic HTML code for an accordion with panels concealed by default is shown below. This code may be modified according to the context, notably with respect to the different heading levels.

<h1>Heading of the first panel</h1>
<div id="panel-1">
    <p>Content of the first panel</p>
</div>
 
<h1>Heading of the second panel</h1>
<div id="panel-2">
    <p>Content of the second panel</p>
</div>
 
<h1>Heading of the third panel</h1>
<div id="panel-3">
    <p>Content of the third panel</p>
</div>

Without JavaScript, all panels are displayed.

Note

Even though it is not so recommended, it is possible, without JavaScript, to keep the links inside the headings. In this case, they are links that point to the corresponding anchors:

<h1><a href="#panel-1">Heading of the first panel</a></h1>
<div id="panel-1">
    <p>Content of the first panel </p>
</div>

Behaviour with JavaScript

The scripts are then added to the basic HTML code to handle the following points:

  1. The panel headings include links that make it possible to fold or unfold the panels.
  2. The panels are hidden by default using the property display: none in the CSS.
  3. By using the mouse or the keyboard to execute a link-heading, you can display or hide the corresponding panel (display: none to hide it and display: block to display it).
  4. The aria-expanded=“false” attribute is applied by default on the link-heading. The value of this attribute then changes dynamically to true when the corresponding content is displayed and false otherwise.
  5. The aria-controls attribute is applied to the link-heading. The value of this attribute is retrieved from the ID attribute of the corresponding panel.

The resulting code with JavaScript is as follows:

<h1><a href="#panel-1" aria-expanded="false" aria-controls="panel-1">First panel heading</a></h1>
<div id="panel-1">
    <p>First panel content (hidden)</p>
</div>
 
<h1><a href="#panel-2" aria-expanded="true" aria-controls="panel-2">Second panel heading</a></h1>
<div id="panel-2">
    <p>Second panel content (displayed)</p>
</div>
 
<h1><a href="#panel-3" aria-expanded="false" aria-controls="panneau-3">Third panel heading</a></h1>
<div id="panel-3">
    <p>Third panel content (hidden)</p>
</div>

Demonstration