I’m trying to create a dynamic tabbed interface for my website where users can click on different tabs to display different content sections. I’ve been able to create static tabs using HTML and CSS, but I’m not sure how to make them dynamic using JavaScript.
Here’s what I have so far:
function openTab(evt, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tab-content");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tab-link");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
}
body {
font-family: Arial, sans-serif;
}
.tabs {
overflow: hidden;
background-color: #f1f1f1;
border-bottom: 1px solid #ccc;
}
.tab-link {
background-color: inherit;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
transition: background-color 0.3s;
}
.tab-link:hover {
background-color: #ddd;
}
.tab-link.active {
background-color: #ccc;
}
.tab-content {
display: none;
padding: 6px 12px;
border: 1px solid #ccc;
border-top: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tabbed Interface</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="tabs">
<button class="tab-link active" onclick="openTab(event, 'Tab1')">Tab 1</button>
<button class="tab-link" onclick="openTab(event, 'Tab2')">Tab 2</button>
<button class="tab-link" onclick="openTab(event, 'Tab3')">Tab 3</button>
</div>
<div id="Tab1" class="tab-content">
<h3>Tab 1</h3>
<p>Content for Tab 1.</p>
</div>
<div id="Tab2" class="tab-content" style="display:none;">
<h3>Tab 2</h3>
<p>Content for Tab 2.</p>
</div>
<div id="Tab3" class="tab-content" style="display:none;">
<h3>Tab 3</h3>
<p>Content for Tab 3.</p>
</div>
<script src="script.js"></script>
</body>
</html>
This code mostly works, but I’m running into a few issues:
- The default active tab doesn’t display its content until I click on another tab and then back.
- The CSS styles don’t seem to transition smoothly when switching tabs.
Can someone help me understand how to fix these issues or suggest a better approach to create a dynamic tabbed interface?
Thanks in advance!
2
Answers
I suggest using the "active" class consistently, rather than directly changing display styles. Then you can specify the initially selected button/content using "active" classes in the HTML. Similarly, I suggest adding event listeners in JavaScript rather than inline "onclick" events.
I don’t notice any obvious problem with the smoothness of the CSS transitions.
For alternative concepts, see: HTML tab interface using only CSS
Try this one hopefully this should be helpful for you. These tab are dynamically created using javasrcipt
HTML:
CSS:
JavaScript: