[JavaScript] Controlling tab visibility with classList.toggle()
Controlling tab visibility with classList.toggle()
When building tabbed UIs, a common task is showing one section while hiding the others. In JavaScript, this can be done efficiently using the classList.toggle() method — especially when used with a condition.
Hiding Tabs Using Bootstrap's `d-none`
In the GTPS blog, two tabs exist: a search tab and a tracker tab. Each time one of them is clicked, a function switches visibility like this:
function changeTab(name) {
document.getElementById('tab-search').classList.toggle('d-none', name !== 'search');
document.getElementById('tab-tracker').classList.toggle('d-none', name !== 'tracker');
}
Each toggle() call controls the visibility of a tab by conditionally applying or removing the d-none class, which is a Bootstrap utility that sets display: none.
Understanding `classList.toggle(className, condition)`
This method has two forms:
- element.classList.toggle('className') — toggles the class on/off
- element.classList.toggle('className', condition) — forces the class on/off based on the boolean condition
In this case:
classList.toggle('d-none', name !== 'search');
means:
* If name is not search, add d-none → hide the tab
* If name is search, remove d-none → show the tab
So the element is shown or hidden based on whether it matches the active tab name.
Why This is Better Than Manual If-Statements
This logic replaces:
if (name === 'search') {
element.classList.remove('d-none');
} else {
element.classList.add('d-none');
}
With one clean line using toggle().
Comments
Post a Comment