DEV Community

Cover image for How to create vertical tabs with Tailwind CSS and JavaScript
Michael Andreuzza
Michael Andreuzza

Posted on

How to create vertical tabs with Tailwind CSS and JavaScript

Let's create a simple vertical tabs component using Tailwind CSS and JavaScript.

See it live and get the code

Why vertical though?

Vertical tabs are a great way to organize content on a webpage. They are easy to navigate and can be used to display different sections of content in a single view. They are also a great way to save space on a page and make it more visually appealing.

More Use Cases:

  • Restaurant menus: A restaurant menu is a list of food and beverage items available for customers to order from.
  • Event schedules: An event schedule is a list of activities, sessions, or presentations happening during an event.
  • Course catalogs: A course catalog is a list of academic courses offered by an educational institution.
  • Recipe collections: A recipe collection is a list of cooking instructions and ingredients for preparing various dishes.
  • Library catalogs: A library catalog is a list of books, periodicals, and other materials available for borrowing from a library.
  • Travel itineraries: A travel itinerary is a list of planned activities and reservations for a trip.
  • Fitness routines: A fitness routine is a list of exercises and workouts designed for achieving specific fitness goals.
  • Project tasks: A project task list is a list of activities or assignments to be completed within a project.
  • Music playlists: A music playlist is a curated list of songs or audio tracks for listening to in a specific order.
  • Movie collections: A movie collection is a curated list of films or videos organized by genre, theme, or other criteria.

The structure

The buttons for the tabs

  • id="tab1": The id of the first tab link, each tab link should have a unique id.
  • href="#tab1": The href of the first tab link, this should be the same as the id of the tab content section.

The tabs content sections

  • id="tab1-content": The id of the first tab content section, each tab content section should have a unique id.
  • class="tab-content ...": The class of the first tab content section, this should be the same as the id of the tab link.
  • class="tab-content hidden ...": The class of the other tab content sections, this shoould have the class hidden so we can hide them and show them on click.

Classes are removed for brevity, but I'll keep those classes relevant to the tutorial

<div>
  <ul>
    <li>
      <a
        id="tab1"
        href="#tab1"
        class="...">
        Tab 1
      </a>
    </li>
    <li">
      <a
        id="tab2"
        href="#tab2"
        class="...">
        Tab 2
      </a>
    </li>
    <li">
      <a
        id="tab3"
        href="#tab3"
        class="...">
        Tab 3
      </a>
    </li>
    <li">
      <a
        id="tab4"
        href="#tab4"
        class="...">
        Tab 4
      </a>
    </li>
  </ul>
  <div class="overflow-hidden h-full">
    <section
      id="tab1-content"
      class="tab-content ...">
      <p>Content for tab 1</p>
    </section>
    <section
      id="tab2-content"
      class="tab-content hidden ...">
      <p>Content for tab 2</p>
    </section>
    <section
      id="tab3-content"
      class="tab-content hidden ...">
      <p >Content for tab 3</p>
    </section>
    <section
      id="tab4-content"
      class="tab-content hidden ...">
      <p >Content for tab 4</p>
    </section>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

The script

The event listener

  • document.addEventListener("DOMContentLoaded", () => {: This is the event listener that will run when the page is fully loaded.
  • const allLinks = document.querySelectorAll("a");: This line selects all the links on the page.
  • const allTabs = document.querySelectorAll(".tab-content");: This line selects all the tab content sections on the page.
  • const switchTab = (linkId) => {: This function will be called when a tab link is clicked.

The switchTab function

  • allTabs.forEach((tab) => {: This line loops through all the tab content sections and hides them.
  • tab.classList.toggle("hidden", tab.id !==${linkId}-content);: This line shows or hides the tab content section based on the link id.

The handleTabClick function

  • event.preventDefault();: This line prevents the default behavior of the link, which is to navigate to the href of the link.
  • const linkId = event.target.id;: This line gets the id of the clicked tab link.
  • allLinks.forEach((link) => {: This line loops through all the tab links and changes their classes based on the link id.
  • const isCurrentLink = link.id === linkId;: This line checks if the clicked tab link is the current link.
  • link.classList.toggle("bg-gray-100", isCurrentLink);: This line changes the background color of the clicked tab link based on if it is the current link.
  • link.classList.toggle("text-blue-600", isCurrentLink);: This line changes the text color of the clicked tab link based on if it is the current link.
  • link.classList.toggle("text-gray-400", !isCurrentLink);: This line changes the text color of the clicked tab link based on if it is not the current link.
  • });: This line closes the for loop.
  • switchTab(linkId);: This line calls the switchTab function with the id of the clicked tab link.

The event listener

  • allLinks.forEach((link) => {: This line loops through all the tab links and adds an event listener to them.
  • link.addEventListener("click", handleTabClick);: This line adds an event listener to the tab links that calls the handleTabClick function when clicked.

The current hash

  • const currentHash = window.location.hash;: This line gets the current hash from the URL.
  • const activeLink = currentHash ? document.querySelector(a[href="${currentHash}"]) : document.querySelector("a");: This line selects the active tab link based on the current hash.
  • handleTabClick({ target: activeLink });: This line calls the handleTabClick function with the active tab link as the argument.
document.addEventListener("DOMContentLoaded", () => {
    const allLinks = document.querySelectorAll("a");
    const allTabs = document.querySelectorAll(".tab-content");

    const switchTab = (linkId) => {
      allTabs.forEach((tab) => {
        tab.classList.toggle("hidden", tab.id !== `${linkId}-content`);
      });
    };

    const handleTabClick = (event) => {
      event.preventDefault();
      const linkId = event.target.id;
      allLinks.forEach((link) => {
        const isCurrentLink = link.id === linkId;
        link.classList.toggle("bg-gray-100", isCurrentLink);
        link.classList.toggle("text-blue-600", isCurrentLink);
        link.classList.toggle("text-gray-400", !isCurrentLink);
      });
      switchTab(linkId);
    };

    allLinks.forEach((link) => {
      link.addEventListener("click", handleTabClick);
    });

    const currentHash = window.location.hash;
    const activeLink = currentHash
      ? document.querySelector(`a[href="${currentHash}"]`)
      : document.querySelector("a");
    handleTabClick({ target: activeLink });
  });
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this tutorial, we learned how to create vertical tabs using Tailwind CSS and JavaScript. We created a simple vertical tabs component that allows users to switch between different sections of content. We also learned how to use event listeners and classes to handle the tab clicks and show or hide the tab content sections. This is a basic example of how to create a vertical tabs component using Tailwind CSS and JavaScript, but you can customize it to fit your specific needs. Remember to make it accessible and responsive for different screen sizes.

Hope you enjoyed this tutorial and have a nice day!

Top comments (0)