The implementation of classList.toggle in my JavaScript code is not functioning as expected

I created a button that toggles the visibility of a div. It works fine the first couple of times, but then it stops working. When I click on column1, the hidden div inside column1 doesn't appear. But when I click on column2, the hidden div inside column2 does show up.

Apologies for my poor English, but I really want to understand why this is happening!

var tabList = document.querySelectorAll("li");

tabList.forEach(function(tab, index) {
  tab.addEventListener('click', function() {
    removeOther();
    tab.classList.toggle("on");
    btnEvent(tab);
  });
});

function removeOther() {
  for (var i = 0; i < tabList.length; i++) {
    if (tabList[i].classList.contains("on")) {
      tabList[i].classList.remove("on");
    }
  }
}

var btn = document.getElementsByTagName("button")[0];

function btnEvent(tab) {
  var hiddenTabs = tab.querySelectorAll('.hidden');
  btn.addEventListener("click", function() {
    for (var i = 0; i < hiddenTabs.length; i++) {
      hiddenTabs[i].classList.toggle("hidden");
    }
  })
}
div {
  background: salmon;
  width: 50px;
  height: 50px;
  margin: 5px;
  display: none;
}

div.hidden,
li.on div.hidden {
  display: none;
}

li.on div {
  display: block;
}
<ul>
  <li class="on">column1
    <div>box</div>
    <div>box</div>
    <div>box</div>
    <div class="hidden">box</div>
    <div class="hidden">box</div>
    <div class="hidden">box</div>
  </li>
  <li>column2
    <div>box</div>
    <div>box</div>
    <div>box</div>
    <div class="hidden">box</div>
    <div class="hidden">box</div>
    <div class="hidden">box</div>
  </li>
  <li>column3
    <div>box</div>
    <div>box</div>
    <div>box</div>
    <div class="hidden">box</div>
    <div class="hidden">box</div>
    <div class="hidden">box</div>
  </li>
</ul>
<button>click!</button>

Answer №1

Kindly review the JavaScript code snippet provided below:

var tabList = document.querySelectorAll("li");

// repositioning the btn selector to the beginning of the code
var btn = document.getElementsByTagName("button")[0];

tabList.forEach(function(tab, index) {
  tab.addEventListener('click', function() {
    removeOther();
    tab.classList.toggle("on");
    btnEvent(tab);
  });

  // triggering the click event on the first tab element by default
  if (index < 1) tab.click();
});

function removeOther() {
  for (var i = 0; i < tabList.length; i++) {
    if (tabList[i].classList.contains("on")) {
      tabList[i].classList.remove("on");
    }
  }
}

function btnEvent(tab) {

  // adding .not-hidden to identify .hidden elements
  var hiddenTabs = tab.querySelectorAll('.hidden,.not-hidden');

  // should be executed as onclick attribute
  btn.onclick = function() {
    for (var i = 0; i < hiddenTabs.length; i++) {
      hiddenTabs[i].classList.toggle("hidden");

      // switching element class to .not-hidden if it's not hidden
      hiddenTabs[i].classList.toggle("not-hidden");
    }
  }
}
div {
  background: salmon;
  width: 50px;
  height: 50px;
  margin: 5px;
  display: none;
}

div.hidden,
li.on div.hidden {
  display: none;
}

li.on div {
  display: block;
}
<ul>
  <li class="on">column1
    <div>box</div>
    <div>box</div>
    <div>box</div>
    <div class="hidden">box</div>
    <div class="hidden">box</div>
    <div class="hidden">box</div>
  </li>
  <li>column2
    <div>box</div>
    <div>box</div>
    <div>box</div>
    <div class="hidden">box</div>
    <div class="hidden">box</div>
    <div class="hidden">box</div>
  </li>
  <li>column3
    <div>box</div>
    <div>box</div>
    <div>box</div>
    <div class="hidden">box</div>
    <div class="hidden">box</div>
    <div class="hidden">box</div>
  </li>
</ul>
<button>click!</button>

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

To enable RTL in TextField, please note that the JssProvider is only available in "react-jss/src/JssProvider" and not in "react-jss/lib/JssProvider"

Seeking help to convert LTR to RTL in the following code: <TextField id="date" label="EmployeeDate" type="date" onChange= ...

The issue with Lodash isEqual arises from the constructor specified by Angular

