Switching between vertical and horizontal div layouts while reorganizing text fields within the top div

function toggleDivs() {
  var container = document.querySelector(".container");
  var top = document.querySelector(".top");
  var bottom = document.querySelector(".bottom");

  if (container.style.flexDirection === "column") {
    container.style.flexDirection = "row";
    top.style.flex = "3";
    bottom.style.flex = "7";
    top.style.height = "auto";
    bottom.style.height = "auto";
  } else {
    container.style.flexDirection = "column";
    top.style.flex = "3";
    bottom.style.flex = "7";
    top.style.height = "100%";
    bottom.style.height = "100%";
  }
}
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.top {
  flex: 3;
  background-color: blue;
  border: 1px solid black;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
}

.bottom {
  flex: 7;
  background-color: green;
  border: 1px solid black;
}

input[type="checkbox"] {
  height: 0;
  width: 0;
  visibility: hidden;
}

label {
  cursor: pointer;
  text-indent: -9999px;
  width: 50px;
  height: 25px;
  background-color: grey;
  display: block;
  border-radius: 100px;
  position: relative;
}

label:before {
  content: "";
  position: absolute;
  top: 1px;
  left: 1px;
  width: 23px;
  height: 23px;
  background-color: #fff;
  border-radius: 90px;
  transition: 0.3s;
}

input:checked + label:before {
  left: calc(100% - 1px);
  transform: translateX(-100%);
}

