How to make tabs on javaScript

This article shows how to create tabs in JavaScript with a simple example.

Creating Tabs with JavaScript

Tabs are a great way to organize content in a small space. They are commonly used to display related pieces of information or to present different views of the same content. By using JavaScript, we can create tabs that can be interacted with, making it easier for the user to navigate between different sections of content.

In this example, we'll create a simple tabbed interface which will allow the user to switch between two different pieces of content. We'll be using HTML, CSS and JavaScript to create the tabs.

Step 1: Setting Up the HTML

The first step is to set up the HTML structure for our tabs. We'll create a <div> element to contain the tabs, and then within that, we'll create two <div> elements for each of the tabs. We'll also use an <input> element and an <label> element to create a toggle switch for the tabs.

<div class="tabs">
  <input type="radio" name="tabs" id="tab-1" checked>
  <label for="tab-1">Tab 1</label>
  <div class="tab-content">
    <p>This is tab 1 content.</p>
  </div>
  <input type="radio" name="tabs" id="tab-2">
  <label for="tab-2">Tab 2</label>
  <div class="tab-content">
    <p>This is tab 2 content.</p>
  </div>
</div>

Step 2: Styling the Tabs

Next, we'll add some CSS to style the tabs. We'll use a combination of positioning, borders and colors to make the tabs look like a toggle switch. We'll also use the :checked selector to style the active tab.

.tabs {
  position: relative;
  margin: 0;
  padding: 0;
  list-style: none;
  font-size: 1.2rem;
  font-weight: bold;
}

.tabs input {
  display: none;
}

.tabs label {
  display: block;
  padding: 10px;
  background: #eee;
  border: 1px solid #ccc;
  margin-left: -1px;
  position: relative;
  left: 1px;
}

.tabs label:hover {
  background: #ddd;
}

.tabs input:checked + label {
  background: #fff;
  border-bottom: 1px solid #fff;
  top: 2px;
}

.tab-content {
  padding: 20px;
  border: 1px solid #ccc;
  background: #fff;
}

Step 3: Adding the JavaScript

Finally, we'll add some JavaScript to make the tabs interactive. We'll use the addEventListener() method to listen for clicks on the labels. When a label is clicked, we'll use the querySelector() method to select the corresponding tab content, and then we'll use the classList.toggle() method to show or hide the content.

const tabs = document.querySelectorAll('.tabs input');

tabs.forEach(tab => {
  tab.addEventListener('click', () => {
    const tabContent = document.querySelector(`#${tab.id}-content`);
    tabContent.classList.toggle('show');
  });
});

And with that, our tabs are now functional! We can now easily switch between different pieces of content with just a few lines of code.

Answers (0)