Why does the content not appear again when switching between tabs?

Hello! I'm facing an issue with toggling between two sets of content on my page. Initially, the correct content shows up, but when I switch tabs, the new content doesn't appear. Furthermore, if I click back to the first tab, that content disappears as well.

How can I ensure a smooth toggle between the different content sections without any disappearing act?

    const dropdown = document.querySelector('.dropdown-select');
    const dropdownItem = document.querySelectorAll('.dropdown-select .menu li');

    dropdown.addEventListener('click', (e) => {
      if (dropdown.classList.contains('closed')) {
        dropdown.classList.remove('closed');
        dropdown.classList.add('open');
      } else {
        dropdown.classList.add('closed');
        dropdown.classList.remove('open');
      }
    });

    for (let i = 0; i < dropdownItem.length; i++) {
      dropdownItem[i].addEventListener('click', function () {
        const dropdownItemClicked = document.querySelector('.menu li.active');
        if (dropdownItemClicked) dropdownItemClicked.classList.remove('active');
        dropdownItem[i].classList.add('active');
      })
    }

    const options = document.querySelectorAll('.menu li')

    const results = document.querySelectorAll('.tabbed-content div')
    options.forEach(e => e.addEventListener('click', function () {
      results.forEach(f => f.style.display = f.id == e.dataset.target ? "block" : "none")
    }));
.dropdown-select {
  transition: all 0.2s ease;
  overflow: hidden;
  cursor: pointer;
  border-top: 1px solid #E0E5EC;
  width: 100%;
}
@media (min-width: 768px) {
  .dropdown-select {
    display: flex;
    align-items: center;
    cursor: default;
    border-bottom: 1px solid #E0E5EC;
    height: 3.75rem;
  }
}
.dropdown-select.open {
  box-shadow: 0px 8px 24px rgba(0, 0, 0, 0.1);
}
@media (min-width: 768px) {
  .dropdown-select.open {
    box-shadow: unset;
  }
}
.dropdown-select__title {
  display: flex;
  align-items: center;
  padding-top: 1rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #E0E5EC;
}
@media (min-width: 768px) {
  .dropdown-select__title {
    border-bottom: unset;
  }
}
.dropdown-select__title h6 {
  font-size: 0.75rem;
  line-height: 0.75rem;
  letter-spacing: 1px;
  text-transform: uppercase;
  pointer-events: none;
}
.dropdown-select__title img {
  width: 1.312rem;
  height: 0.656rem;
  margin-left: auto;
  transition: all 0.2s ease;
}
.dropdown-select ul {
  margin: 0;
  padding: 0;
  list-style-type: none;
}
.dropdown-select .menu li {
  font-size: 1rem;
  line-height: 1.5rem;
  padding: 1rem 0;
  font-weight: 800;
  color: #6D7582;
}
@media (min-width: 768px) {
  .dropdown-select .menu li {
    padding: 0;
    cursor: pointer;
    display: flex;
    flex-direction: column;
  }
  .dropdown-select .menu li:first-child {
    margin-right: 2rem;
  }
}

.tabbed-content {
  padding-left: 1.25rem;
  padding-right: 1.25rem;
}
.tabbed-content .release {
  display: none;
}
  <main>
    <div class="dropdown-select closed">
      <div class="dropdown-select__title">
        <h6>Other Releases</h6>
        <img src="https://cdn-icons-png.flaticon.com/24/25/25243.png" alt="down caret ">
      </div>
      <ul class="menu">
        <li data-target="fall21" class="active">Fall 2021</li>
        <li data-target="summer21">Summer 2021</li>
      </ul>
    </div>
    <h6 class="intro kicker kicker--bold">Product Releases</h6>

    <div class="tabbed-content">
      <div id="fall21" class="release" style="display: block;">
        <div class="page-hero">
          <h2>Fall 2021</h2>
        </div>

      </div>
      <div id="summer21" class="release">
        <div class="page-hero">
          <h2>Summer 2021</h2>
        </div>
      </div>
    </div>
  </main>

Answer №1

I have corrected your snippet.

