UNIT 24 • STAGE 3 OF 7
JavaScript that shows and hides menu cards when a tab is clicked
The tab pattern is one of the most common UI patterns on the web. It follows a simple logic:
data-tab valueactive class from all buttons, add it to the clicked onedata-category matches the tab, show it; otherwise, hide itThe 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.
Add a <script> block at the bottom of <body>. First, select all the elements you need:
querySelectorAll returns a NodeList of all matching elements. It works exactly like a CSS selector.tabBtns and cards makes the code readable at a glance.Loop through every button and attach a click listener. Inside the handler, clear all active states, then set the new one:
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.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.
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.