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

The CORS policy has blocked access to XMLHttpRequest from 'localhost' to 'localhost'. A preflight response is required

I'm encountering the following error message: Access to XMLHttpRequest at 'https://localhost:44355/Brand' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access ...

"Using regular expressions in a MongoDB find() query does not provide the desired

app.get("/expenses/:month", async (req, res) => { const { month } = req.params; const regexp = new RegExp("\d\d\d\d-" + month + "-\d\d"); console.log(regexp); const allExpenses ...

What are the best practices for dynamically handling variables in JavaScript?

I am looking to dynamically work with variables and store their references in a collection. My first question is: How can I save a variable reference (not its value) in a collection? For example: var apple = "A delicious fruit"; var banana = "A yellow f ...

PHP JSON Return for Empty Ajax Response

I'm currently learning PHP and JS, and I have run into an issue while using Ajax to do a GET request. The PHP return is showing up as white for me. I have searched the internet but haven't been able to find a solution. Any help would be much appr ...

Challenges with HTML and Session Handling

It's not functioning properly! <?php session_start(); ?> <p class="username"><?php echo $_SESSION['name']; ?></p> ...

Utilizing Regular Expressions for extracting data from an HTML webpage

Is it possible to extract the response "Here is the solution" from an HTML document using Regular Expression? <b>Previous Query:</b> <b>Here is the answer</b> ...

looking to restrict the interface to only specific types

Currently working with TypeScript and I have a query regarding the utilization of TypeScript interface. Is there a way to selectively extract and output specific key types from the interface being used? While I am able to isolate the type I need, I am inte ...

Stop the automatic hiding of the sticky header when reaching the bottom of the page

I have implemented the position: sticky property for my website's header. However, I am facing an issue where the header becomes hidden when I scroll halfway down the page (bottom on mobile devices). Can anyone suggest a solution to fix this problem? ...

Upon encountering an expression, the code anticipated either an assignment or a function call, but instead found an expression, triggering the no

When using the forEach method within a function in JavaScript, I encountered a code compilation failure with the following error: Expected an assignment or function call and instead saw an expression no-unused-expressions. This error occurs for both ins ...

What is the best way to showcase a value in JavaScript using CSS styling?

I'm looking to customize the background, font style, and outline for both open and closed elements in the code snippet below: a.innerHTML = "We are Open now now."; a.innerHTML = "We are Closed, arm."; Additionally, I want to appl ...

How can we control the content being displayed on our tree?

Is there a way to customize the view of our V-treeview by filtering what is displayed? By entering the beginning of an element key in the filter field input, the tree will only show elements whose keys match the input. I am working on Vue.js with the late ...

What is the best way to access a specific attribute of an HTML element?

Within my ng-repeat loop, I have set a custom attribute like this: <div ng-repeat="item in itemsList" stepType="{{item.stepType}}"> {{item.itemValue}} </div> The possible values for item.stepType are 'task' or 'action ...

The JSON format provided is not valid

Currently, I am in the process of constructing a JSON object and sending it to the server using JQuery ajax. data: "{'authorID' : '" + authorID + "', 'title' : '" + encodeURIComponent(blogTitle) + "', &a ...

What steps can be taken to avoid the duplication of color and stock values when including additional sizes?

Individual users have the ability to include additional text fields for size, color, and stocks. When adding more sizes, the data inputted for colors and stock will duplicate from the initial entry. Desired output: 1st Size : small color: red, stocks: 10 ...

How can you trigger an event when a table cell is selected and a key is pressed?

In my project, I have some td elements with a class name assigned to them. My goal is to trigger a pop-up window when one of these td elements is in focus and the F9 key is pressed. Here's what I've attempted so far: $(document.body).keypress(fu ...

Exploring jQuery: Moving between different table cells using traversal techniques

Seeking assistance from experienced jQuery users as I am new to this library and may not be approaching this task correctly. I have a dynamically generated HTML table that is quite extensive. To enhance user experience, I aim to assign navigation function ...

Six Material-UI TextFields sharing a single label

Is there a way to create 6 MUI TextField components for entering 6 numbers separated by dots, all enclosed within one common label 'Code Number' inside a single FormControl? The issue here is that the label currently appears only in the first tex ...

Exploring Vaadin 14 Slider Components

I'm looking for help on how to incorporate a slider into my Vaadin 14 project. I discovered that the slider component was removed in Vaadin 10, so I turned to this alternative: Once I added the Maven dependency and repository to my pom.xml, I success ...

Applying FadeIn Effect to Background Image on Hover

For several applications, I have utilized this jQuery code that swaps images with a smooth fading effect. It's incredibly straightforward. $(document).ready(function() { $("img.a").hover( function() { $(this).stop().animate({ ...

Why isn't res.send() in Node.js sending the message?

Despite numerous attempts, I am unable to send my response message. It was working briefly, but after some code changes, it stopped functioning. Can anyone provide a solution to this challenging issue? exports.listBoth = function(req, res) { ...