UNIT 24 • STAGE 3 OF 7

Tab Switcher

JavaScript that shows and hides menu cards when a tab is clicked

UNIT 3 / 7
STEP 1

How the Tab Switcher Pattern Works

The tab pattern is one of the most common UI patterns on the web. It follows a simple logic:

  • When a tab button is clicked, read its data-tab value
  • Remove the active class from all buttons, add it to the clicked one
  • Loop through all cards: if the card's data-category matches the tab, show it; otherwise, hide it

The key tool is btn.dataset.tab, JavaScript's way of reading data-tab="starters" from an element. The dataset property gives you access to all data attributes as a simple object.

STEP 2

Select the Buttons and Cards

Add a <script> block at the bottom of <body>. First, select all the elements you need:

👉 Add just before </body>: <script>
  var tabBtns = document.querySelectorAll('.tab-btn');
  var cards = document.querySelectorAll('.menu-card');
</script>
  • querySelectorAll returns a NodeList of all matching elements. It works exactly like a CSS selector.
  • Using variable names tabBtns and cards makes the code readable at a glance.
STEP 3

Add the Click Handler

Loop through every button and attach a click listener. Inside the handler, clear all active states, then set the new one:

👉 Add inside <script>: tabBtns.forEach(function(btn) {
  btn.addEventListener('click', function() {
    var filter = btn.dataset.tab;
    tabBtns.forEach(function(b) { b.classList.remove('active'); });
    btn.classList.add('active');
    cards.forEach(function(card) {
      if (card.dataset.category === filter) {
        card.style.display = '';
      } else {
        card.style.display = 'none';
      }
    });
  });
});
  • btn.dataset.tab reads the data-tab attribute. JavaScript strips the data- prefix automatically, so data-tab="starters" becomes dataset.tab.
  • classList.remove('active') on every button first: this clears the previous selection before adding the new one.
  • card.style.display = '' (empty string) removes any inline style, letting the card fall back to its CSS default (which is visible). Using 'none' hides it.
  • card.dataset.category reads the card's data-category attribute, the same pattern as btn.dataset.tab.

Test it: click each tab

Click Starters, then Mains, then Sides, then Desserts. Each click should show only the matching 3 cards. If cards are not hiding, check that the data-tab values on your buttons exactly match the data-category values on your cards.

Stage 3 Complete

You now have a fully working tab switcher. Clicking any tab shows only that category's cards.

Next: Stage 4 adds the restaurant's About section with a two-column grid layout and a pull quote.

Code Editor
Live Preview