How to make tabs in JavaScript

Learn how to create Tabs using JavaScript and an example of their use.

Creating Tabs with JavaScript

Tabs are a great way to organize content on a page and make it easier to read. By using JavaScript, you can easily create tabs that will allow users to quickly jump between different sections of content.

The first step to creating tabs with JavaScript is to define the HTML structure for the tabs. This consists of a container element, which will contain the tab links, and a content element, which will contain the content for each tab. Here's an example of the HTML structure for a set of tabs:

<div id="tabs">
  <ul>
    <li><a href="#tab1">Tab 1</a></li>
    <li><a href="#tab2">Tab 2</a></li>
    <li><a href="#tab3">Tab 3</a></li>
  </ul>

  <div id="tab1">
    <h2>Tab 1</h2>
    <p>Content for tab 1</p>
  </div>

  <div id="tab2">
    <h2>Tab 2</h2>
    <p>Content for tab 2</p>
  </div>

  <div id="tab3">
    <h2>Tab 3</h2>
    <p>Content for tab 3</p>
  </div>
</div>

Once the HTML structure is in place, we can add the JavaScript to make the tabs functional. We'll need to set up a few global variables to keep track of the current tab and the tab elements:

<script>
  var currentTab = 0; // Current tab is set to be the first tab (0)
  var tabContent = document.getElementsByClassName("tabcontent"); // Get all elements with class="tabcontent" and store in tabContent variable
  var tabLinks = document.getElementsByClassName("tablinks"); // Get all elements with class="tablinks" and store in tabLinks variable
</script>

Next, we'll need to define a function that will be used to open the tabs. This function will take in a tab number as an argument and will set the current tab to that number. It will also loop through all the tab content elements and hide all of them except for the one with the corresponding tab number.

<script>
  function openTab(tabNum) {
    // Hide all tab content
    for (var i = 0; i < tabContent.length; i++) {
      tabContent[i].style.display = "none";
    }

    // Show the specific tab content
    tabContent[tabNum].style.display = "block";

    // Set current tab to tabNum
    currentTab = tabNum;
  }
</script>

Lastly, we'll need to set up an event listener that will be triggered when a tab link is clicked. This will call the openTab() function and pass in the corresponding tab number. Here's an example of how this can be done:

<script>
  // Set up an event listener for each tab link
  for (var i = 0; i < tabLinks.length; i++) {
    tabLinks[i].addEventListener("click", function(e) {
      e.preventDefault();
      openTab(i);
    });
  }
</script>

And that's it! With this code in place, you should now have a working set of tabs. You can customize the look and feel of the tabs by adding some CSS styling to the HTML structure.

Answers (0)