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:
- We use the display property (
none/block) to hide and show elements. - When the user clicks a tab, we call the function and pass the tab’s ID.
- Inside the function, we use
<strong>querySelectorAll</strong>+<strong>forEach</strong>to hide all tab contents. - 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
EasyWe’ve already written the JavaScript function that makes the tabs work. Your task:
- Add the
onclickattribute to each tab button so that clicking a tab shows the correct content - Call the function
openTab(). - Pass the id of the tab content (
home,about, orcontact).
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>This lesson includes a short quiz. Start the lesson to answer it and track your progress.