When one div is hidden, the width of another div will automatically adjust to 100%

Is there a way to make #leftdiv expand to 100% when #rightdiv is hidden, and have both <div>s positioned next to each other when a button is clicked?

I have successfully aligned both <div>s next to each other upon button click, but I would like #leftdiv to occupy 100% width when #rightdiv is invisible.

function toggleSideBar() {
    var div = document.getElementById('rightdiv');
    if (div.style.display !== 'none') {
        div.style.display = 'none';
    } else {
        div.style.display = 'block';
    }
};
#leftdiv
{
   border: solid medium thick;
   float: left;
   display: inline-block;
   background-color: #ffc;
   /*border: 1px solid red;*/
}

#rightdiv
{
   width: 50%;
   border: solid medium thick;
   background-color: #ffa;
   display: none;
   float:right;
}
<input type="button" id="btn" value="toggle" onclick="toggleSideBar()" />
    <div id="main-content">
        <div id="leftdiv">selectable</div>
        <div id="rightdiv">right panel</div>
    </div>`

Answer №1

One way to tackle this design is by utilizing flexbox:

HTML

<input type="button" id="btn" value="toggle" onclick="toggleSideBar()" />
<div id="main-content">
  <div id="leftdiv">selectable</div>
  <div id="rightdiv">right panel</div>
</div>

CSS

#main-content {
  display: flex;
  flex-flow: row nowrap;
}

#leftdiv {
  background-color: #ffc;
  flex: 1 1 auto;
  border: 1px solid red;
}

#rightdiv {
  flex: 1 1 auto;
  background-color: #ffa;
  display: none;
  border: 1px solid green;
}

JS

function toggleSideBar() {  
    var div = document.getElementById('rightdiv');

    if (div.style.display !== 'none') {
        div.style.display = 'none';
    } else {
        div.style.display = 'block';
    }
};

The reason why your previous attempt didn't yield the desired outcome is due to the utilization of float. Using float causes an element to only take up space based on its content. To resolve this, a width:100% would need to be applied to the left container when using float. Furthermore, to dynamically switch between 50% and 100% width, the style needs to be toggled in the function.

Utilizing flexbox eliminates the need for these adjustments, as children are automatically arranged in the specified direction, in this case, row. Setting flex: 1 1 auto; for both containers allows for equal growth and shrinkage to fill available space. (Using flex: 1 0 auto; would achieve the same result in this scenario.)

Answer №2

To achieve the desired effect without the need for JavaScript manipulation of the width, you can style the elements as table-cell:

function toggleSideBar() {
    var div = document.getElementById('rightdiv');
if (div.style.display !== 'none') {
    div.style.display = 'none';
} else {
div.style.display = 'table-cell';
}
};
#leftdiv {
border: solid medium thick;
    width: auto;
display: table-cell;
    background-color: #ffc;
}

#rightdiv {
    width: 50%;
    border: solid medium thick;
    background-color: #ffa;
    display: none;
}

#main-content {
    display:table;
    width: 100%;
}
<input type="button" id="btn" value="toggle" onclick="toggleSideBar()" />
<div id="main-content">
    <div id="leftdiv">selectable</div>
    <div id="rightdiv">right panel</div>
</div>`

Answer №3

Here is an example of how this can be achieved:

http://jsfiddle.net/nw8Ln6ha/18/

<input type="button" id="btn" value="toggle" onclick="toggleSideBar()" />
<div id="main-content">
   <div id="leftdiv">selectable</div>
   <div id="rightdiv">right panel</div>
</div>
<script>
  function toggleSideBar() {

    var r_div = document.getElementById('rightdiv');
    var l_div = document.getElementById('leftdiv');
    if (r_div.style.display !== 'none') {
        r_div.style.display = 'none';
        l_div.setAttribute('style', '');
    }
    else {
        r_div.style.display = 'block';
        l_div.setAttribute('style', '30%');
    }

};
</script>

css

#leftdiv
{

  border: solid medium thick;
  float: left;
  display: inline-block;
  background-color: #ffc;
 /*border: 1px solid red;*/
  width: 100%;

}

#rightdiv
{

 width: 50%;
 border: solid medium thick;
 background-color: #ffa;
 display: block;
 float:right;

}

Answer №4

Kindly review the code snippet provided below:

HTML

<input type="button" id="btn" value="toggle" onclick="toggleSideBar()" />
<div id="main-content">
    <div id="leftdiv">selectable</div>
    <div id="rightdiv">right panel</div>
</div>

CSS

#leftdiv
{
   border: solid medium thick;
   float: left;
   display: inline-block;
   background-color: #ffc;
   height:50px;
   width: 50%;
   /*border: 1px solid red;*/
}

#rightdiv
{
   width: 50%;
   height:50px;
   border: solid medium thick;
   background-color: #ffa;
   display: none;
   float:right;
}

JS

function toggleSideBar() {
    debugger;
    var div = document.getElementById('rightdiv');
    if (div.style.display !== 'none') {
        div.style.display = 'none';
   document.getElementById('leftdiv').style.width = '100%';
    }
    else {
        div.style.display = 'block';
 document.getElementById('leftdiv').style.width = '';
    }

};

You may also investigate a live demonstration of this code on :

http://jsfiddle.net/zjea48bu/19/

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

I created a thorough duplicate that successfully addressed an issue with a table