Currently, I am utilizing Lodash _.isEqual for performing a deep comparison between a local JavaScript object and another JavaScript object fetched through angular $get. The initial code indicates that the objects are not the same: $get({...}, function ( ...

Vue.js variable routes present an issue where the Favicon fails to appear

I've successfully set my favicon in the index.html file for my Vue webpack SPA. It displays properly when I visit the main site or any standard route, but it fails to show up when I navigate to a dynamic route (path: "/traduzione/:translation"). I&ap ...

Tips for preserving newly add row with the help of jquery and php

Currently, I am attempting to implement a functionality on a Wordpress theme options page that dynamically adds rows using jQuery. Below is the HTML code snippet from the THEME-OPTIONS page <a href="#" title="" class="add-author">Add Author</ ...

Having difficulty loading the JSON configuration file with nconf

I'm currently attempting to utilize nconf for loading a configuration json file following the example provided at: https://www.npmjs.com/package/nconf My objective is to fetch the configuration values from the json file using nconf, however, I am enc ...

Different options for determining network connectivity on a website

Seeking Network and Location Information on ASP.Net Core MVC Web Application After some investigation, I came across the Navigator API online. For acquiring location data, it functions flawlessly. navigator.geolocation.getCurrentPosition(function (posi ...

How to prevent CSS styles from being overridden by SASS in a stylesheet

When working with a Sass file, I encountered an issue with the way styles were being output. The original style in the Sass file looked like this: .style{ width: calc(100%); } However, when compiled to its corresponding CSS file, the output was: .style{ ...

Javascript - struggling with implementing changeClass() function on click event

I am working on creating movable images within a container using the jQuery plugin found at . My goal is to have items appear within the container when clicked, but I am struggling with changing the class of my object (.item) outside of the container. Th ...

implement a Django for loop within the template by utilizing JavaScript

Is it possible to incorporate a {% for in %} loop and {{ variables }} in a Django template using JavaScript DOM (insertAdjacentText, or textContent) and dynamically load data from the views without refreshing the entire page? If so, can you please guide me ...

Tips for triggering functions when a user closes the browser or tab in Angular 9

I've exhausted all my research efforts in trying to find a solution that actually works. The problem I am facing is getting two methods from two different services to run when the browser or tab is closed. I attempted using the fetch API, which worke ...

The issue of Dynamoose/DynamoDB converting empty arrays to null during updates

Utilizing the Node.js package Dynamoose to manage DynamoDB requests within my web application has been a challenge. An issue arises when attempting to update an item that contains an empty array in the JSON object. It seems that Dynamoose is setting this ...

Unable to view videos shared by users in PeerJS and WebRTC video chat application from different tabs

Recently, I embarked on the task of creating a Video chat Website using Peer Js. Initially, everything seemed to be working fine as I was able to see my own video stream. However, a problem arose when attempting to view the video stream from another tab or ...

Error in Access-Control-Allow-Origin when using Node.js and JSONP

It seems like JSONP eliminates cross domain restrictions. I am currently attempting to create a JSONP service with node and express. Below is a simple example of the code: self.routes['/portfolio'] = function(req, res) { // Website you wis ...

Execute a node script file at random intervals

I've been utilizing forever to maintain the continuous execution of a node script: forever start script1.js However, my requirement is to run these files in a random order... For instance: Execute node script1.js Execute node script2.js Run script ...

What can cause my function to return true on the server but false on the client side in Meteor.js?

I am facing an issue with the hasCompleted function which returns true or false on the server side: Smaples.helpers({ hasCompleted(userId) { // … switch (this.frequency) { case Frequency.ONE_TIME:{ return measures.fetch().every(mea ...

What is the best way to combine TypedArrays in JavaScript?

Looking to combine multiple arraybuffers into a Blob, but facing limitations with TypedArrays that lack handy methods like "push". For example: var x = new Int8Array( [ 1, 2, 3 ] ); var y = new Int8Array( [ 4, 5, 6 ] ); The desired outcome is to have [ ...

What is the best way to position the div element to the right side of the webpage?

Looking at my HTML code below, I am trying to reposition the 'site-logo' and 'nav-search-wrapper' div elements to the left side of the parent div (top-nav) and have the 'list' div element appear on the right side. However, the ...

Illuminate a corresponding regular expression within a text input

I currently have a functional code for testing regex, which highlights matching patterns. However, my challenge lies in highlighting the result within the same input as the test string. Below you will see the HTML and JavaScript snippets along with two ima ...

Managing toggles for save and edit buttons in Vue - a comprehensive guide

I am currently working on a Vue 'app' within a larger Django application as a means to enhance my understanding of Vue. My objective is to create unique forms that can be edited independently. I have been experimenting with this for some time n ...

Tips for aligning a Font-Awesome icon vertically centered with a line of text in Bootstrap 4

My goal is to vertically center a Font Awesome icon next to a small block of text. To better illustrate, here is a reference image of what I am aiming for: This is the visual I aspire to achieve The section of my website that I am currently fine-tuning ca ...