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

What is the reason behind jshint issuing an alert specifically for the lastSelectedRow being

Upon pasting the code below into jshint.com, an error is generated: Read only in reference to line: lastSelectedRow = 1; I am curious as to why this error occurs and how it can be remedied. Interestingly, jslint does not return this error. /*global la ...

Tips for achieving seamless scrolling with the combination of javascript and css

Looking for a solution to achieve smooth scrolling on an HTML page without using the #id_name to scroll to a specific div. Instead, I want to scroll to a particular point, such as having a button that scrolls down the webpage smoothly by 250px when press ...

Creating a layered image by drawing a shape over a photo in Ionic using canvas

While there are plenty of examples demonstrating how to draw on a canvas, my specific problem involves loading a photo into memory, adding a shape to exact coordinates over the photo, and then drawing/scaling the photo onto a canvas. I'm unsure of whe ...

Having trouble obtaining the serialized Array from a Kendo UI Form

I am working on a basic form that consists of one input field and a button. Whenever the button is clicked, I attempt to retrieve the form data using the following code: var fData = $("#test").serializeArray(); Unfortunately, I am facing an issue where I ...

The issue with Open Sans and sans-serif fonts not rendering properly in all web browsers

I am having trouble with websites that use the Open Sans font appearing with a strange handwriting style. I'm not sure where this issue is originating from. Here are some things I have tried: Using In-Private browsing Disabling all extensions Testin ...

What is the most effective way to identify mobile browsers using javascript/jquery?

As I develop a website, I am incorporating image preloading using JavaScript. However, I want to ensure that the preload_images() function is not called for users on slow bandwidth connections. In my experience, the main demographic with slow internet spe ...

Rejuvenate your Bootstrap Accordion with these Settings

Using bootstrap documentation, I have implemented an accordion in my web application with the following code: <div class="accordion" id="accordion2"> <div class="accordion-group"> <div class="accordion-heading"> <a class=" ...

Tips for arranging five images side-by-side in a row

I have a collection of 5 images: Image 1: Image 2: Image 3: Image 4: Image 5: The dimensions of each image are as follows: Image 1: 70x40 Image 2: 80x42 Image 3: 90x44 Image 4: 100x46 Image 5: 120x48 I would like to arrange these images ...

Arrange elements with Material-UI's Grid system

Check out my codesandbox example (here) showcasing how I have set up my current app with Material-UI grid. I have 5 components that need to be positioned in a specific way for different screen sizes. For screens sized lg and above, I want the components t ...

Uploading Blobs using JavaScript and FormData

Currently, I'm encountering an issue with uploading a blob generated in JavaScript to my server. The main concept involves a user uploading an image, which is then center cropped and downsampled using JavaScript before being transmitted. Although the ...

I am interested in monitoring for any alterations to the @input Object

I've been attempting to detect any changes on the 'draft' Object within the parent component, however ngOnChange() does not seem to be triggering. I have included my code below, but it doesn't even reach the debugger: @Input() draft: ...

Process called gulp useref eliminates certain files from the pipeline

Is there a way to exclude the gulp.src file from output? I am aiming to bundle only JavaScript and output .js files, not HTML. The following blocks in base.html are utilized for bundling JavaScript with gulp-useref: <!-- build:js app.core.js --> &l ...

Guide to using Ajax to send a form and receive text in response

Check out my code on Fiddle: $("form.signupform").submit(function(e) { e.preventDefault(); var data = $(this).serialize(); var url = $(this).attr("action"); var form = $(this); // Added this line for reference $.post(url, data, function(data) { $(for ...

Running a node.js project on the client side without using npm for deployment

Looking for a solution to efficiently deploy my nodejs project with frequent updates. The site does not have npm available, so I have to package the node_modules every time, which results in a large file size (80MB) that takes a long time to send via ftp t ...

Can $.ajax be used as a replacement for $(document).ready(function()?

After conducting an extensive search, I am still unable to find a clear answer to my assumption. The code I used is as follows: <?php session_start(); if (isset($_SESSION['valid_user']) && $_SESSION['from']==1) { ?> ...

Using ng-include destroys the styling of the dropdown menu in a bootstrap ul li format

Greetings! I am attempting to replicate the following code snippet that creates a basic dropdown menu using bootstrap: <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="fal ...

Ways to activate an event based on the dimensions (width/height) of

Exploring ways to implement an if statement based on specific width/height values using this code example. Check out the code snippet here My approach: <p id="confirmation">Try again!</p> <script> if (new dynamicSize.width() < ...

What is the reason behind the occurrence of an error when attempting to iterate through an array of objects within my react.js component?

Here is an example of some code: class Stepper extends Component { state ={ quiz_data: [ patient_data: [ {name: "A", age: "1"}, {name: "B", age: & ...

What is preventing the click function on a dynamically created button from being executed in jQuery?

Take a look at this jsFiddle where I illustrate my issue. Whenever I click on the "Add an ingredient" button, the button click event is triggered. My issue arises when I click on the "Create a subtitle" button because it dynamically creates "Add an ingredi ...

The 8 x 8 grid I am constructing is functional, however, the issue lies in the fact that the first line only begins with a single # symbol

I am attempting to create an 8 x 8 grid. It's coming together, but the issue is that the first line only starts with one # sign. function print(msg) { console.log(msg); return msg; } let result = ""; for(let i=1; i<=8; i++) { result += ...