Showcase 4 divs in full screen width by toggling their display

Trying to create a page with 4 columns, each set at 25% width and 100% height. The challenge is resizing them when toggled to be hidden or visible.

The goal is for:

  • 4 visible columns = each at 25% wide
  • 3 visible columns = each at 33% wide
  • and so on...

When I toggle the hidden columns to be visible again, they should adjust accordingly. Any suggestions or solutions?

I've included a code snippet below:

$("#button-column-1").click(function() {
  $("#column-1").toggle(1500);
});

$("#button-column-2").click(function() {
  $("#column-2").toggle(1500);
});

$("#button-column-3").click(function() {
  $("#column-3").toggle(1500);
});

$("#button-column-4").click(function() {
  $("#column-4").toggle(1500);
});
.column {
  float: left;
  height: 100vh;
  width: 25%;
  -webkit-box-shadow:inset 0px 0px 0px 1px black;
  -moz-box-shadow:inset 0px 0px 0px 1px black;
  box-shadow:inset 0px 0px 0px 1px black;
}
<html>

  <head> </head>
  
  <body>
    
    <div id="button-container">
      
      <button type="button" id="button-column-1">Column 1</button>
      <button type="button" id="button-column-2">Column 2</button>
      <button type="button" id="button-column-3">Column 3</button>
      <button type="button" id="button-column-4">Column 4</button>
      
    </div>
    
    
  
    <div class="column" id="column-1">
      1
    </div>  
     <div class="column" id="column-2">
      2
    </div> 
     <div class="column" id="column-3">
      3
    </div> 
     <div class="column" id="column-4">
      4
    </div> 
   
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
  </body>
  
</html>

Answer №1

Enhance your layout using the power of flexbox. Simply wrap your columns within a block element, like a section, and apply the following CSS:

/* Define the container for the columns */
#setB {
  display: flex;
  flex-wrap: nowrap;
  justify-content: center;
}
/* Allow the columns to adapt in width based on available space */
.column {
  flex: 1 1 24%; 
  ...

SNIPPET

$("#btn1").click(function() {
  $("#col1").toggle(1500);
});

$("#btn2").click(function() {
  $("#col2").toggle(1500);
});

$("#btn3").click(function() {
  $("#col3").toggle(1500);
});

$("#btn4").click(function() {
  $("#col4").toggle(1500);
});
#setB {
  display: flex;
  flex-wrap: nowrap;
  justify-content: center;
}
.column {
  flex: 1 1 24%;
  height: 100vh;
  width: 25%;
  -webkit-box-shadow: inset 0px 0px 0px 1px black;
  -moz-box-shadow: inset 0px 0px 0px 1px black;
  box-shadow: inset 0px 0px 0px 1px black;
}
<html>

<head></head>

<body>

  <fieldset id="setA">

    <button id="btn1">Column 1</button>
    <button id="btn2">Column 2</button>
    <button id="btn3">Column 3</button>
    <button id="btn4">Column 4</button>

  </fieldset>


  <section id='setB'>
    <div class="column" id="col1">
      1
    </div>
    <div class="column" id="col2">
      2
    </div>
    <div class="column" id="col3">
      3
    </div>
    <div class="column" id="col4">
      4
    </div>
  </section>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

</body>

</html>

Answer №2

adjusting CSS width post toggling event

Check out this JSFiddle example

$("#button-column-1").click(function() {
  $("#column-1").toggle(1500, function() {
       columnCalc();
  });
});

$("#button-column-2").click(function() {
  $("#column-2").toggle(1500, function() {
       columnCalc();
  });
});

$("#button-column-3").click(function() {
  $("#column-3").toggle(1500, function() {
       columnCalc();
  });
});

$("#button-column-4").click(function() {
  $("#column-4").toggle(1500, function() {
       columnCalc();
  });
});

function columnCalc () {
    $(".column").css('width', 100/$(".column:visible").length+'%'); 
}

revision

This snippet will adjust the width of the .column to 33%: $(".column").css('width', '33%');

For dynamic adjustments, we need to determine the current number of visible .column elements. This can be achieved by counting them like so: $(".column:visible").length

Therefore, we divide the total block width (100%) by the count of visible .column elements: 100/$(".column:visible").length

Since the CSS property is in percentage format, we concatenate it as follows: 100/$(".column:visible").length+'%')

This results in the final code: $(".column").css('width', 100/$(".column:visible").length+'%');

Remember to ensure calculations are performed after the completion of the animation

.toggle(1500, function() {
       columnCalc();
  });
});

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

Properly segregating data across various instances of JavaScript objects

Until today, I was completely unaware of this issue and now I am eager to discover the most effective way to navigate around it. The problem arises when two distinct objects are instantiated from the same constructor function - they end up sharing the same ...

Discover the perfect method for combining two objects while updating any empty values with a new specified value. Furthermore, in the case where the new value is also

