Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 47

JavaScript Tab-Switching

Recommended resources

Hello! Welcome back to building your AI Writing Assistant.

In the last lesson, you did an excellent job setting up the visual foundation for our application's features. You created the HTML structure for the tabs and used CSS to style them, making sure only the default "Summarize" tab is visible when the page loads.

Right now, if you click on the "Correct Grammar" tab, nothing happens. This lesson is all about bringing that static interface to life. Our goal is to implement tab-switching functionality using JavaScript to show and hide content. We'll write the code that listens for clicks on the tab buttons and dynamically updates which tab content is visible.

The Logic: How Tab Switching Works

The core of our task lies in manipulating the active class we created in the last lesson. Remember, the CSS rule .tab-content { display: none; } hides all content panels, while .tab-content.active { display: block; } makes the one with the active class visible.

Our JavaScript will perform the following steps whenever a tab button is clicked:

  1. Identify the clicked tab and the content panel it corresponds to (using the data-tab attribute you already set up).
  2. Reset the interface by removing the active class from all tab buttons and all content panels.
  3. Activate the new selection by adding the active class back to only the button that was just clicked and its corresponding content panel.

This ensures that only one tab and its content are shown at any time.


Implementing the JavaScript Logic

To understand how this is done in code, we'll watch a detailed video tutorial. This video walks through the process of selecting elements, listening for clicks, and managing classes to create a fully functional tabbed interface.

How to Create Switchable Tabs - HTML, CSS & JavaScript Tutorial

The following video from the dcode channel, 'How to Create Switchable Tabs', explains the JavaScript needed to make tabs interactive. We will focus on the part where the JavaScript is written.

Please watch from timestamp 11:59 to 20:43. The video's HTML structure is slightly different from ours, but the JavaScript logic is exactly what we need. Pay close attention to: How querySelectorAll is used to select all the buttons. How addEventListener is used to detect a 'click'. How dataset is used to read the data-* attribute. The logic of removing the 'active' class from all elements before adding it to the selected one.


Writing the Code for Your Project

Now, let's apply the concepts from the video to your script.js file. The logic is the same, but we'll adapt it to match the class names (.tab-button, .tab-content) and attributes (data-tab) in your index.html.

Open your script.js file and add the following code:

// This function will set up our tab functionality.
function setupTabs() {
    // 1. Select all tab buttons and all tab content panels.
    const tabButtons = document.querySelectorAll('.tab-button');
    const tabContents = document.querySelectorAll('.tab-content');

    // 2. Add a click event listener to each tab button.
    tabButtons.forEach(button => {
        button.addEventListener('click', () => {
            // Get the value of the 'data-tab' attribute from the clicked button.
            // This tells us which content panel to show. e.g., "summary"
            const targetTabId = button.dataset.tab;
            const targetContent = document.getElementById(targetTabId);

            // 3. Deactivate all tabs and content panels first.
            // Remove 'active' class from all buttons.
            tabButtons.forEach(btn => {
                btn.classList.remove('active');
            });
            // Remove 'active' class from all content panels.
            tabContents.forEach(content => {
                content.classList.remove('active');
            });

            // 4. Activate the clicked tab and its corresponding content.
            // Add 'active' class to the clicked button.
            button.classList.add('active');
            // Add 'active' class to the target content panel.
            targetContent.classList.add('active');
        });
    });
}

// Run the setup function once the HTML document has finished loading.
document.addEventListener('DOMContentLoaded', () => {
    setupTabs();
});

Let's break this down:

  • document.querySelectorAll('.tab-button'): This selects all elements with the class tab-button and returns them as a list.
  • tabButtons.forEach(button => { ... }): This loops through each button in the list.
  • button.addEventListener('click', () => { ... }): This attaches a function to run every time a button is clicked.
  • button.dataset.tab: This is how you access custom data attributes. It reads the value from data-tab="..." on the button you clicked.
  • document.getElementById(targetTabId): This finds the single content panel whose id matches the clicked button's data-tab value.
  • classList.remove('active') / classList.add('active'): These methods are used to remove or add a CSS class to an element, which triggers our CSS rules for showing and hiding content.

Save your script.js file and open index.html in your browser. Your tabs should now be fully interactive!

For a quick summary and a slightly different code presentation of the same logic, you can check out this article.

Create a Simple Tabbed Component with HTML, CSS & ...

The article 'Create a Simple Tabbed Component' provides a very concise code snippet for the same functionality. It's a great reference for seeing the core logic in a compact form.

Look at the JavaScript code under 'Step 3: Add Tab Logic with JavaScript'. Notice how it achieves the same outcome as our code, just structured slightly differently. This helps reinforce your understanding of the core concepts.

Test your understanding!

In our JavaScript code, what do you think would happen if we forgot to include this part?

// Remove 'active' class from all content panels.
tabContents.forEach(content => {
    content.classList.remove('active');
});
Show answer

If you removed that part, clicking a new tab would still make its button look active, but the old content panel would never disappear. As you click more tabs, more and more content panels would appear on the page, stacked on top of each other. This is because we would only be adding the active class to new content, never removing it from the old ones.


Conclusion

Fantastic work! You have now successfully implemented the JavaScript logic to make your tabbed interface fully interactive. You've learned how to use fundamental JavaScript concepts like querySelectorAll, event listeners, and classList manipulation to dynamically change what's displayed on your webpage. This is a huge step in building a responsive and user-friendly application.

Key Takeaways:

  • JavaScript is used to make web pages interactive by responding to user events like clicks.
  • document.querySelectorAll() is used to grab multiple HTML elements based on a CSS selector.
  • element.addEventListener('click', ...) runs a block of code when an element is clicked.
  • The element.dataset property gives you access to custom data-* attributes.
  • Switching content is often a matter of toggling a CSS class (like .active) that controls visibility.

In our next lesson, we will finally connect the frontend to the backend. You'll learn how to use JavaScript to take the user's text from the text area, send it to one of your Flask API endpoints, and display the AI-generated result back on the page.