Tips for displaying tab content with CSS Grid areas

I have successfully implemented a tabbed interface using CSS Grid areas. However, I am encountering an issue where the tab content is not displaying and the console shows a value of null.

Below is the code snippet that I am currently working with:

function initializeTabs() {
  document.querySelectorAll('.tabs_button').forEach(button => {
    button.addEventListener('click', () => {
      const sidebar = button.parentElement;
      const tabsContainer = document.querySelector("section");
      const tabNumber = button.dataset.forTab;
      const tabToActivate =
        tabsContainer.querySelector('.tabs_content[data-tab="${tabNumber}"]');

      console.log(tabsContainer);
      console.log(tabNumber);
      console.log(tabToActivate);

      sidebar.querySelectorAll(".tabs_button").forEach(btn => {
        btn.classList.remove("tabs_button--active");
      });

      tabsContainer.querySelectorAll(".tabs_content").forEach(tab => {
        tab.classList.remove("tab_content--active");
      });

      button.classList.add("tabs_button--active")
      tabToActivate.classList.add("tabs_content--active")

    });
  });
}
document.addEventListener('DOMContentLoaded', () => {
  initializeTabs();
});
<div class="wrapper">
  <nav class="tabs_sidebar">
    <button class="tabs_button tabs_button--active" data-for-tab="1">Tab #1</button>
    <button class="tabs_button" data-for-tab="2">Tab #2</button>
    <button class="tabs_button" data-for-tab="3">Tab #3</button>
  </nav>

  <section id="main_con" class="tabs_content tabs_content--active">
    <div class="tabs_content tabs_content--active" data-tab="1">
      <h2>Tab #1</h2>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque egestas vitae felis non rhoncus. Integer ultrices dolor nisl, vel suscipit dolor tristique ac. Maecenas pellentesque egestas placerat. Phasellus consequat erat risus </p>
    </div>

    <div class="tabs_content" data-tab="2">
      <h2>Tab #2</h2>
      <p>Nunc vel risus commodo viverra maecenas. Egestas congue quisque egestas diam. Tellus integer feugiat scelerisque varius morbi enim nunc faucibus a. Pharetra et ultrices neque ornare. Aliquam ultrices sagittis orci a scelerisque purus semper eget.
        Viverra justo nec ultrices dui sapien eget mi proin. Lacus vel facilisis volutpat est velit egestas dui id. Magna fringilla urna porttitor rhoncus dolor purus non. Cursus risus at ultrices mi tempus imperdiet. Ornare aenean euismod elementum nisi.
        Morbi blandit cursus risus at ultrices. Vel eros donec ac odio tempor orci. Netus et malesuada fames ac turpis egestas integer. Interdum varius sit amet mattis vulputate enim nulla. Nam libero justo laoreet sit. Imperdiet proin fermentum leo vel
        orci porta non pulvinar. Netus et malesuada fames ac turpis egestas sed tempus urna. Integer quis auctor elit sed vulputate mi. Pellentesque sit amet porttitor eget. Tempor commodo ullamcorper a lacus vestibulum. Laoreet sit amet cursus sit amet
        dictum sit amet justo. Vulputate ut pharetra sit amet aliquam. Sed sed risus pretium quam vulputate. Eget duis at tellus at urna condimentum. Sit amet consectetur adipiscing elit. A scelerisque purus semper eget duis at tellus at urna. Sapien
        eget mi proin sed. </p>
    </div>

    <div class="tabs_content" data-tab="3">
      <h2>Tab #3</h2>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque egestas vitae felis non rhoncus. Integer ultrices dolor nisl, vel suscipit dolor tristique ac. Maecenas pellentesque egestas placerat. Phasellus consequat erat risus. Integer
        ultrices dolor nisl, vel suscipit dolor tristique ac. Maecenas pellentesque egestas placerat. Phasellus consequat erat risus </p>
    </div>
  </section>

</div>

I would greatly appreciate any assistance in resolving this issue.

Thank you for your help!

Answer №1

Here's a suggestion for you. There seems to be an error in your code.

