SyntaxStudy
Sign Up
jQuery Intermediate 4 min read

Tab Component

Custom Tabs

Build accessible tabs with jQuery that show/hide content panels and update aria attributes for screen readers.

Example
$(function() {
  $(".tab-btn").on("click", function() {
    const target = $(this).data("tab");
    $(".tab-btn").attr("aria-selected", "false").removeClass("active");
    $(".tab-panel").hide().attr("hidden", "");
    $(this).attr("aria-selected", "true").addClass("active");
    $("#" + target).show().removeAttr("hidden");
  });
  // Activate first tab
  $(".tab-btn:first").trigger("click");
});
/* HTML: <button class="tab-btn" data-tab="panel1" role="tab" aria-selected="false">Tab 1</button>
         <div id="panel1" class="tab-panel" role="tabpanel">Content</div> */
Pro Tip

Use role="tablist", role="tab", and role="tabpanel" plus aria-selected and aria-controls for full ARIA compliance.