Menu
Coddy logo textTech

Tabs

Part of the JavaScript in Action section of Coddy's HTML journey — lesson 1 of 27.

Tabs let users switch between different pieces of content without leaving the page. In Section 4, we built them with HTML and CSS. Now we’ll use JavaScript. 

Key points:

  1. We use the display property (none / block) to hide and show elements.
  2. When the user clicks a tab, we call the function and pass the tab’s ID.
  1. Inside the function, we use <strong>querySelectorAll</strong> + <strong>forEach</strong> to hide all tab contents.
  2. Finally, we show the one that matches the ID.
<div class="tabs">
  <button class="tab" onclick="openTab('services')">Services</button>
  <button class="tab" onclick="openTab('contact')">Contact</button>
</div>

<div id="services" class="tab-content">Our services are listed here.</div>
<div id="contact" class="tab-content" style="display:none;">Contact us at contact@example.com.</div>

<script>
  function openTab(tabId) {
    // Hide all tab contents
    document.querySelectorAll('.tab-content').forEach(el => el.style.display = 'none');
    // Show the selected tab
    document.getElementById(tabId).style.display = 'block';
  }
</script>
challenge icon

Challenge

Easy

We’ve already written the JavaScript function that makes the tabs work. Your task: 

  1. Add the onclick attribute to each tab button so that clicking a tab shows the correct content
  2. Call the function openTab().
  3. Pass the id of the tab content (home, about, or contact).

Try it yourself

<!DOCTYPE html>
<html>
<head>
  <title>Simple Tabs Example</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="tabs">
    <!-- Each button calls the function and passes the tab's ID -->
    <button class="tab" >Home</button>
    <button class="tab" >About</button>
    <button class="tab" >Contact</button>
  </div>

  <!-- By default, only "Home" is visible -->
  <div id="home" class="tab-content">Welcome to the homepage!</div>
  <div id="about" class="tab-content" style="display:none;">Learn more about us here.</div>
  <div id="contact" class="tab-content" style="display:none;">Get in touch with us.</div>

  <script src="script.js"></script>
</body>
</html>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in JavaScript in Action