Currently, I am facing an issue with the material-table library as it automatically adds a new element called tableData to my object when I update it using Patch in my code and API. To resolve this problem, I tried implementing both a conventional and cust ...

Using regex in Javascript to find and match an ID within a string

JavaScript: var data='<div id="hai">this is div</div>'; I am looking to retrieve only the ID "hai" using a regular expression in JavaScript. The expected output should be, var id = regularexpression(data); The variable id should n ...

Uniquely combining multiple jQuery appendTo functions into a single call

Is it possible to optimize this code snippet: jQuery('<img />',{alt:"Logo",src:"img/logo.jpg"}).appendTo("#scrittacentro"); jQuery('<h1 />',{text:'THE LCARS COMPUTER NETWORK',class:'cLightOrange lcars'}) ...

What's the process for including delivery charges in Stripe transactions?

I am facing an issue with Stripe where I am unable to incorporate delivery fees into my transactions. How can I successfully integrate this feature? let line_items = []; for (let productId of uniqIds) { const quantity = productsIds.filter(id => id == ...

Tips for declaring the project npm registry within the package.json configuration file

Currently, I am juggling multiple projects simultaneously and facing the issue of each project having a different node module registry. For instance, project A sources its modules from http://registroy.foo.com, while project B pulls modules from http://re ...

What steps should I take to solve this wheel-related issue in my Vue 3 application?

I have been developing a Single Page Application (SPA) using Vue 3, TypeScript, and The Movie Database (TMDB). Currently, I am tackling the implementation of a search feature and I've encountered a bug. The "search-box" component is located in src&b ...

Performing self-addition on a randomly generated number using JavaScript

I have implemented a feature in jQuery where I generate a random number on click. Below is the code snippet that showcases this functionality. Now, I am looking for a method to add each newly generated random number to the previous one and store the total ...

Struggling with aligning items vertically in Bootstrap 4?

Despite my experience in programming, I am struggling with CSS and HTML. I am attempting to create a simple "Login Page" for my personal web application. GitHub: https://github.com/n-winspear/cashflow-webapp After trying various solutions suggested in ot ...

Guide to integrating a static page with personalized CSS and JavaScript resources within a Rails project

Currently, I am developing a simple Rails application (using Rails version 4.1) and I am looking to incorporate a static page into it. The static page is structured as follows: | |- index.html |- css folder |-- (various css files) |- js folder |-- (some j ...

The integration of express and cors() is malfunctioning

Currently, I am developing a React application and facing an issue while trying to make an API call to https://itunes.apple.com/search?term=jack+johnson In my project, there is a helper file named requestHelper.js with the following content : import &apo ...

Using JSON in JavaScript to handle the click event of ASP.NET buttons

Here is the code that works well for me. I need to execute two different server-side functions, and they can't run at the same time as I have separated them. Default.aspx/AddCart btnUpdate Click Event The issue I'm facing is that the alert box ...

Creating full-width divs using BootstrapLearn how to easily create full-width div

Bootstrap is being utilized in my current project. I have been creating divs inside columns, but they are not extending to the full width of the columns. Below is a snippet of the code: <!DOCTYPE html> <html lang="en"> <head> ...

In IE8, the :last-child pseudo-class appears to be ineffective

Here is the HTML structure I am working with: <div class="footerMenu"> <ul> <li>Home</li> <li>About</li> <li>Feedback</li> <li>Contact us</li> </ul> ...

Combining my CSS and JS files is causing code issues (works on my Mac, but not on the server)

Currently, I am in the process of merging my CSS and JS files before minifying them with the YUI compressor. My web application functions perfectly when each file is linked individually. Now, I am attempting to combine all the files into one single CSS fi ...

Are your JavaScript scripts causing conflicts?

My bootstrap Carousel was working perfectly fine until I added a script to modify the navigation bars. The original script for the Carousel looked like this: <script> !function ($) { $(function() { $('#myCar ...

Simple method to restrict duration of video uploads using HTML5's capture attribute

I'm working on a website that allows users to take photos and videos with their smartphones. Everything is running smoothly with HTML5 and some javascript, but I want to set a maximum time limit for the videos without requiring users to start recordin ...

Inserting a crisp white divider between items in breadcrumb navigation in the form of arrowheads

I have designed a unique custom breadcrumb with an arrow shape : <ol class="breadcrumb-arrow"> <li class="active"><a href="#">1. Foo<span class="arrow"></span></a> </li> <li ...

List the properties that the arguments object supports

During a NodeJS interview, I was presented with the following question: What properties are supported by the arguments object? a) caller b) callee c) length d) All Upon researching, I discovered that all 3 mentioned properties are supposed to be present ...

Error message in React-router: Cannot read property 'func' of undefined, resulting in an Uncaught TypeError

When attempting to launch my react application, I encountered an error in the browser console: Uncaught TypeError: Cannot read property 'func' of undefined at Object../node_modules/react-router/lib/InternalPropTypes.js (InternalPropTypes.js: ...

Problem with Jquery show/hide feature only resolved after refreshing the page

I built a checkout page that consists of three fieldsets with unique IDs - 1, 2, and 3. I want the page to initially display only fieldset 1 while hiding fieldsets 2 and 3. Here is the jQuery code I used: $(document).ready(function(){ $("#1").show(); ...