.toggle-button {
  margin-top: 10px;
  padding: 10px;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.toggle-button:hover {
  background-color: #3e8e41;
}

input[type="text"] {
  margin-bottom: 10px; /* added this */
}

@media screen and (min-width: 768px) {
  .container {
    flex-direction: row;
  }

  input[type="text"] {
    margin-bottom: 0; /* added this */
  }
}
<input type="checkbox" id="toggle-switch" onclick="toggleDivs()" />
<label for="toggle-switch"></label>

<div class="container">
  <div class="top">
    <input type="text" placeholder="Text box 1" />
    <input type="text" placeholder="Text box 2" />
    <input type="text" placeholder="Text box 3" />
    <input type="text" placeholder="Text box 4" />
    <input type="text" placeholder="Text box 5" />
    <input type="text" placeholder="Text box 6" />
    <input type="text" placeholder="Text box 7" />
    <input type="text" placeholder="Text box 8" />
  </div>
  <div class="bottom"></div>
</div>

In the given code, we can toggle a div using a switch. I want to modify the code so that when the top div is vertical, all textboxes are displayed one below the other. When it's horizontal, the first 4 text boxes should be arranged in a row and then the next 4 text boxes, and so on. Essentially, I want to toggle and rearrange the text boxes simultaneously.

Rearranging and toggling fields using a toggle switch.

Answer №1

When the main container is displayed horizontally, you have the option to adjust the toggleDivs() function:-

    function toggleDivs() {
      var container = document.querySelector(".container");
      var top = document.querySelector(".top");
      var bottom = document.querySelector(".bottom");
    
      if (container.style.flexDirection === "column") {
        container.style.flexDirection = "row";
        top.style.flex = "3";
        bottom.style.flex = "7";
        top.style.height = "auto";
        bottom.style.height = "auto";
        // Remove the textbox-row class for rearrangement
        var textboxRows = document.querySelectorAll(".textbox-row");
        textboxRows.forEach((row) => {
          row.style.display = "flex";
        });
      } else {
        container.style.flexDirection = "column";
        top.style.flex = "3";
        bottom.style.flex = "7";
        top.style.height = "100%";
        bottom.style.height = "100%";
        // Add the textbox-row class to stack textboxes vertically
        var textboxRows = document.querySelectorAll(".textbox-row");
        textboxRows.forEach((row) => {
          row.style.display = "block";
        });
      }
    }
    .container {
      display: flex;
      flex-direction: column;
      height: 100vh;
    }
    
    .top {
      flex: 3;
      background-color: blue;
      border: 1px solid black;
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      justify-content: center;
    }
    
    .bottom {
      flex: 7;
      background-color: green;
      border: 1px solid black;
    }
    
    .textbox-row {
      display: flex; /* Added this */
      flex-wrap: wrap; /* Added this */
    }
    
    .textbox-row input[type="text"] {
      margin: 5px; /* Adjusted this */
    }
    
    input[type="checkbox"] {
      height: 0;
      width: 0;
      visibility: hidden;
    }
    
    label {
      cursor: pointer;
      text-indent: -9999px;
      width: 50px;
      height: 25px;
      background-color: grey;
      display: block;
      border-radius: 100px;
      position: relative;
    }
    
    label:before {
      content: "";
      position: absolute;
      top: 1px;
      left: 1px;
      width: 23px;
      height: 23px;
      background-color: #fff;
      border-radius: 90px;
      transition: 0.3s;
    }
    
    input:checked + label:before {
      left: calc(100% - 1px);
      transform: translateX(-100%);
    }
    
    .toggle-button {
      margin-top: 10px;
      padding: 10px;
      background-color: #4caf50;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }
    
    .toggle-button:hover {
      background-color: #3e8e41;
    }
    
    @media screen and (min-width: 768px) {
      .container {
        flex-direction: row;
      }
    
      .textbox-row {
        display: block; /* Adjusted this */
      }
    
      .textbox-row input[type="text"] {
        margin: 0 5px 0 0; /* Adjusted this */
      }
    
      input[type="text"] {
        margin-bottom: 0;
      }
    }
   <input type="checkbox" id="toggle-switch" onclick="toggleDivs()" />
    <label for="toggle-switch"></label>
    
    <div class="container">
      <div class="top">
        <div class="textbox-row">
          <input type="text" placeholder="Text box 1" />
          <input type="text" placeholder="Text box 2" />
          <input type="text" placeholder="Text box 3" />
          <input type="text" placeholder="Text box 4" />
        </div>
        <div class="textbox-row">
          <input type="text" placeholder="Text box 5" />
          <input type="text" placeholder="Text box 6" />
          <input type="text" placeholder="Text box 7" />
          <input type="text" placeholder="Text box 8" />
        </div>
      </div>
      <div class="bottom"></div>
    </div>

There are two additional div elements with the class "textbox-row" that group the textboxes. When the main container is in horizontal display, these rows will act as flex containers, allowing for flexible arrangement of the textboxes in a row-based layout. If the main container is shown vertically, the "textbox-row" class will be removed, resulting in vertical stacking of the textboxes since they are block elements by default.

Tested Link Available Here:- Codesandbox Code

Answer №2

It seems that utilizing a grid layout would be more suitable for achieving your goal.


After reviewing the feedback, I dedicated an hour to adjusting the JavaScript code to incorporate a class instead of relying on inline styles. The integration of a media query to define the initial grid-template-columns value adds complexity to both the JS and CSS with conditional statements like if..else if..else, the creation of the .row class, and the use of the !important flag.

function toggleColumns() {
  const top = document.getElementById("top");
  console.log(top.outerHTML);

  if (top.classList.contains("rows")) {
    top.classList.toggle("rows");
    top.classList.toggle("columns");
   }
   
  else if (top.classList.contains("columns")) {
    top.classList.toggle("rows");
    top.classList.toggle("columns");
   }
   
  else {
    top.classList.toggle("columns");
  }

}
.container {
  height: 100vh;
  background-color: green;
}

.top {
  display: grid;
  align-items: center;
  justify-content: center;
  background-color: blue;
  border: 1px solid black;
  gap: 1em;
  padding: 1em;
}

.columns {
  grid-template-columns: repeat(4, 1fr) !important;
}

.rows {
  grid-template-columns: auto !important;
}

input[type="checkbox"] {
  height: 0;
  width: 0;
  visibility: hidden;
}

label {
... [CSS properties continue here]
@media screen ... [CSS media query definition continues here]
JAVA SCRIPT AND HTML CODE SECTIONS ARE UNCHANGED FOR CLARITY

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

Attempting to locate an element using Selenium IDE proves to be challenging unless each command is executed individually

Currently, I am utilizing selenium ide for automating my tests. Once I click on a link, a popup window appears with a div containing text. Strangely, I am unable to retrieve the text within the div tag without either double-clicking on it or executing the ...

What steps can I take to direct mobile visitors to the mobile-friendly version of my website?

Looking for a way to automatically redirect users on mobile devices from www.domain.com to the new mobile version at m.domain.com? ...

I am unable to send back my JSON object

I seem to be having trouble returning a JSON object as all I get is an undefined variable. The code below is supposed to fetch a JSON element from an API. It appears to work within the success: function, but when attempting to use that data elsewhere, it ...

The previously set display value remains unchanged when switching CSS files

I'm working on a project where I need to display three separate articles based on the screen size. Article 1 should only be visible when the screen width is less than 600 pixels Article 2 should be visible between 600 and 900 pixels Article 3 shoul ...

Issue with module.exports entry in Webpack configuration causing errors

I've been working on setting up webpack but I've hit a roadblock due to this error message. It seems like there's an issue with the entry configuration. When I try to add it without specifying a path, as shown in the tutorial, I receive the ...

How can I use cookies to make an HTML div disappear when a button is clicked?

I've been attempting to conceal this message in Vue.js, but so far I haven't had any luck. Currently, I am utilizing the js-cookie library. My objective is as follows: HTML <div v-show="closeBox()"> < ...

Is there a way to efficiently manage multiple modules in AngularJS? I've put in a lot of effort, but while one module is functioning properly, the

angular .module('ApplicationOne',[]) .controller('myControllerOne', function($scope){ $scope.name = "Luther"; $scope.fname = "Martin"; $scope.ed = "B.TECH"; }); angular .module('App2&apos ...

Troubleshooting issue with refreshing selectpicker in Bootstrap-select and Vue.js

Incorporating the bootstrap-select plugin (found at ) into a ruby on rails app with Vue.js as the javascript framework has been my latest project. The goal is to have two select options where one selects a category and the other displays all available tea ...

Only JSON objects with a boolean value of true will be returned

I am working on returning JSON objects in JavaScript/TypeScript that have a true boolean value for the "team" property. For example, the JSON data I am using is as follows: { "state": "Texas", "stateId": 1, "team": true }, { "state": "Cali ...

How can I target all ul elements except those contained within a div with a specific class using CSS?

In my global.scss file, I have defined global styles for ul elements as shown below: ul { list-style: none; margin: 0; padding: 0; } However, I am trying to find a way to style all ul elements except those within a specific jodit-wrapper class ...

Tips for showcasing information from the tmdb api by leveraging the value or data obtained from a separate api

I am currently working on a project that involves displaying movie data using the tmdb api. I receive the response from my own api which only includes the id of the tmdb movie. Here is an example of the response: [ { "id": 0, "tit ...

Utilizing ReactStrap: a guide to retrieving the id of the chosen dropDownItem

In my code, I have a dropdownList component with various DropdownItems: <Dropdown isOpen={this.state.dropdownOpen[3]} toggle={() => { this.toggle(3); }} > <DropdownToggle className="my-dropdown" car ...

My JavaScript code is being executed before Chrome Auto-fill

I have successfully created form input elements in Chrome that display a floating label when focused. However, I am encountering an issue when the browser autofills the username and password fields with yellow prefilled text. The JavaScript for the float ...

Locate the element for a button or an image

Having trouble recognizing the object in the image. Looking for guidance on how to identify the Button using ClassName or customized XPATH. <div class="schedule"> <a href="https://link" target="_blank"> <img border="0" alt="Sc ...

What is the process of uploading a video and showcasing it on an HTML page?

I have successfully uploaded images and displayed them on an HTML page. Now, I am looking to do the same for videos. Here is my current code: $('#addPhotosBtn').click(function() { $(this).parents().find('#addPhotosInput').click(); }) ...

Executing a javascript function numerous times

Here are a few examples: <div class="statement">text goes here</div> <div class="response"><input type="text" id="amount1" style="border: 0; color: #f6931f; font-weight: bold;" /></div> <div id="sli ...

Struggling with transferring form input data to a different file using JavaScript, Node.js, React.js, and Next.js

I've been struggling with writing form input to a separate file in JavaScript. I created a demo repo to showcase the issue I'm facing. Check it out here: https://github.com/projectmikey/projectmikey-cant-write-to-api-dir-stackoverflow Locally, t ...

What is the best way to incorporate a smooth transition for an object as it appears on the screen in React?

After configuring my code to display a component in the HTML only if a specific hook is set to true, I encountered an issue with a CSS transition. The problem arises because the 'open' class is triggered at the same time the element becomes true, ...

NodeJS JSON file write function not updating as expected

I'm working on a task that involves reading an existing JSON file, updating the value within it, and then saving it back. However, I've encountered the following error message: node:internal/modules/cjs/loader:944 throw err; ^ Error: Cannot ...

While making changes, I was anticipating a "for-of" loop to be used instead of a "for" loop

There seems to be an issue with TSlint and its disapproval of using the traditional for(i=0; ...) loop. Consider this straightforward code snippet: this.filters['1','2','3'....]; for (let i = 0; i < this.filters.length; i+ ...