Vanilla Javascript Tabs Won't Close On Click
Solution 1:
The code you posted had some confusing behaviour (such as the buttons disappearing completely). I removed the line that made buttons disappear, as well two different loops that seemed to conflict with each other regarding the class name of the links.
I edited the code down to something simple that displays the content according to the button clicked, but I suspect I've misunderstood something and you're after something else. Maybe you can clarify what's missing?
function openTab(click, openTab) {
var i;
var content;
var wasOpen = document.getElementById(openTab).style.display === "block";
content = document.getElementsByClassName("content");
for (i = 0; i < content.length; i++) {
content[i].style.display = "none";
}
if (wasOpen) return;
document.getElementById(openTab).style.display = "block";
}
<div class="tabs">
<button class="link" onclick="openTab(event, 'About')">About</button>
<button class="link" onclick="openTab(event, 'Hire')">Why You Should Hire Me</button>
<button class="link" onclick="openTab(event, 'Contact')">Contact</button>
</div>
<div id="About" class="content" style="display:none">
ABOUT CONTENT
</div>
<div id="Hire" class="content" style="display:none">
HIRE CONTENT
</div>
<div id="Contact" class="content" style="display:none">
CONTACT CONTENT
</div>
Explainer:
The changes I made to the html was 1- to add some text in each tab and 2- set all tabs to display:none
Within the javascript:
On click, we have a value for "openTab", representing one of the tabs. The line:
var wasOpen = document.getElementById(openTab).style.display === "block";
Sets a Boolean variable which is true if "openTab"'s display property is set to block.
Then we set all tabs to display:none with the following:
content = document.getElementsByClassName("content");
for (i = 0; i < content.length; i++) {
content[i].style.display = "none";
}
And now, depending on whether or not the tab was already open, we either leave the function already, or set the tab to "block"
if (wasOpen) return;
document.getElementById(openTab).style.display = "block";
Tadaaaa!
Post a Comment for "Vanilla Javascript Tabs Won't Close On Click"