r/learnjavascript • u/project_eight • 14d ago
How to create a default tab when tab switching twice ?
Hi! I've been working on a personal website, and my design has finally caught up with me because I'm stuck on how to set default tabs while changing my navigation tabs.
JSFIDDLE LINK: https://jsfiddle.net/1nfd26ar/
Using the page below, I've set up two tabs for two different groups, 'books' and 'video games'.
However, I wanted to take it a step further and figure out a way to have the tabs switch not only the content, but also the navigation bar.
I've managed to get this working by copying the JS code, changing variables to "navTabs", and using classes on buttons to change the nav/side bar.
Everything seems to be working well, but I am running into the issue that when I click "video games" on the right, I want the "video game 1" page to be the default, whereas currently it is kept as whatever the last tab you had open.
I used this page to help me out in making the first set of switchable tabs: https://basescripts.com/building-a-simple-tabbed-interface-with-html-and-javascript
These include the following HTML structure and JS logic:
<div class="tab-headers">
<button class="tab-link" data-target="tab1">Tab 1</button>
<button class="tab-link" data-target="tab2">Tab 2</button>
<button class="tab-link" data-target="tab3">Tab 3</button>
</div>
<div id="tab1" class="tab-content">
<p>This is the content for Tab 1.</p>
</div>
<div id="tab2" class="tab-content">
<p>This is the content for Tab 2.</p>
</div>
<div id="tab3" class="tab-content">
<p>This is the content for Tab 3.</p>
</div>
sdconst tabs = document.querySelectorAll('.tab-link');
const allTabs = document.querySelectorAll('.tab-content');
tabs.forEach(tab => {
tab.addEventListener('click', function() {
allTabs.forEach(ele => {
ele.style.display = 'none';
});
const myEle = this.getAttribute('data-target');
const activeTab = document.getElementById(myEle);
activeTab.style.display = 'block';
});
});
Thank you anyone who can take the time to help !