Ways to display or conceal various divs by employing an if/else statement?

I am aiming to conditionally display various divs based on certain criteria:

  • Show the "x" div if it's not already visible
  • Display the "y" div only if the "x" div is already being displayed
  • Show the "z" div only if both the "x" and "y" divs are already visible

The following code allows me to toggle a single div between displaying and not displaying:

function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

However, when I attempt to do this for multiple divs, it doesn't work as expected.

Here is an example of what I tried:

function myFunction() {
  var x = document.getElementById("myDIV");
  var y = document.getElementById("myDIV2");

  if (x.style.display === "none") {
    x.style.display = "block";
  } else if (y.style.display === "none") {
    y.style.display = "block";
  } else {
    console.log("It worked!");
  }
}

I have created a couple of CodePens to demonstrate these snippets:

I would be grateful for any assistance. Thank you!

Answer №1

Let's go step by step in the initial myFunction. This approach will be reliable since it involves a straightforward decision process - "is x set to display: none? if yes, do X; otherwise, do Y." This mechanism operates on binary logic and covers all scenarios effectively as it simply toggles the style.display property. However, as you introduce more complex conditions and factors, the situation may become trickier and require a more careful formulation of your strategy.

The desired logic essentially states that if X is hidden, reveal it; if y is hidden AND x is visible, show it; lastly, if X, Y, and Z have specific visibility combinations, show Z. You can make this logic more readable by creating concise helper functions like isHidden(), isVisible(), and show():

UPDATE: FZs brought up an important point regarding classes not being considered in this rationale. To address this, we can incorporate an additional condition checking for the presence of the "hidden" class using classList within the isHidden() function.

// helper functions
let isHidden = (el) => el.style.display == "none" || el.classList.contains('hidden'),
    isVisible = (el) => !isHidden(el),
    show = (el) => el.style.display = "block";

// DOM elements
let x = document.getElementById("div-x"),
    y = document.getElementById("div-y"),
    z = document.getElementById("div-z");

// click event handler
let handleClick = () => {

  if (isHidden(x))
    show(x);

  else if (isHidden(y) && isVisible(x))
    show(y);

  else if (isHidden(z) && isVisible(y) && isVisible(x))
    show(z);

  else console.log("Success!");
  
}

document.getElementById('btn').addEventListener('click', handleClick);
<div id="div-x" style="display:none">X</div>
<div id="div-y" style="display:none">Y</div>
<div id="div-z" style="display:none">Z</div>

<button id="btn">Click Here!</button>

Answer №2

When you use elem.style, it retrieves the inline style (style="/* styles */") of the element elem.

In the case of #myDiv and #myDiv2, they only have styles applied by stylesheets, so when you check x.style.display, it will return undefined instead of "none".

A solution is to toggle a .hidden class on the elements:

function myFunction() {
  var x = document.getElementById("myDIV");
  var y = document.getElementById("myDIV2");

  if (x.classList.contains("hidden")) {
    x.classList.remove("hidden");
  } else if (y.classList.contains("hidden")) {
    y.classList.remove("hidden");
  } else {
    console.log("It worked!");
  }
}
.hidden{
  display: none;
}
<div id="myDiv" class="hidden"></div>
<div id="myDiv2" class="hidden"></div>

Alternatively, to show them alternately (assuming that was the intention):

function myFunction() {
  var x = document.getElementById("myDIV");
  var y = document.getElementById("myDIV2");
  x.classList.toggle("hidden")
  y.classList.toggle("hidden")
}
.hidden{
  display: none;
}
<div id="myDiv"></div>
<div id="myDiv2" class="hidden"></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

Concealing inactive select choices on Internet Explorer versions greater than 11 with the help of AngularJS

I am having trouble hiding the disabled options in AngularJS specifically for IE. Check out this fiddle for a better idea: https://jsfiddle.net/s723gqo1/1/ While I have CSS code that works for hiding disabled options in Chrome/Firefox, it doesn't see ...

Tips for customizing Bootstrap theme color schemes in a React/Redux application that has been bootstrapped

As a newcomer to REACT, I am facing an issue with changing the theme colors in my freshly bootstrapped react application. I have gone through some solutions suggested by others but none of them seem to work for me. My entry point looks like this: import ...

Bootstrap 4 - The Mystery of 'col-sm-auto' Taking Precedence Over 'col-md-4'

