Accessible Tabs In HTML CSS and jQuery

Accessible Tabs In HTML CSS and jQuery
Code Snippet:Accessible Tabs
Author: David yez Setz
Published: January 28, 2024
Last Updated: February 3, 2024
Downloads: 321
License: MIT
Edit Code online: CodeHim
Read More

This code enables accessible tabs in HTML, CSS, and jQuery. It allows users to navigate and toggle between content panels using both mouse clicks and keyboard arrow keys. The tabs visually highlight the active selection and update the corresponding content panel, enhancing user experience. Helpful for creating accessible and interactive tabbed interfaces without relying solely on mouse interactions.

How to Create Accessible Tabs Using HTML CSS and jQuery

1. First of all, load the Normalize CSS by adding the following CDN link into the head tag of your HTML document.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

2. In your HTML file, create a structure for your tabs and content panels. Use the following code as a template, replacing the placeholder text with your content.

Adjust the content inside each tab and panel to suit your needs. Update the id, aria-labelledby, and aria-controls attributes for each button and panel to ensure proper accessibility.

<div class="tab-teaser">
  <nav role="tablist" class="tab-teaser__nav grid">
    <div class="grid__item one-quarter">
      <button class="tab-teaser__tab tab-teaser__tab--active  js_tab-teaser__tab" id="tab1" href="#" role="tab" aria-controls="panel1" aria-selected="true">Lorem Ipsum</button>
    </div>
    <div class="grid__item one-quarter">
      <button class="tab-teaser__tab js_tab-teaser__tab" tabindex="-1" id="tab2" href="#" role="tab" aria-controls="panel2" aria-selected="false">Lorem Ipsum</button>
    </div>
    <div class="grid__item one-quarter">
      <button class="tab-teaser__tab js_tab-teaser__tab" tabindex="-1" id="tab3" href="#" role="tab" aria-controls="panel3" aria-selected="false">Lorem Ipsum</button>
    </div>
    <div class="grid__item one-quarter">
      <button class="tab-teaser__tab js_tab-teaser__tab" tabindex="-1" id="tab4" href="#" role="tab" aria-controls="panel4" aria-selected="false">Lorem Ipsum</button>
    </div>
  </nav>
  <p id="panel1" role="tabpanel" aria-labelledby="tab1" class="tab-teaser__panel js_tab-teaser__panel tab-teaser__panel--active">
    Base attack bonus continuous damage end of round good domain kind light weapon natural reach ranged weapon slime domain square stunned. Blinded cast a spell character incorporeal subtype invisible knowledge domain known spell low-light vision native subtype protection domain renewal domain shield bonus skill points teleportation subschool turning damage unarmed attack. Alignment animal domain attack of opportunity barbarian base save bonus caster level check confused dead direct a spell enchantment environment flank force damage immediate action pattern subschool spell-like ability touch spell turn resistance.
  </p>
  <p id="panel2" role="tabpanel" aria-labelledby="tab2" class="tab-teaser__panel js_tab-teaser__panel">
    attack bonus continuous damage end of round good domain kind light weapon natural reach ranged weapon slime domain square stunned. Blinded cast a spell character incorporeal subtype invisible knowledge domain known spell low-light vision native subtype protection domain renewal domain shield bonus skill points teleportation subschool turning damage unarmed attack. Alignment animal domain attack of opportunity barbarian base save bonus caster level check confused dead direct a spell enchantment environment flank force damage immediate action pattern subschool spell-like ability touch spell turn resistance.
  </p>
  <p id="panel3" role="tabpanel" aria-labelledby="tab3" class="tab-teaser__panel js_tab-teaser__panel">
    bonus continuous damage end of round good domain kind light weapon natural reach ranged weapon slime domain square stunned. Blinded cast a spell character incorporeal subtype invisible knowledge domain known spell low-light vision native subtype protection domain renewal domain shield bonus skill points teleportation subschool turning damage unarmed attack. Alignment animal domain attack of opportunity barbarian base save bonus caster level check confused dead direct a spell enchantment environment flank force damage immediate action pattern subschool spell-like ability touch spell turn resistance.
  </p>
  <p id="panel4" role="tabpanel" aria-labelledby="tab4" class="tab-teaser__panel js_tab-teaser__panel">
    continuous damage end of round good domain kind light weapon natural reach ranged weapon slime domain square stunned. Blinded cast a spell character incorporeal subtype invisible knowledge domain known spell low-light vision native subtype protection domain renewal domain shield bonus skill points teleportation subschool turning damage unarmed attack. Alignment animal domain attack of opportunity barbarian base save bonus caster level check confused dead direct a spell enchantment environment flank force damage immediate action pattern subschool spell-like ability touch spell turn resistance.
  </p>
