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.
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.
The scripts are then added to the basic HTML code to handle the following points:
display: none
attribute in the CSS.role=“tabpanel”
attribute value is applied to each panel. role=“tablist”
attribute value is applied to the tab container.role=“tab”
attribute value is applied to each of the tabs.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. 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. <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. 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>