skip to Main Content

I’m trying to create a dynamic tabbed interface for my website where users can click on different tabs to display different content sections. I’ve been able to create static tabs using HTML and CSS, but I’m not sure how to make them dynamic using JavaScript.

Here’s what I have so far:

function openTab(evt, tabName) {
    var i, tabcontent, tablinks;

    tabcontent = document.getElementsByClassName("tab-content");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }

    tablinks = document.getElementsByClassName("tab-link");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }

    document.getElementById(tabName).style.display = "block";
    evt.currentTarget.className += " active";
}
body {
    font-family: Arial, sans-serif;
}

.tabs {
    overflow: hidden;
    background-color: #f1f1f1;
    border-bottom: 1px solid #ccc;
}

.tab-link {
    background-color: inherit;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 14px 16px;
    transition: background-color 0.3s;
}

.tab-link:hover {
    background-color: #ddd;
}

.tab-link.active {
    background-color: #ccc;
}

.tab-content {
    display: none;
    padding: 6px 12px;
    border: 1px solid #ccc;
    border-top: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tabbed Interface</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="tabs">
        <button class="tab-link active" onclick="openTab(event, 'Tab1')">Tab 1</button>
        <button class="tab-link" onclick="openTab(event, 'Tab2')">Tab 2</button>
        <button class="tab-link" onclick="openTab(event, 'Tab3')">Tab 3</button>
    </div>
    <div id="Tab1" class="tab-content">
        <h3>Tab 1</h3>
        <p>Content for Tab 1.</p>
    </div>
    <div id="Tab2" class="tab-content" style="display:none;">
        <h3>Tab 2</h3>
        <p>Content for Tab 2.</p>
    </div>
    <div id="Tab3" class="tab-content" style="display:none;">
        <h3>Tab 3</h3>
        <p>Content for Tab 3.</p>
    </div>
    <script src="script.js"></script>
</body>
</html>

This code mostly works, but I’m running into a few issues:

  1. The default active tab doesn’t display its content until I click on another tab and then back.
  2. The CSS styles don’t seem to transition smoothly when switching tabs.

Can someone help me understand how to fix these issues or suggest a better approach to create a dynamic tabbed interface?

Thanks in advance!

2

Answers


  1. I suggest using the "active" class consistently, rather than directly changing display styles. Then you can specify the initially selected button/content using "active" classes in the HTML. Similarly, I suggest adding event listeners in JavaScript rather than inline "onclick" events.

    I don’t notice any obvious problem with the smoothness of the CSS transitions.

    For alternative concepts, see: HTML tab interface using only CSS

    // define buttons and contents
    let tabButtons = document.querySelectorAll(".tab-link");
    let tabContents = document.querySelectorAll(".tab-content");
    
    // add event listeners
    tabButtons.forEach((btn) => {
      btn.addEventListener('click', openTab);
    });
    
    // handle button click
    function openTab() {
    
      // get data-tabname value from HTML element
      let tabName = this.dataset.tabname;
    
      // define active content area based on tabName
      let activeContent = document.getElementById(tabName);
    
      // loop through all tabs and toggle active states
      for (i = 0; i < tabButtons.length; i++) {
        let thisButton = tabButtons[i];
        let thisContent = tabContents[i];
        let activeState = (thisContent === activeContent);
        thisButton.classList.toggle("active", activeState);
        thisContent.classList.toggle("active", activeState);
      }
    
    }
    body {
      font-family: Arial, sans-serif;
    }
    
    .tabs {
      overflow: hidden;
      background-color: #f1f1f1;
      border-bottom: 1px solid #ccc;
    }
    
    .tab-link {
      background-color: inherit;
      border: none;
      outline: none;
      cursor: pointer;
      padding: 14px 16px;
      transition: background-color 0.3s;
    }
    
    .tab-link:hover {
      background-color: #ddd;
    }
    
    .tab-link.active {
      background-color: #ccc;
    }
    
    .tab-content {
      display: none;
      padding: 6px 12px;
      border: 1px solid #ccc;
      border-top: none;
    }
    
    .tab-content.active {
      display: block;
    }
    <div class="tabs">
      <button class="tab-link active" data-tabname="Tab1">Tab 1</button>
      <button class="tab-link" data-tabname="Tab2">Tab 2</button>
      <button class="tab-link" data-tabname="Tab3">Tab 3</button>
    </div>
    <div id="Tab1" class="tab-content active">
      <h3>Tab 1</h3>
      <p>Content for Tab 1.</p>
    </div>
    <div id="Tab2" class="tab-content">
      <h3>Tab 2</h3>
      <p>Content for Tab 2.</p>
    </div>
    <div id="Tab3" class="tab-content">
      <h3>Tab 3</h3>
      <p>Content for Tab 3.</p>
    </div>
    Login or Signup to reply.
  2. Try this one hopefully this should be helpful for you. These tab are dynamically created using javasrcipt
    enter image description here

    HTML:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Tabbed Interface</title>
        <link rel="stylesheet" href="styles.css">
    </head>
    <body>
        <div class="tabs" id="tabs"></div>
        <div id="tab-contents"></div>
    
        <script src="script.js"></script>
    </body>
    </html>
    

    CSS:

    body {
       font-family: Arial, sans-serif;
    }
        
    .tabs {
        overflow: hidden;
        background-color: #f1f1f1;
        border-bottom: 1px solid #ccc;
    }
        
    .tab-link {
        background-color: inherit;
        border: none;
        outline: none;
        cursor: pointer;
        padding: 14px 16px;
        transition: background-color 0.3s;
    }
        
    .tab-link:hover {
        background-color: #ddd;
    }
        
    .tab-link.active {
        background-color: #ccc;
    }
        
    .tab-content {
        display: none;
        padding: 6px 12px;
        border: 1px solid #ccc;
        border-top: none;
    }
    

    JavaScript:

     const tabData = [
         { id: 'Tab1', title: 'Tab 1', content: '<h3>Tab 1</h3><p>Content for Tab 1.</p>' },
         { id: 'Tab2', title: 'Tab 2', content: '<h3>Tab 2</h3><p>Content for Tab 2.</p>' },
         { id: 'Tab3', title: 'Tab 3', content: '<h3>Tab 3</h3><p>Content for Tab 3.</p>' }
     ];
    
     function createTabs() {
            const tabsContainer = document.getElementById('tabs');
            const tabContentsContainer = document.getElementById('tab-contents');
    
            tabData.forEach((tab, index) => {
                   
             // Create tab button
             const tabButton = document.createElement('button');
             tabButton.type = 'button';
             tabButton.className = 'tab-link';
             if (index === 0) tabButton.classList.add('active');
             tabButton.textContent = tab.title;
             tabButton.onclick = (event) => openTab(event, tab.id);
             tabsContainer.appendChild(tabButton);
    
             // Create tab content
             const tabContent = document.createElement('div');
             tabContent.id = tab.id;
             tabContent.className = 'tab-content';
             if (index === 0) tabContent.style.display = 'block';
             tabContent.innerHTML = tab.content;
             tabContentsContainer.appendChild(tabContent);
          });
      }
    
      function openTab(evt, tabName) {
           const tabContentElements = document.getElementsByClassName('tab-content');
    
           for (let i = 0; i < tabContentElements.length; i++) {
             tabContentElements[i].style.display = 'none';
           }
    
           const tabLinkElements = document.getElementsByClassName('tab-link');
                
           for (let i = 0; i < tabLinkElements.length; i++) {
              tabLinkElements[i].className = tabLinkElements[i].className.replace(' active', '');
           }
    
            document.getElementById(tabName).style.display = 'block';
            evt.currentTarget.className += ' active';
      }
    
      // Initialize tabs on page load
      window.onload = createTabs;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search