</div>

3. Style the tabs using the following CSS code. Adjust the CSS styles to match your website’s design. Modify colors, fonts, and sizes to create a visually appealing tabbed interface.

.tab-teaser {
  margin: 20px;
  padding: 20px;
  border-top: 2px solid #2b2;
  border-bottom: 2px solid #2b2;
}
.tab-teaser__nav {
  margin-bottom: 20px;
  clear: both;
  overflow: hidden;
}
.tab-teaser__tab {
  margin-right: 10px;
  padding: 14px 10px 14px;
  float: left;
  width: calc(25% - 10px);
  border: none;
  border-radius: 5px;
  background: #2b2;
  color: #333;
  font-size: 16px;
  line-height: 16px;
  transition: all 0.3s ease-in-out;
}
.tab-teaser__tab--active, .tab-teaser__tab:hover {
  background-color: #333;
  color: #fff;
}
.tab-teaser__panel {
  display: none;
  margin-bottom: 0;
}
.tab-teaser__panel--active {
  display: block;
}

4. Now, load the jQuery by adding the following CDN link just before closing the <body> element:

<script src='//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>

5. Finally, add the following JavaScript function between <script> tag or external JS file. It handles tab switching, keyboard navigation, and other interactive features.

/**
 * Show / hide content based on selected tab
 * Enable arrowkey navgation on focus
 */
(function() {
  'use strict';

  var focused     = 1;
  var keysActive  = false;
  var panel       = 'panel';
  var panelActive = 'tab-teaser__panel--active';
  var panels      = $('.js_tab-teaser__panel');
  var tab         = 'tab';
  var tabActive   = 'tab-teaser__tab--active';
  var tabs        = $('.js_tab-teaser__tab');
  var numTabs     = tabs.length; 
  
  // change active class + set aria-selected to true
  function switchTab(clickedTab) {
    var id = clickedTab.id.substring(tab.length, clickedTab.id.length);

    tabs.removeClass(tabActive);
    tabs.attr('aria-selected', false);
    $(clickedTab).addClass(tabActive);
    $(clickedTab).attr('aria-selected', true);
    panels.removeClass(panelActive);
    $('#' + panel + id).addClass(panelActive);
  }

  // focus tabs with left and right arrows
  function handleKeys(e) {

    keysActive = true;

    switch(e.keyCode) {
      // space
      case 32:
        switchTab($('#' + tab + focused)[0]);
        break;
      // left arrow 
      case 37:
        if (focused === 1) {
          focused = numTabs;
        } else {
          focused --;
        }
        $('#' + tab + focused).focus();
        break;
      // right arrow
      case 39:
        if (focused === numTabs) {
          focused = 1;
        } else {
          focused ++;
        }
        $('#' + tab + focused).focus();
        break;
    }
  }

  function killKeys() {
    // wait to see if focus switches to another tab
    window.setTimeout(function() {
      if (!tabs.is(':focus')) {
        $(window).off('keydown', handleKeys);  
        keysActive = false;
        focused = 1;
      }
    }, 100);
  }
  
  // Add Eventhandler
  tabs.on('click', function() {
    switchTab(this);
  }).on('focus', function() {
    if (!keysActive) {
      $(window).on('keydown', handleKeys);
    }
  }).on('focusout', killKeys);
})();

That’s all! hopefully, you have successfully created accessible tabs using HTML CSS and jQuery. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X