When I click on a particular tab the other tabs's content should be hidden but it is not hiding. This is all the code I have.
function showStuff(id) {
if (document.getElementById(id).style.display === "block") {
document.getElementById(id).style.display = "none";
} else {
document.getElementById(id).style.display = "block";
}
}
<ul class="side bar tabs">
<li id="tabs1" onclick="showStuff('tabs-1')">City</li>
<li id="tabs2" onclick="showStuff('tabs-2')">Country</li>
<li id="tabs3" onclick="showStuff('tabs-3')">Humanity</li>
</ul>
<div id="tabs-1" style="display : none">
<p>Proin elit m</p>
</div>
<div id="tabs-2" style="display : none">
<p>M massa ut d</p>
</div>
<div id="tabs-3" style="display : none">
<p> sodales.</p>
</div>
hide() Hides one or more tabs.
Giving all the tab content elements a common CSS class makes selecting and styling them much easier, for example in this demo and code below.
CSS
.tabContent {
display:none;
}
JavaScript
function showStuff(element) {
var tabContents = document.getElementsByClassName('tabContent');
for (var i = 0; i < tabContents.length; i++) {
tabContents[i].style.display = 'none';
}
// change tabsX into tabs-X in order to find the correct tab content
var tabContentIdToShow = element.id.replace(/(\d)/g, '-$1');
document.getElementById(tabContentIdToShow).style.display = 'block';
}
HTML
<ul class="side bar tabs">
<li id="tabs1" onclick="showStuff(this)">City</li>
<li id="tabs2" onclick="showStuff(this)">Country</li>
<li id="tabs3" onclick="showStuff(this)">Humanity</li>
</ul>
<div id="tabs-1" class="tabContent">
<p>Proin elit m</p>
</div>
<div id="tabs-2" class="tabContent">
<p>M massa ut d</p>
</div>
<div id="tabs-3" class="tabContent">
<p> sodales.</p>
</div>
I have also updated the showElement
function to be more generic so that there is less code duplication when hiding and showing the correct tab content.
The only caveat is that getElementsByClassName()
is not available in IE8 or below. Other (modern) browsers have this function but there are alternatives - see getElementsByClassName & IE8: Object doesn't support this property or method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With