function setupTabs () {
  document.querySelectorAll('.tabs_button').forEach(button => {
    button.addEventListener('click', () => {
      const sideBar = button.parentElement;
      const tabsContainer = document.querySelector("section");
      const tabNumber = button.dataset.forTab;
      const tabToActivate = tabsContainer.querySelector(`.tabs_content[data-tab='${tabNumber}']`);// mistake found here.

      console.log(tabsContainer);
      console.log(tabNumber);
      console.log(tabToActivate);

      sideBar.querySelectorAll(".tabs_button").forEach(button => {
          button.classList.remove("tabs_button--active");
      });

      tabsContainer.querySelectorAll(".tabs_content").forEach(tab => {
          tab.classList.remove("tab_content--active");
      });

      button.classList.add("tabs_button--active")
      tabToActivate.classList.add("tabs_content--active")

    });
});
}
document.addEventListener('DOMContentLoaded', () => {
  setupTabs();
});
The HTML structure should resemble this:

        <div class="wrapper">
            <nav class="tabs_sidebar">
                <button class="tabs_button tabs_button--active" data-for-tab="1">Tab #1</button>
                <button class="tabs_button" data-for-tab="2">Tab #2</button>
                <button class="tabs_button" data-for-tab="3">Tab #3</button>
            </nav>

            <section id="main_con" class="tabs_content tabs_content--active">
                <div class="tabs_content tabs_content--active" data-tab="1">
                <h2>Tab #1</h2>
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque egestas vitae felis non rhoncus. Integer ultrices dolor nisl, vel suscipit dolor tristique ac. Maecenas pellentesque egestas placerat. Phasellus consequat erat risus </p>
                 </div>

                <div class="tabs_content" data-tab="2">
                <h2>Tab #2</h2>
                <p>Nunc vel risus commodo viverra maecenas. Egestas congue quisque egestas diam. Tellus integer feugiat scelerisque varius morbi enim nunc faucibus a. Pharetra et ultrices neque ornare. Aliquam ultrices sagittis orci a scelerisque purus semper eget. Viverra justo nec ultrices dui sapien eget mi proin. Lacus vel facilisis volutpat est velit egestas dui id. Magna fringilla urna porttitor rhoncus dolor purus non. Cursus risus at ultrices mi tempus imperdiet. Ornare aenean euismod elementum nisi. Morbi blandit cursus risus at ultrices. Vel eros donec ac odio tempor orci. Netus et malesuada fames ac turpis egestas integer. Interdum varius sit amet mattis vulputate enim nulla. Nam libero justo laoreet sit. Imperdiet proin fermentum leo vel orci porta non pulvinar. Netus et malesuada fames ac turpis egestas sed tempus urna. Integer quis auctor elit sed vulputate mi. Pellentesqu...
                </div>

                <div class="tabs_content" data-tab="3">
                <h2>Tab #3</h2>
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque egestas vitae felis non rhoncus. Integer ultrices dolor nisl, vel suscipit dolor tristique ac. Maecenas pellentesque egestas placerat. Phasellus consequat erat risus. Integer ultrices dolor nisl, vel suscipit dolor tristique ac. Maecenas pellentesque egestas placerat. Phasellus consequat erat risus </p>
                </div>
            </section>

        </div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble integrating VueX store and router into Mocha tests

Latest Update To view the issue on VueX git repository that has been created, please follow this link: https://github.com/vuejs/vuex/issues/1509 If you want to replicate the problem, here is the link to the repository: https://github.com/djam90/vuex-vue- ...

Exploring the Power of Pythons, Selenium, and XPATH for Handling New Windows

Is it possible to retrieve an element through XPath after using the .click() method when that element is located within a section of JavaScript known as BODY_BLOCK_JQUERY_REFLOW and appears only after the click action? I am attempting to access this speci ...

Failure to load a picture does not trigger onError in the onLoad function

Is there a way to ensure that an image always loads, even if the initial load fails? I have tried using the following code snippet: <img class="small" src="VTVFile4.jpg" onload="this.onload=null; this.src='VTVFile4.jpg?' + new Date();" alt=" ...

Difficulty with CasperJS multi-select functionality

I am currently attempting to utilize CasperJS for choosing both options in a multiple select within an HTML form: <select id="bldgs" name="bldgs" multiple="multiple" size="6" autocomplete="off"> <option value="249759290">Southeast Financia ...