I am currently learning Bootstrap and have encountered a challenge that I can't seem to figure out. Let's take a look at a snippet of the code: <button className=" col-md-4 col-sm-auto btn btn-info ...

Positioning of Cloned Element in jQuery

When a user presses enter while in one of the text input fields provided, I want to add a new empty text input field directly below it - and before the other existing ones. The code snippet below currently adds the new field at the end of the container, bu ...

Show the button's value inside a div when clicked using Javascript and HTML

I am troubleshooting an issue where the value of a button is not displayed in the picked_letters div when the button is clicked, despite having the appropriate code in both the html and javascript files. The structure of the html file is as follows: < ...

What is preventing me from using Selenium/Javascript to control Firefox on Ubuntu 22.04, when I am able to do so with Python?

My python script effectively controls Firefox using Selenium: from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Firefox() driver.get("https://dev.to") driver.find_element(By.CLASS_NAME, "crayons ...

Canvas not displaying image in JavaScript

I have a bird object with a draw function defined, but for some reason, the image is not showing up when called in the render function. Can someone please help me figure out what I'm doing wrong? Thanks in advance. EDIT: Upon further investigation, I ...

CodeIgniter - Utilizing quotes within a form

Consider a scenario where the database has a field named NAME which contains text with both single and double quotes: TEST1 "TEST2" 'TEST3' Now, if you want to edit this value using the following code in a form: <label for="name">Ful ...

Using routerLink for linking to multiple components

Below is the anchor tag provided: <a class="uppercase" routerLink="settings/pressure" routerLinkActive="text-success" (click)="closeModal()" > <div class="pad-btm"> PRESSURE </div> </a> I need to include another route ...

Dynamic Checkbox Functionality in REACT

Motivation: My goal is to generate multiple rows with a variable number of checkboxes that will be managed by a useState hook. Challenge: The page freezes or displays constant loading, with no content visible. There are no console logs, and even the debug ...

The path('/') in $rootScope is not functioning properly

Below is a function called register() that I am working with. <form class="form-auth" ng-submit="register()"> This is how I have defined the register function: $scope.register = function(){ $http.post('/auth/signup', $scope.user).success ...

Top techniques for dynamic loading of HTML and Javascript

I recently implemented a page that uses XHR requests to load a modal box containing a form. The form is comprised of HTML tags along with some JavaScript for validation and submission through another XHR request. Although the functionality works as intend ...

Problem with sending JSON-encoded arrays to an API

After successfully connecting to an API via Postman, I encountered an issue with my AJAX call. The error message returned is: Object {status: false, message: "Add amenities in JSON string"} The problem seems to be related to the amenities parameter, as ...

Merge the chosen values from the drop-down menu into one string

Any suggestions would be greatly appreciated! I am currently developing an application using ASP.NET web forms that consists of a dropdown list and two list boxes. I want these elements to be cloned whenever a specific button is clicked. However, my issue ...

Problem with z-index in VueJS: Child div z-index not functioning within v-dialog

I am facing an issue where I have brought a span to display a loading image inside the v-Dialog of a vuejs screen. The problem is that the v-dialog has a z-index of 220 set as inline style, causing my new span (loading image) to appear below the v-dialog. ...

Are image collections featuring the <img> tag available?

I am working on a website project and I'm looking for a way to create a gallery with a group of photos. The challenge is that I am using Spring MVC, which means regular js and jquery plugins may not work with my 'img src..' tags. Are there a ...

Having trouble customizing the Material UI button in React?

For a recent project, I utilized the older version (v1) of Material UI to ensure compatibility with Node 10.8. In order to implement a round button, I referred to this demo. The round mini button functioned perfectly without any applied themes. <Button ...

React.Children does not reveal the presence of any offspring

I am looking to implement react-native-maps-clustering in my project. However, this library only accepts markers that are direct children of the maps component. An example of how it should be structured: <MapView> <Marker/> <Marker/> ...

The text in the <p> tag will remain the same color

I am encountering an issue with changing the color in the <p> tags within the code snippet below. Specifically, I am trying to change the TITLE text to gray but have been unsuccessful so far. If anyone could provide assistance on this matter, it wou ...

Maintain the selected image

I am working on a program that allows users to choose images and I have given them the pseudo-class. .my_image_class:hover{ border:3px solid blue; -webkit-box-sizing: border-box; } This makes the images bordered in blue when hovered over, giving a "sele ...