Easy Toggle Tab In Vanilla JavaScript

Category: Javascript | August 18, 2020
Author:Fikri Al-baihaqi
Views Total:2,971 views
Official Page:Go to website
Last Update:August 18, 2020


Easy Toggle Tab In Vanilla JavaScript


An easy-to-use toggle tab (tabs) UI component implemented in pure JavaScript and CSS.

How to use it:

1. Code the HTML for the toggle tab interface.

<div class="wrapper">
  <div class="buttonWrapper">
    <button class="tab-button active" style="border-top-left-radius: 10px;" data-id="home">Home</button>
    <button class="tab-button" data-id="css">CSS</button>
    <button class="tab-button" style="border-top-right-radius: 10px;" data-id="script">Script</button>
  <div class="contentWrapper">
    <p class="content active" id="home">
      Tab 1
    <p class="content" id="css">
      Tab 2
    <p class="content" id="script">
      Tab 3

2. The necessary CSS styles.

.wrapper {
  width: 590px;
  margin: auto;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0px 5px 15px rgba(0, 0, 0, .1);
.buttonWrapper {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
button {
  letter-spacing: 3px;
  border: none;
  padding: 10px;
  background-color: #bccbe9;
  color: #232c3d;
  font-size: 18px;
  cursor: pointer;
  transition: 0.5s;
button:hover {
  background-color: #d5e3ff;
button.active {
  background-color: white;
.active {
  background-color: white;
p {
  text-align: left;
  padding: 10px;
.content {
  display: none;
  padding: 10px 20px;
.content.active {
  display: block;

3. The JavaScript to enable the toggle tab.

const tabs = document.querySelector(".wrapper");
const tabButton = document.querySelectorAll(".tab-button");
const contents = document.querySelectorAll(".content");
tabs.onclick = e => {
  const id = e.target.dataset.id;
  if (id) {
    tabButton.forEach(btn => {
    contents.forEach(content => {
    const element = document.getElementById(id);

You Might Be Interested In:

Leave a Reply