Tips for Making a Div 100% Width While Hiding Another Div Using jQuery

I am looking for a solution to adjust the width of the blue div to 100% when hiding the red div. Can anyone help with this? Here is my JavaScript code

  <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function() {
            $("#button").toggle(function() {
                $(this).text('Show Content');
            }, function() {
                $(this).text('Hide Content');
            }).click(function(){
                $("#red").slideToggle("slow");
            });
        });
        </script>

My style

<style>
        #red {

            width: 50%;
            border: 5px solid red;
            float: left
        }
        .blue {
            float: left;
            border: 5px solid #00F;
        }
        </style>

And here is my HTML code

<a href="#" id="button" class="button_style">Hide content</a> <br/>
<div id="red">Content</div>
<div class="blue">&nbsp;</div>

Answer №1

The version of toggle you are using is outdated: 1.8, no longer supported as of 1.9

Consider using the following statement instead:

$("#red").next(".blue").css("width","100%");

Alternatively, you can add an extra class and utilize .toggleClass("wide"); where .wide specifies the desired width.

Below is my recommendation to eliminate the deprecated toggle function from the button:

View Demo

$(function() {
   $("#button").click(function(){
       var $red = $("#red"),
           hiding=$red.is(":visible"), 
           text = hiding?'Show Content':'Hide Content';
       $(this).text(text);
       $red.slideToggle("slow");
       $red.next(".blue").toggleClass("wide");
  });
});

You may want to experiment with animations for a different effect:

Live Animation Demo

$(function() {
   $("#button").click(function(){
       var $red = $("#red"),
           $blue=$("#red").next(".blue"),
           hiding=!$red.hasClass("wide"), 
           text = hiding?'Show Content':'Hide Content';
       $(this).text(text);
       $red.animate({width:(hiding?0:100)+'%'},2000);
       $blue.animate({width:(hiding?100:0)+'%'},2000);
       $red.toggleClass("wide");
   });
});

Answer №2

Consider applying a style that sets the width to 100%.

JavaScript :

$("#blue").slideUp("fast",function(){
    $('.green').toggleClass('expandedWidth')
});

CSS :

.expandedWidth{
    width:100%;
}

See It in Action

Source : jQuery toggleClass() Documentation

Answer №3

Adjust the width of a div based on the text inside it

Give this a shot:

$(document).ready(function () {
    $("#button").toggle(function () {
        $(this).text('Show Content');
        $('.blue').css('width', '100%');
    }, function () {
        $(this).text('Hide Content');
        $('.blue').css('width', 'auto');
    }).click(function () {
        $("#red").slideToggle("slow");
    });
});

DEMO

Answer №4

JavaScript :

$(document).ready(function() {
        $("#button").toggle(function() {
            $(this).text('Display Content');
            $("#red").next(".blue").css("width","100%");
        }, function() {
            $(this).text('Hide Content');
            $("#red").next(".blue").css("width","46%");
        }).click(function(){
            $("#red").slideToggle("slow");
        });
    });

Cascading Style Sheets (CSS) :

#red {

        width: 50%;
        border: 5px solid red;
        float: left
    }
    .blue {
        float: right;
        border: 5px solid #00F;
        width: 46%;
    }

HTML:

<a href="#" id="button" class="button_style">Show content</a> <br/>
    <div id="red">Content</div>
    <div class="blue">&nbsp;</div>

I believe this fulfills your requirements.

Check out the Demo here

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 best way to include two additional columns next to the sidebar?

I'm having trouble adding another two-column section next to the sidebar. Is there anyone who can help me out? <!-- -------------Navigation Bar------------- --> <div class="sidebar"> <a class="active" href="#home">Home</a ...

Is Polymer more of a comprehensive framework compared to just a library? What is the best way to implement web components in a modular fashion

Web components aim to modularize the web, independent of any specific framework being used. The Polymer project offers the ability to create web components without being tied to a particular framework, meaning they should be compatible with any framework. ...

Scale up each image with the use of Java script

I have a main container with three different sub-containers, each containing an image and text. I want to achieve the effect of zooming in on the image of the specific sub-container when hovering over it. Currently, when I hover over any sub-container, all ...

Message toggle not functioning in custom method of jQuery Validate plugin