The JQuery.ajax function encountered an unexpected identifier and threw an Uncaught SyntaxError

Hey there, I'm encountering this error and I'm stumped: jQuery.ajax Uncaught SyntaxError: Unexpected identifier I'm attempting to pass some customer information to another file named "pricealarm.php" in the main directory of the FTP-Serve ...

Creating a vertical scrollable container that spans the full height of the PDF document

I am currently working on embedding a PDF file into my website. I'm trying to hide the status bar, including download buttons and page numbers, through some clever techniques so that I can control them externally. My goal is to be able to redirect use ...

The map fails to fully display when using d3.js

Currently, I am developing a globe where multiple locations are marked with small circles. These locations provide relevant information through tooltips when the cursor hovers over them. The issue I am facing is that the global map often renders incomplet ...

Troubleshooting jQuery Div Separation Problem

Currently, I am working on implementing resizable sidebars using jQuery and potentially jQueryUI. However, I am encountering an issue with the resizing functionality. Specifically, the right sidebar is causing some trouble in terms of proper resizing, wher ...

Display the JSON data in a table only if the ID is a match

I am working on a table that consists of 5 rows and 2 columns. Each row is assigned an ID ranging from 1 to 5. My goal is to insert JSON data into the table, but only if the ID in the data matches the ID of the corresponding row. If there is no matching I ...

Creating an Angular library that utilizes HTML components from the application

This is my first attempt at developing an angular library. My goal is to create a header and footer library for angular. The challenge lies in making sure that it integrates seamlessly with the HTML structure of the application it is being used in. Below ...

I am interested in creating a table that can toggle between show/hide mode with a plus/minus feature

$(document).ready(function() { $("#t1").hide(); // hide table by default $("#close").hide(); //hide the minus button as well if you only want one button to display at a time $('#sp1').on('click', function() { //when p ...

Nodejs aggregate lookup fails to find any matching documents

I've created a user model with the following schema: const mongoose = require("mongoose"); const uniqueValidator = require("mongoose-unique-validator"); const userSchema = mongoose.Schema({ email: { type: String, required: true, unique: true }, p ...

"Enhance text formatting by making it stand out when hovered over

I am encountering an issue where the hover action for a specific letter begins before the mouse actually touches the text. In this case, I want the letter 'P' in 'Paul' to turn white when hovered over. The image illustrates the distanc ...

Flexbox not rendering correctly on IE and Chrome browsers

Initially, I avoided using flexboxes because of concerns about older browser support. However, the alternative involved floats, margins, z-indexes, and resulted in a layout that was visually unattractive. Despite setting specific dimensions for the left-h ...

Troubleshooting compatibility issues between JS and ng-view in AngularJS

In my AngularJS SPA project, I am using ngRoute along with Bootstrap's Carousel template. However, I have run into an issue where certain functionalities ceased to work once I started using ng-view instead of placing all the main content in the index. ...

Calculating the sum of all values in the database

In my database, I have a value called task_time. I want to add this value to itself so that the total time is calculated as totalTime = task_time + task_time + ... + task_time. This is how I retrieve the data: function getEndTasks() { $http.get(& ...

What's the advantage in using 2 functions instead of just utilizing one?

When I'm asking for help with my code, I make sure to include all of it in case there's a connection between the different functions. Recently, I received assistance to get one of my functions working properly. Specifically, I'm looking at t ...

Angular2: Dynamically switch between selected checkboxes in a list

Is there a way to toggle a checked checkbox list in Angular2? I am trying to create a button that, when pressed while the full list is visible, will display only the checked items. Pressing the button again would show the entire list. Here's the Plu ...

Is there a way to reverse the confirmation of a sweet alert?

Hey there, I'm currently using Sweet Alert to remove a product from my website. I want to implement it with two options - 'ok' and 'cancel'. However, I'm facing an issue where clicking anywhere on the page removes the product ...

CSS: The relative positioned element now functions correctly with the inclusion of overflow-x

Is there a way to ensure that the images in the day_time_block cover the title class? I would also like all contents within the day_time_block to be displayed using overflow-x. However, when I add overflow-x: auto; to the scroll div, the images in the d ...