My task involves working with an array of objects where each time I select a value, it gets pushed into the array. My goal is to merge two objects that share the same key "code" and remove any empty values. (4) [{…}, {…}, {…}, {…}] 0: {code: "abc ...

Unable to retrieve translations using language header in axios are not successful

My goal is to create a single-page website with multiple components. I am facing an issue where only one language appears instead of fetching translations from the API for each component. When using Promise.all() in the index page, the translations do not ...

What is the best way to upload images in Vue.js without using base64 formatting?

Is there a way to upload an image file without it being base64 encoded? I currently can only achieve base64 format when trying to upload an image. How can I modify the code to allow for regular file uploads? <script> submitBox = new Vue({ el: "#su ...

Retrieve the truncated text content from the text node using ellipsis

Is there a way to retrieve truncated text from a node using Javascript? Take a look at the code snippet below: console.log(document.getElementById("text1").textContent); // prints "This is a long text" console.log(document.getElementById("text2").text ...

Tips for adding a border to a 3D pie chart in Highcharts

I created a 3D pie chart using the Highchart plugin and wanted to add borders to each portion. I tried adding the following code: borderWidth: 4, borderColor: "red" within the plotOptions: pie: section. However, I noticed that the portions were getting b ...

How can I run JavaScript code written in the Chrome console on standalone Node.js platform

After successfully creating a script that functions when input into the Google Chrome developer console, I now desire to convert it into an executable file. My goal is to open the file and have it log all activity in a separate node.js console window, whil ...

Move the <div></div> element to the bottom of the webpage and center it

My HTML includes a <div>...</div> section that serves as a toolbar. Is there a method to position this section at the bottom of the webpage (document, not viewport) and align it to the center? ...

Setting Kendo grid height to a specific value upon page load

Looking to achieve a fixed height and width for a Kendo grid, regardless of data size. Scrolling should be enabled if data exceeds the fixed dimensions. The issue arises when the page initially loads with data, as the Kendo grid does not adhere to the spe ...

Update the div using AJAX following the form submission

I'm having trouble displaying the loading image before every AJAX response when I submit the form. Currently, the image only shows on the first submission. Here's the code I'm using: $('form.ajax').on('submit', function ...

Facing issues with Jquery object that is producing undefined output when utilizing .text(), .val(), or .html() methods

Created this unique foo using dom selectors in the console: foo [<input type=​"text" maxlength=​"70" id=​"authCreateAcctUsernameInput" name=​"userName" autocomplete=​"off" autocapitalize=​"off" autocorrect=​"off">​] Discovered that ...

Loading local JSON data using Select2 with multiple keys can greatly enhance the functionality

Comparing the select2 examples, it is evident that the "loading remote data" example contains more information in the response json compared to the "loading array data" example. I am interested in knowing if it is feasible to load a local json file with a ...

Is it possible to stop JSON.stringify from invoking the toJSON method?

JSON.stringify provides a way for objects to customize their serialization process by defining a function named toJSON. Here is an excerpt from the MDN documentation: toJSON() behavior If an object being converted to a string has a method called toJSON, ...

"Integrate a URL segment into the primary URL with the help of AngularJS or JavaScript

One interesting case involves a URL path that is structured in the following way. http://localhost:12534/urlpart1/urlpart2?querystring=140 The challenge here is to replace "urlpart2" with "urlpart3" using either javascript or AngularJS. One approach is t ...

Resolving Div Alignment Issues in Internet Explorer with jQuery CSS AddClass and RemoveClass

I've set up an HTML table with a hover highlight feature using jQuery and CSS. Here's how my hover event is structured: $('#' + element.id + ' tr:not(:first,[class="summary_row"])').die('mouseover mouseout').live(&a ...

The functionality of CSSTransition seems to be malfunctioning. Perhaps switching to V2 of react

Can anyone help me troubleshoot my code snippet where I'm attempting to incorporate an animation for Tooltip Nodes? Despite my efforts, the animation does not show up on the screen after mounting. Additionally, the console.log is not triggered on the ...

Is there a way to detect empty strings within JavaScript arrays?

I am trying to determine if an array contains at least one empty element. If any of the elements are empty, I want it to result in false. For example: let myArray = new Array(); myArray[0] = ""; myArray[1] = "hi"; myArray[2] = ""; In this case, both t ...

The YouTube-Search NPM module is producing unexpected outcomes

I recently integrated the youtube-search NPM library with express to fetch the first youtube video based on a song name. app.get("/search", (req, res) => { var search = require("youtube-search"); var SONG = req.query.SONG; var opts = { maxR ...

Adding JSON data to a MySQL column in JSON format with the help of NodeJS

I currently have a MySQL table set up with the following specifications: CREATE TABLE `WorkOrders` ( `workorder_id` int(11) NOT NULL AUTO_INCREMENT, `intertype_id` int(11) NOT NULL, `equipment_id` int(11) NOT NULL, `reason_id` int(11) NOT NULL ...

Flexbox - managing wrapping on legacy devices

Utilizing flexbox, I have successfully designed a 2 column layout with a div at the top spanning both columns for a menu format. While this works flawlessly in Chrome and iOS7, it appears to be ineffective in outdated versions of Safari. In this fiddle, yo ...