You had an error in the selector on this line:

const results = document.querySelectorAll('.tabbed-content div')

To select only the direct children of the .tabbed-content, you need to add > otherwise, it will select all the divs inside it.

So the corrected line should be:

const results = document.querySelectorAll('.tabbed-content > div'

let dropdown = document.querySelector('.dropdown-select');
          let dropdownItem = document.querySelectorAll('.dropdown-select .menu li');

          dropdown.addEventListener('click', (e) => {
            if (dropdown.classList.contains('closed')) {
              dropdown.classList.remove('closed');
              dropdown.classList.add('open');
            } else {
              dropdown.classList.add('closed');
              dropdown.classList.remove('open');
            }
          });

          for (let i = 0; i < dropdownItem.length; i++) {
            dropdownItem[i].addEventListener('click', function () {
              let dropdownItemClicked = document.querySelector('.menu li.active');
              if (dropdownItemClicked) dropdownItemClicked.classList.remove('active');
              dropdownItem[i].classList.add('active');
            })
          }

          const options = document.querySelectorAll('.menu li')

          const results = document.querySelectorAll('.tabbed-content > div')
          options.forEach(e => e.addEventListener('click', function () {
            results.forEach(f => f.style.display = f.id == e.dataset.target ? "block" : "none")
          }));
.dropdown-select {
        transition: all 0.2s ease;
        overflow: hidden;
        cursor: pointer;
        border-top: 1px solid #E0E5EC;
        width: 100%;
      }
      @media (min-width: 768px) {
        .dropdown-select {
          display: flex;
          align-items: center;
          cursor: default;
          border-bottom: 1px solid #E0E5EC;
          height: 3.75rem;
        }
      }
      
      /* Additional CSS code goes here */
      
<main>
          <div class="dropdown-select closed">
            <div class="dropdown-select__title">
              <h6>Other Releases</h6>
              <img src="https://cdn-icons-png.flaticon.com/24/25/25243.png" alt="down caret ">
            </div>
            <ul class="menu">
              <li data-target="fall21" class="active">Fall 2021</li>
              <li data-target="summer21">Summer 2021</li>
            </ul>
          </div>
          <h6 class="intro kicker kicker--bold">Product Releases</h6>
      
          <div class="tabbed-content">
            <div id="fall21" class="release" style="display: block;">
              <div class="page-hero">
                <h2>Fall 2021</h2>
              </div>
      
            </div>
            <div id="summer21" class="release">
              <div class="page-hero">
                <h2>Summer 2021</h2>
              </div>
            </div>
          </div>
        </main>

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

Why isn't the length of the Array changing when using React's useState hook

I am facing a challenge trying to understand why the value of inputElementArray.length consistently remains 0 when accessed within the useEffect method. function view() { const [inputElementArray, setInputElementArray] = useState<HTMLInputElement[]& ...

Discover how to utilize images encoded in base64 format within webhook embeds on Discord

Can someone help me with inserting an image into a Discord embed using a webhook? I have the image saved as a base64 string obtained from a database. However, my attempts so far have only resulted in an empty embed. const data = b64image.split(',&ap ...

Using HTML and JavaScript to add variables into the URL within the window.location

I have been struggling to incorporate longitude and latitude into the URL. Despite researching various topics online, I have not found a solution that works for me. Below is the HTML code that showcases the issue. When you click the "Show Position" button ...

An effective method for binding items permanently while still being able to update the entire selection

Imagine a scenario where a list of 1000 items is displayed using infinite scrolling. Each item on the list includes a person's firstName, lastName, and mood for simplicity. Initially, I didn't want to constantly listen for updates. Fortunatel ...

Tips for setting a data-attribute on the body tag using the current route name in Vue

I have been considering adding a data-attribute to the body of my vue-app that would display the current route's name. I prefer not to utilize the vue-body-class package and want to keep it simple. Currently, I am implementing this in each of my main ...

Node.js: Steps for receiving an ArrayBuffer in a $http request

I made a request using $http.post from Angular.js to Node.js, expecting to receive an ArrayBuffer. Here is the code snippet: $http.post('/api/scholarships/load/uploaded-files', Global.user, {responseType:'arraybuffer'}).success(functi ...

Looking for assistance with getting 2 functions to run onLoad using Ajax - currently only 1 is operational

In the coding journey, I first implemented shuffle functions for arrays which was successful. Then, I proceeded to define two global variables that would dictate the random order in which images are displayed on the webpage. The variable picOrder was meant ...

How can I filter an array to retain only the initial 5 characters of every element?

I need help using the .map function to transform this array so that only the first 5 characters are displayed, like "01:00", "02:00"? This is the array: ["01:00:00 AM", "02:00:00 AM", "03:00:00 AM", "04:00:00 AM", "05:00:00 AM", "06:00:00 AM", "07:00:00 ...

What is the best way to design a dynamic gallery that showcases three columns for large screens, but switches to two columns for mobile devices?

My goal is to create an image gallery using Bootstrap, with 3 columns on large screens and 2 columns on mobile. I want to maintain the aspect ratio of each image while fixing the width so they align within the columns. I was able to achieve this on large s ...

Issue with RequireJS: The data-main attribute fails to load the specified file

As I convert my small project into nodejs, I am facing an issue with the requireJS file that defines the JS to be used in the project not loading properly. Below is the structure of my project: https://i.sstatic.net/oYnqn.png The ng-app specifies the fr ...

Troubleshooting the issue with generateStaticParams() in NextJs/TypeScript

My NextJs app has a products page that should render dynamic routes statically using generateStaticParams(). However, this functionality does not work as expected. When I run "npm run build," it only generates 3 static pages instead of the expected number. ...

Tips for showcasing beautifully formatted XML content on a webpage

I have some XML data that I want to display on my website, but I'd prefer to show it in a styled format like a bootstrap table. However, I'm not sure how to go about doing this. Here's an example of the XML: <?xml version="1.0" encoding ...

Running the `npm start` command in Angular tends to be quite time-consuming

When I use Visual Studio Code to run Angular projects, my laptop seems to take a longer time when running the server through npm start compared to others. Could this delay be related to my PC specifications, or is there something I can do to improve it? ...

Mocha avoids running the test

Hi everyone, I am a beginner in Node.js and JavaScript and I'm having trouble understanding why Mocha is skipping over my test. I know that I may not be using the request and supertest libraries correctly, but I really want to figure out why, when it ...

Immutable.Map<K, T> used as Object in Typescript

While refactoring some TypeScript code, I encountered an issue that has me feeling a bit stuck. I'm curious about how the "as" keyword converts a Map<number, Trip> into a "Trip" object in the code snippet below. If it's not doing that, the ...

Determine the width of a div by utilizing SASS and following a series of incremental steps

Let's discuss the current scenario: I have a parent div that consists of multiple child elements which vary in number. (2, 3, 4) The goal is to determine the appropriate width for each step element dynamically: For 2 steps: 50% For 3 steps: 33.3% ...

When utilizing Dynamic Links for routing in Next.js, the props are not successfully passed to redirected components

Currently, I am immersing myself in the world of Next.js with the help of the book "Building React Apps using server-side rendering". As part of my learning process, I am constructing a basic react application that consists of an index page linking to an ...

Is there a way to integrate PHP functionality into JavaScript?

When it comes to using JavaScript and PHP together, a common challenge is retrieving information from a database and utilizing that data in a JavaScript function. In my case, I need this functionality for implementing password change functionality on a w ...

What is the best way to switch the site header in JavaScript or jQuery?

I have created a Bootstrap menu design and I am looking to add a sliding functionality to it. My goal is to hide the menu when scrolling down and display it when scrolling up (slide-down / slide-up). For implementing this feature, I plan to utilize jQuery ...

Ways to engage with a fixed html page generated by an Express router?

Let me start by mentioning that I am relatively new to working with NodeJs. Currently, I am dealing with a situation where I need to render a static HTML web page (which includes JavaScript code) as a response to a post request. Below is the relevant snipp ...