Here is a custom rule that I have implemented: jQuery.validator.addMethod("onespecial", function(value, element){ var pattern = /^(?=.{6,})(?=.*[a-z])(?=.*[0-9])|(?=.*[!@#$%^&*()-+=]).*$/; return (pattern.test(value)); }, "Your ...

Totally clueless when it comes to JSON

After diving into tutorials on JSON, the structure and syntax are finally clicking for me. However, I'm currently working on a project that requires a GET, and it seems like JSON could help with this. I've come across comparisons of JSON and AJA ...

Guidance on implementing turn.js in your Ionic 2 project

I used to have an Ionic v1 project with turn.js, but now I've upgraded to Ionic v2. However, I'm facing issues when trying to import turn.js along with jQuery. angular.module('albumController', []) .directive('flipbook', fun ...

When hovering over a single list item, only the top border will be displayed without affecting the

Check out the live link provided below: I am attempting to add a border and later an arrow in the middle on hover in the menu. However, the current code places a border over the entire menu, with individual list items on top of that. #menu ul li { margin ...

How can I retrieve the width of a responsive React element during its initial rendering phase?

In my React project, there is a component called ResultList which is used to display products in a gallery format. The challenge I'm facing is determining the appropriate number of products to show per row based on the available width for the ResultL ...

What is the best way to toggle the visibility of fields on a modal in a Ruby on Rails

I am working on an application that utilizes Rails 4.1 and Ruby 2.1.2. The show.html.erb view for the Assignment Model in this application is as follows: <h1><%= "#{'Source URL'}"%> <div class="source-url"><%= @assignment.so ...

Utilizing Z-Index on DropDownTree has no impact on its display

Whenever the DropDownTree is placed near other expanding controls such as standard date pickers, it causes those controls to appear behind the DropDownTree. I have attempted various solutions including using inline style, setting z-index for .RadDropDownTr ...

Attempting to align a FieldSet in the middle of the page

Having trouble aligning a field set within a div. The first two elements are centered right next to each other, but the third one is justified left and I'm struggling to center it within the div. JSP <tr> <th> <span onclick="toggleDiv ...

Graphics distorting on android devices when implementing createjs and canvas technology

I have a question regarding the performance of my game that I'm developing to work on both desktop browsers and mobile devices. Using HTML5 and CreateJs, most of the game is being drawn on a canvas element. While everything runs smoothly on a standar ...

What specific CSS selector should be targeted in order to modify the appearance of this button?

I'm attempting to alter the appearance of a button within my Wordpress site, but I've hit a roadblock in identifying the correct element to modify. So far, I've tried targeting: .input#chained-quiz-action-1, however, the button stubbornly re ...

Struggling to make the toggle button appear on the bootstrap navbar when shrinking the resolution

Everything seems to be working well with the navbar initially, but when resizing the screen to a smaller resolution, all the navigation items disappear and the "hamburger icon" fails to appear. <nav class="navbar navbar-custom navbar-expand-md fi ...

How to Use Jquery to Perform Subtraction on Elements

Hello everyone! I am currently working on creating a nutrition label similar to this one: Example I have set up my database and now I am focusing on getting it to work with one element before moving on to the rest. Here is what my database looks like: in ...

I attempted to utilize certain CSS properties, only to find that they were not being applied due to conflicts with Bootstrap's own CSS. I'm unsure what I should do next

click here for image .container, .container-fluid, .container-lg, .container-md, .container-sm, .container-xl, .container-xxl { --bs-gutter-x: 1.5rem; --bs-gutter-y: 0; width: 100%; **padding-right: calc(var(--bs-gutter-x) * .5);** **pa ...

Display badges alongside Bootstrap pills while hiding any non-badge text when viewing on a mobile device

I'm working on a multi-step form using angular UI router and have a bootstrap nav at the top. However, on mobile-sized screens, each pill in the nav occupies its own line due to the amount of text. I want the non-badge content of each pill to disappea ...

Troubleshooting problem with URL mapping in Javascript Ajax on IIS

Currently, I am developing an MVC application where I am utilizing JavaScript to invoke server action methods. When working on my local project, I specify the URL as a string in the format "/ActionMethod/Controller". Below is the snippet of my JavaScript A ...

What is the most efficient method of organizing form components together?

After exploring numerous tutorials, I have yet to discover the ideal solution for properly marking up a form that contains logical groupings of elements such as labels, controls (input or select), and previous values - essentially single fields. My prefer ...

The webpage lacked the functionality of smooth scrolling

I created a website which you can view here. Check out the code below: <div id="mainDiv" class="container"> <div id="header"> <div class="plc"> <h1><a href="#"></a></h1> ...