Tabs

A few views of the same thing, one at a time, moved through with the arrow keys.

Try it

Click a tab, or tab to the row and use the arrow keys. Home and End jump to the first and last tab. Press Tab again to move into the panel.

A one page site for a neighborhood bakery: menu, hours, and online orders. Launch is planned for spring.

When to use tabs

Code

Plain HTML for any site, or React. Both use the same styles, so the tabs looks the same wherever it lands.

ReadyAny website, Shopify, WordPress, Square, plain hosting

<link rel="stylesheet" href="tokens.css">
<link rel="stylesheet" href="base.css">
<link rel="stylesheet" href="parts.css">

<!-- Tabs: arrow keys move between tabs, Home and End jump to the ends. -->
<div class="prism-tabs">
  <div class="prism-tabs__list" role="tablist" aria-label="Project">
    <button type="button" role="tab" class="prism-tabs__tab" id="tab-1" aria-selected="true" aria-controls="panel-1">Overview</button>
    <button type="button" role="tab" class="prism-tabs__tab" id="tab-2" aria-selected="false" aria-controls="panel-2" tabindex="-1">Files</button>
    <button type="button" role="tab" class="prism-tabs__tab" id="tab-3" aria-selected="false" aria-controls="panel-3" tabindex="-1">Activity</button>
  </div>
  <div class="prism-tabs__panel" role="tabpanel" id="panel-1" aria-labelledby="tab-1" tabindex="0">Overview content.</div>
  <div class="prism-tabs__panel" role="tabpanel" id="panel-2" aria-labelledby="tab-2" tabindex="0" hidden>Files content.</div>
  <div class="prism-tabs__panel" role="tabpanel" id="panel-3" aria-labelledby="tab-3" tabindex="0" hidden>Activity content.</div>
</div>

<script>
  document.querySelectorAll(".prism-tabs").forEach((root) => {
    const tabs = [...root.querySelectorAll('[role="tab"]')];
    const choose = (tab, focus) => {
      tabs.forEach((t) => {
        const on = t === tab;
        t.setAttribute("aria-selected", String(on));
        t.tabIndex = on ? 0 : -1;
        document.getElementById(t.getAttribute("aria-controls")).hidden = !on;
      });
      if (focus) tab.focus();
    };
    tabs.forEach((tab, i) => {
      tab.addEventListener("click", () => choose(tab));
      tab.addEventListener("keydown", (e) => {
        const last = tabs.length - 1;
        const to = { ArrowRight: i === last ? 0 : i + 1, ArrowLeft: i === 0 ? last : i - 1, Home: 0, End: last }[e.key];
        if (to == null) return;
        e.preventDefault();
        choose(tabs[to], true);
      });
    });
  });
</script>

Accessibility