A Tabbed component lets you show and hide contents. They are similar to tabs in your browser, but you use them inside the page.
I call the tabbed component “Tabby” because the word “Tab” can be used to mean too many things. (Like the Tab key, browser Tabs, etc). Plus, “Tabby” sounds more friendly and fun compared to a “Tabbed component”.
Here’s what Tabby looks like:
Tabby’s HTML
Tabby contains two parts:
The tabs.
The contents of each tab (we’ll call this tab-content).
If a tab is selected, it should be emphasized. There are many ways to do this. For Tabby, I used filter to de-emphasized tabs that are not selected.
/* De-emphasize tabs that are not selected */
.tab {
filter: grayscale(75%) brightness(0.9);
}
/* Emphasize the selected tab */
.tab.is-selected {
filter: none;
background-color: white;
}
When a tab is selected, its corresponding tab-content should be displayed. Other tabs are hidden. We can do this with display: none.
/* Hides tab-content when it is not selected */
.tab-content {
display: none;
}
/* Show the selected tab-content */
.tab-content.is-selected {
display: block;
}
Switching tabs
If you want to switch to the second tab, you need to:
When a user clicks on a Tab, you want to switch to the tab they clicked. Here, you need to:
Add event listeners to each tab
Find the tab they clicked
Find the corresponding tab content
Remove is-selected from other tabs to de-emphasize them
Remove is-selected from other tab content to hide them
Add is-selected to the tab they clicked to emphasize it
Add is-selected to the tab content to show it
Adding event listeners
Here, you can use querySelectorAll to select the tabs. Then, you loop through each tab with forEach, and use addEventListener to add an event listener to each tab.
const tabs = Array.from(document.querySelectorAll('.tab'))
tabs.forEach(tab => {
tab.addEventListener('click', event => {
// Do something here
})
})
Finding the clicked tab
If an event fires, it will fire on the tab that was clicked.
There are two ways to find the correct tab content:
Counting elements.
Designating a target element.
For Tabby, it makes more sense to designate target elements since each tab has their corresponding tab contents. (You’ll learn how to count elements in Carousel).
When we designate a target element, we set an attribute (like data-target) of the tab to the same value as the id of the tab-content. This works because id is unique. There should not be two elements with the same id.
(For Tabby, we use digimon, pokemon, and tamagotchi instead of content-1, content-2, content-3).
Notice we used t as an abbreviation for tab in the forEach loop. We used t because we don’t want to overwrite the tab variable. tab is already used for something else; it means the “clicked tab”. If we used tab, we’ll get the two tab variables mixed up.
Selecting a tab-content
We also need to do two things to select a tab-content:
Remove is-selected from other tab content to hide them.