Different div elements are clashing with each other when it comes to hiding and

Having added multiple div elements with different IDs, I am facing an issue where clicking one div displays it while hiding the others. I am looking for a solution to prevent conflicts between the divs. Any suggestions on what might be causing this problem?

var divs = ["on1", "off1", "on2", "off2", "on3", "off3"];
var visibleDivId = null;

function divVisibility(divId) {
  if (visibleDivId === divId) {
    visibleDivId = null;
  } else {
    visibleDivId = divId;
    hideNonVisibleDivs();
  }

}

function hideNonVisibleDivs() {
  var i, divId, div;
  for (i = 0; i < divs.length; i++) {
    divId = divs[i];
    div = document.getElementById(divId);
    if (visibleDivId === divId) {
      div.style.display = "block";
    } else {
      div.style.display = "none";
    }
  }
}
.buttons a {
  font-size: 16px;
}

.buttons a:hover {
  cursor: pointer;
  font-size: 16px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="main_div">
  <div class="buttons">
    <a href="#" onclick="divVisibility('on1');">On</a> |
    <a href="#" onclick="divVisibility('off1');">Off</a> |
  </div>
  <div class="inner_div">
    <div id="on1">I'm Div One</div>
    <div id="off1" style="display: none;">I'm Div Two</div>
  </div>
</div>

<div class="main_div">
  <div class="buttons">
    <a href="#" onclick="divVisibility('on2');">On</a> |
    <a href="#" onclick="divVisibility('off2');">Off</a> |
  </div>
  <div class="inner_div">
    <div id="on2">I'm Div One</div>
    <div id="off2" style="display: none;">I'm Div Two</div>
  </div>
</div>

<div class="main_div">
  <div class="buttons">
    <a href="#" onclick="divVisibility('on3');">On</a> |
    <a href="#" onclick="divVisibility('off3');">Off</a> |
  </div>
  <div class="inner_div">
    <div id="on3">I'm Div One</div>
    <div id="off3" style="display: none;">I'm Div Two</div>
  </div>
</div>

Answer №1

It appears that your issue has been well understood. Is the proposed logic aligned with your expectations?

After reviewing your code, I noticed that the complex nature of the HTML markup and solution logic could potentially hinder flexibility. Specifically, adding new main_div elements would require manual registration in an array.

To address this concern, I have completely rewritten the code snippet as follows:

allOnOffButtons = document.querySelectorAll("a");

allOnOffButtons.forEach(button=>{
  button.addEventListener('click', handleVisibility);
})

function handleVisibility(e) { 
  // check if the button was on or off
  const clickedButtonClass = e.srcElement.className;
  
  // grab the inner div that belongs to the clicked button
  const clickedinnerDiv = e.srcElement.closest(".main_div").querySelector(".inner_div");
 
  // find all divs inside the given inner_div
  const allDivsInsideInnerDiv = clickedinnerDiv.querySelectorAll("div");

  // check if they should be shown or hidden
  allDivsInsideInnerDiv.forEach(div => {
    if (div.className === clickedButtonClass) {
       div.style.display = "block";
    } else {
       div.style.display = "none";
    }
  })
}
.buttons a {
  font-size: 16px;
}

.buttons a:hover {
  cursor: pointer;
  font-size: 16px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="main_div">
  <div class="buttons">
    <a href="#" class="on">On</a> |
    <a href="#" class="off">Off</a> |
  </div>
  <div class="inner_div">
    <div class="on">I'm Div One (on)</div>
    <div class="off" style="display: none;">I'm Div Two (off)</div>
  </div>
</div>

<!-- Additional instances of main_div here -->

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

Unique calculation for rotational movement

I am currently developing a unique compass application. Although the project is progressing well, I am facing a significant challenge with one aspect: My code calculates degree angles within the range of -360 and 360: -318°, -29°, 223°, -163°, ... ...

Is a Javascript-only application compatible with Amazon S3 cloud storage?

I am currently investigating the validity of the following statement: Based on my research, it seems unlikely to create a web application using only JavaScript - without any server-side logic - hosted on Amazon S3 that can also store data solely on S3 whi ...

Revise code according to updates in the shopping cart

I've been using cart.js for quite some time now in my stores. Currently, I am working on implementing a countdown to free shipping based on the cart's total price. It seems like a simple task, but I'm facing an issue with updating the #count ...

Step-by-Step Guide: Unveiling a Particular Modal Post-Submission of Form with

My website has a form inside a modal, and when the form is submitted, I don't want the modal to close. However, I have encountered an issue because my SQL UPDATE statement redirects to the same page after updating the database. This disrupts the funct ...

Div element obstructing the ability to view markers

Issue with a positioned DIV over Google Maps: The DIV is causing accessibility problems for the map, taking up the entire width when it should stop at the green square borders. Interaction with the map is limited to the very bottom after the green square. ...

What causes Vue to only update once when there are two closely timed mutations to reactive data?

Can you take a look at this simple example? export default { data() { return { name: "Amy", age: 18, }; }, computed: { combinedDataForWatching() { return { name: this.name, age: this.age, ...

Issue with IE7 causing div elements to slide off the screen on specific WordPress pages

Encountering a strange IE7 bug on two pages of a WordPress site I'm currently developing. Some divs are shifting to odd positions, with one completely off the screen: and another here: Additionally, possibly related or not, the "created by" link in ...

The error message "GetListItems is not defined" indicates that the function is not recognized

I am currently working on a project in SPFx using React, where I need to retrieve SharePoint list items that exceed 5000 through a REST call. Everything seems to be going smoothly until an error occurs during the next iteration process, displaying this me ...

`I'm having difficulty transferring the project to Typescript paths`

I posted a question earlier today about using paths in TypeScript. Now I'm attempting to apply this specific project utilizing that method. My first step is cloning it: git clone <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

What could be causing the issue: Unable to locate or read the file: ./styles-variables?

I'm currently following a tutorial on how to create responsive layouts with Bootstrap 4 and Angular 6. You can find the tutorial here. I've reached a point where I need to import styles-variables.scss in my styles file, but I keep encountering t ...

Utilizing JavaScript text variables as hidden inputs

My JavaScript code is responsible for populating a modal from various sections of a website. Essentially, when the modal expansion button is clicked, it collects all data associated with that particular button press. While this functionality works flawles ...

How can we sort an array based on the inner HTML values of its children elements in JavaScript?

Can you arrange a JavaScript array based on the innerText values of its HTML elements? I am generating a div element (class="inbox" id="inbox${var}") with a number as its innerText, then adding all these divs to an array (numArr). I wan ...

What is the best way to transfer parameters from the Vue root to a component?

Currently, I am attempting to transfer a string value from index.cshtml to the main Vue element. The specific parameter I want to pass is: userId Location: Index.cshtml (this is where the parameter is obtained) @using Microsoft.AspNetCore.Identity @inje ...

NextJs getStaticPaths function is failing to render the correct page, resulting in a 404 error message being displayed

Hey there, I'm in a bit of a pickle as I've never used 'getStaticPaths' before and it's crucial for my current project! I followed the example code from NextJs's documentation on 'getStaticPaths', but when I try to ...

The jQuery half rating by Chris Richards is a game-changer in the world

I've been utilizing the Chris Richards jQuery rating plugin and have found it to be incredibly helpful and user-friendly. However, I require the ability to include half ratings, which the current plugin does not support. Is there a way to modify the p ...

What is the best way to extract a thumbnail image from a video that has been embedded

As I work on embedding a video into a webpage using lightbox, I'm looking for advice on the best design approach. Should the videos be displayed as thumbnails lined up across the page? Would it be better to use a frame from the video as an image that ...

Discovering an <a> element with an href attribute containing two specified strings

Here's what I have: $("a[href*='string1' && 'string2']") Unfortunately, this code didn't work for me. I also attempted: $("a:contains('string1' && 'string2')") The second one only return ...

At what point does the chaining of async/await come to an end?

I was experimenting with node-fetch and encountered a question while using async / await: Do I need to make my function async if I use await in it? But then, since my function is async, I need to await it and make the parent function async. And so on... He ...

The HTML object is experiencing difficulties with the Ajax page loader feature not functioning as

I attempted to use the code below in order to show an Ajax loader image while the page loads into an HTML object. Unfortunately, it didn't work as expected and I'm having trouble figuring out why. Everything seems to be functioning correctly exce ...

Exploring the Power of Vue 3 in Manipulating the DOM

Hello everyone, I am a beginner with Vue and I am interested in learning how to modify the DOM without relying on methods such as document.querySelector or getElementById. Let's take for instance this input: <input id="myInputId" class=& ...