Skip to content Skip to sidebar Skip to footer

Vanilla Javascript Tabs Won't Close On Click

I've attempted to code vanilla Javascript that opens and closes buttons (tabs) and shows content. They show the content correctly, but don't hide the content once clicked. I've 're

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?

functionopenTab(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";
    }
<divclass="tabs"><buttonclass="link"onclick="openTab(event, 'About')">About</button><buttonclass="link"onclick="openTab(event, 'Hire')">Why You Should Hire Me</button><buttonclass="link"onclick="openTab(event, 'Contact')">Contact</button></div><divid="About"class="content"style="display:none">
ABOUT CONTENT
</div><divid="Hire"class="content"style="display:none">
HIRE CONTENT
</div><divid="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"