Let’s Build: With JavaScript – How to Create Tabs with Vanilla JavaScript

Welcome to the next installment of my Let’s Build: With JavaScript series. In this video, learn how to create tabs with vanilla JavaScript.

View Source Code

The focus of these series of videos will be on using vanilla JavaScript to start. I’ll strive to not reach for frameworks until absolutely necessary.

Tabs are a useful feature for displaying more content on a page that you would rather not display in block or inline fashion using traditional CSS. Making the tab component as dynamic as possible in this video was a focus for the sake of adding new tabs and tab content further down the line.

The main function will be checking what tabs are active and not active. If they are active we will use an event listener when the user clicks to determine which tab and it’s respective content to display.

In the end the code looks like the following:

The HTML Markup

<div class="container">
<!-- Tabs -->
<ul id="nav-tab" class="nav">
  <li class="active"><a href="#home">Home</a></li>
  <li><a href="#profile">Profile</a></li>
  <li><a href="#messages">Messages</a></li>
  <li><a href="#settings">Settings</a></li>
</ul>

<!-- Tab panes -->
<div class="tab-content">
  <div class="tab-pane active" id="home">
    <h4>Home Panel Content</h4> 
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quidem iure quos cum, saepe reprehenderit minima quasi architecto numquam nesciunt dicta. Qui excepturi recusandae vitae maiores, inventore sequi? Rerum, odio omnis.</p> </div>
  <div class="tab-pane" id="profile">
    <h4>Profile Panel</h4>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quidem iure quos cum, saepe reprehenderit minima quasi architecto numquam nesciunt dicta. Qui excepturi recusandae vitae maiores, inventore sequi? Rerum, odio omnis. Lorem ipsum dolor sit amet consectetur adipisicing elit. Alias distinctio, tempora incidunt aliquid adipisci, minus rerum optio libero quae provident sed at dignissimos, quia nostrum! Fuga dolorum quia hic magni.</p></div>
  <div class="tab-pane" id="messages">
    <h4>Messages Panel</h4>
    <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Fugiat quos, at qui aspernatur minus animi hic sunt necessitatibus incidunt molestiae reprehenderit ratione neque odit ipsa. Nemo laborum consequatur adipisci beatae!</p>
  </div>
  <div class="tab-pane" id="settings">
    <h4>Settings Panel</h4>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Minima possimus sed odit iste vitae, magnam amet illum laudantium ea! Fugiat consectetur consequuntur qui eos obcaecati sequi ipsam repellat vero voluptate.</p>
  </div>
</div>
</div>

The CSS/SCSS Styles

Here we define some general layout and active states to better denote what is indeed active or not.

body {
 font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  color: #444;
}

.container {
  max-width: 800px;
  margin: 0 auto;
}

ul {
  list-style: none;
  padding: 0;

  li {
    display: inline-flex;

    a {
      text-decoration: none;
      color: darkgray;
      padding: 10px;
      transition: all .3s ease-in-out;
      border-bottom: 1px solid transparent;
      &:hover {
        color: gray;
      }
    }
  }
}

.nav .active a { 
  color: slateblue; 
  border-bottom: 1px solid slateblue;
  &:hover {
    border-color: transparent;
    background: slateblue;
    color: white;
  }
}

.tab-pane { 
  display: none;
}

.tab-pane.active { 
  display: block; 
}

The JavaScript

Finally, our JavaScript is a basic function which fires when a given user clicks on a tab.

function onTabClick(event) {
  let activeTabs = document.querySelectorAll('.active');

  // deactivate existing active tab and panel 
  activeTabs.forEach(function(tab) {
    tab.className = tab.className.replace('active', '');
  });

  // activate new tab and panel
  event.target.parentElement.className += ' active';
  document.getElementById(event.target.href.split('#')[1]).className += ' active';
}

const element = document.getElementById('nav-tab');

element.addEventListener('click', onTabClick, false);

Check out my process and more in this video. If you have suggestions for future videos or ideas for components to build please let me know in the comments. Thanks for watching!

The Let’s Build: With JavaScript series so far