2.1.3. Tabs

Purpose

Tabs are dynamic modules that enable you to optimize the display of page content in a small space. They are usually shown in the form of a list of side-by-side links that display the corresponding content of the selected tab. You can only activate one tab at a time.

Basic HTML code

The HTML code includes internal links that point to the corresponding panels.

<ul>
    <li><a href="#panel-01">First tab</a></li>
    <li><a href="#panel-02">Second tab</a></li>
    <li><a href="#panel-03">Third tab</a></li>
</ul>
 
<div id="panel-01">
    Content of the first panel.
</div>
 
<div id="panel-02">
    Content of the second panel.
</div>
 
<div id="panel-03">
    Content of the third panel.
</div>

Without JavaScript, all the panels are displayed, and the tabs are used as links to directly access the content of the corresponding panel.

Behaviour with JavaScript

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

  • With the exception of the active panel, the panels are hidden by default using the display: none attribute in the CSS.
  • The role=“tabpanel” attribute value is applied to each panel.
  • The role=“tablist” attribute value is applied to the tab container.
  • The role=“tab” attribute value is applied to each of the tabs.
  • The aria-controls attribute is applied to each of the tabs. The value of this attribute is retrieved from the id attribute of the corresponding panel.
  • The aria-selected=“false” attribute value is applied to each tab, except for the active tab that has the attribute value aria-selected=“true”. The value of this attribute then changes dynamically to true when the corresponding content is displayed and false otherwise.
  • The <strong> tag is added systematically around the content of the active tab. This tag is deleted as soon as the tab is no longer active.
  • The tabindex=“0” attribute is applied to each of the panels so that they can receive the focus. As soon as a tab is selected, the focus must be positioned dynamically on the corresponding panel.

The resulting code with JavaScript is as follows:

<ul role="tablist">
    <li role="tab" aria-selected="true" aria-controls="panel-01"><a href="#panel-01"><strong>First tab</strong></a></li>
    <li role="tab" aria-selected="false" aria-controls="panel-02"><a href="#panel-02">Second tab</a></li>
    <li role="tab" aria-selected="false" aria-controls="panel-03"><a href="#panel-03">Third tab</a></li>
</ul>
 
<div id="panel-01" role="tabpanel" tabindex="0">
    Content of the first panel.
</div>
 
<div id="panel-02" role="tabpanel" tabindex="0">
    Content of the second panel.
</div>
 
<div id="panel-03" role="tabpanel" tabindex="0">
    Content of the third panel.
</div>

Démonstration

notices/interfaces-riches-javascript/onglets.txt · Last modified: 06 January 2014 at 11:08 by rlapeze
 

Project coordinated by Atalan.

In partnership with:

Observers: