Switch button for revealing/ hiding div elements

I am currently working on a project that involves two divs placed next to each other. My goal is to implement the toggle function in order to collapse one div (Sidebar) horizontally while simultaneously expanding the other (Map) to occupy the full width of the former. After achieving this effect, I aim to have another toggle functionality that will revert both divs back to their original widths and positions. Although I have successfully accomplished the first operation, I am facing difficulties in figuring out how to execute the reverse action. A demonstration can be found at this Fiddle.

    $(document).ready(function(){
        $("#toggle").click(function(){
            $("#sidebar").animate({width: 'toggle'});
            $("#map").animate({width: '100%'});     
        });
    });

Answer №1

Here's a suggestion for you to try

Here is the HTML code:

<input type="button" data-name="show" value="Toggle" id="toggle">

This is the Script:

$(document).ready(function () {
            $("#toggle").click(function () {
                if ($(this).data('name') == 'show') {
                    $("#sidebar").animate({
                        width: '0%'
                    }).hide()
                    $("#map").animate({
                        width: '100%'
                    });
                    $(this).data('name', 'hide')
                } else {
                    $("#sidebar").animate({
                        width: '19%'
                    }).show()
                    $("#map").animate({
                        width: '80%'
                    });
                    $(this).data('name', 'show')
                }
            });
        });

You can view a demonstration here at DEMO

Answer №2

Ensure the div width is either set to 100% or 80%.

$(document).ready(function () {
    $("#toggle").click(function () {
        $("#sidebar").animate({
            width: 'toggle'
        });
        var value = $("#map")[0].style.width !== "100%" ? '100%' : '80%';
        $("#map").animate({
            width: value
        });
    });
});

Check out the Working Fiddle here

Answer №3

My typical approach involves using a secondary css class to indicate the current state of the div. For example, I may use a class like collapsed which is toggled or removed when the div expands, allowing for easy detection of user actions.

Check out the updated Fiddle here: http://jsfiddle.net/8wKxY/6/

Here's a sample code snippet:

$(document).ready(function(){
    $("#toggle").click(function(){
        if($(this).hasClass('expanded')){
            $("#sidebar").stop().animate({width: '19%'});
            $("#map").stop().animate({width: '80%'});
            $(this).removeClass('expanded');
        }
        else {
            $("#sidebar").stop().animate({width: '100%'});
            $("#map").stop().animate({width: '100%'});      
            $(this).addClass('expanded');
        }
    });
});

In this example, I've directly attached the control class to the button, but it would be better practice to attach it to a common container for both expandable divs.

It's also important to note that adding an overflow: hidden property to the sidebar ensures it doesn't go under the map when collapsing. In my implementation, I completely hide the sidebar once the animation is complete.

Answer №4

Learn how to utilize jQuery's toggleClass() method.

See a live demo here!

$(document).ready(function(){
  $("#toggle").click(function(){
            $("#sidebar").animate({width: 'toggle'});
            $("#map").toggleClass('fullWidth');     
  });
});

.fullWidth{
    width : 100% !important;
}

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

Looking to conceal an <hr> element using jQuery's slideToggle function and then reveal it when clicked once more

I recently embarked on my journey to learn jQuery. I encountered a challenge with a simple button that triggers the slideToggle function to show/hide a div. Directly above this toggled div, there is an break line which I want to hide when the button is in ...

Hosting provider overhauls entire site, rather than just updating the UpdatePanel

Some assistance would be greatly appreciated as I'm struggling to identify the root cause of my current issue. Perhaps you possess the solution. The situation is this: I have an asp.net website with an AJAX updatePanel that functions perfectly on my ...

Avoiding the use of apostrophes in jQuery or JavaScript

I need to show the text below for the <span> element. What's the best way to handle single quotes in this case? $("#spn_err").text($('#txt1').attr('value')+" is not valid"); The desired message format is 'ZZZ' is ...

Issue with Bootstrap 4 nested tabs retaining active status

I'm having some issues with my nested tabs, both vertical and horizontal, as they are not switching the active states properly and some bugs are arising. body { min-height: 100%; } <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/b ...

Highcharts stretching beyond parent container width in Chrome exclusive

On my webpage, I have multiple charts displayed in individual bordered boxes. However, upon the initial page load, all the charts exceed the width of their parent container. An interesting observation is that if I slightly resize the page, everything adju ...

Impact of Jquery on dropdown menus in forms

Currently, I have a script for validating form information that adds a CSS class of .error (which includes a red border) and applies a shake effect when the input value is less than 1 character. Now, I also need to implement this validation on various sel ...

Tips for ensuring images are mobile-friendly in terms of screen size adaptation

I have implemented a carousel feature for my app by referring to the example provided at https://www.w3schools.com/bootstrap/bootstrap_carousel.asp. To ensure that the carousel displays the example images perfectly on a mobile screen without requiring user ...

What is the method for showcasing an h1 heading and an unordered list link side by

Can you help me align my h1 and ul elements on the same line in my header? I want to have my logo and navigation links next to each other (This extra text is just filler) Below is the code snippet: HTML: <div id="header"> <h1>Logo</h1> ...

What methods does JUMflot use to update points or select items? Interested in adding objects to an array and redrawing them without altering the original item

My goal is to use a button to push a line into an array and have JUMflot redraw those lines without affecting the original line being pushed in. Initially, I attempted this using the following code snippet (the generator ID represents the button and optio ...

Verify the status of the Devexpress aspxhtmlControl using jQuery to determine if it is active or inactive

On my settings page, I have implemented an AspxHtmlEditor that can be enabled or disabled based on saved configurations from another page. To handle this dynamic behavior, I need to identify whether the editor is currently disabled and take appropriate act ...

Elements with a lower z-index do not have text drawn over them

I am currently facing an issue with a hidden list on a page that is crucial for my menu. Despite setting the z-index of different elements, the text inside a specific div only displays to one side which is causing alignment issues. Using display:none is no ...

assigning attributes to web addresses

Is there a way to set a style property for webpages by targeting addresses that contain /index.php/projecten/ instead of specifying each complete address in the code? Currently, I am using the following code: <ul class="subnavlist" style="display: &l ...

Tips and Tricks for Resizing Images within an Angular iframe

Can anyone help me figure out how to make the image content inside my iframe fit perfectly within the frame? I noticed that when displaying a PDF it scales correctly, but when displaying a PNG image it does not scale properly and looks distorted. Any ass ...

Utilizing a div element for creating a clipping mask with CSS

I am facing a challenge with a background image that has been set to background-size:cover; and a series of overlaid divs that I would like to convert into separate clipping masks. I have explored the clip: rect(20px, 20px, 20px, 20px,) feature, but since ...

Uncaught ReferenceError: ajaxUrl is undefined

After pressing a green button on the website , instead of the expected popup image and email confirmation, I receive an error message stating "ajaxUrl is not defined". I have attempted to find a solution to this problem by searching on Google and Stackove ...

"Employing AJAX along with jQuery in .NET often leads to the error message stating, 'The requested resource was not

Could use some guidance on setting up a simple Ajax call in .NET Any suggestions? [WebMethod] public string Greetings() { return "Hello World"; } When I try to access the webmethod through my browser using this URL: I encounter the error: "The r ...

Scrolling horizontally in md-list

I have a list of items where each item can be of varying lengths horizontally: https://i.sstatic.net/ITIQd.png The issue is that long items are getting cut off on the right side. Here's the code snippet I am currently using: <md-list-item ng-repea ...

The .val() and focus() methods are not functioning correctly

I am having an issue with a simple script: when I input a link to an image in the form's INPUT field, it should automatically display a preview of the image: https://example.com/image.jpg However, when I input the same link not by using ctrl+C/ctr ...

I'm wondering, what is the name of this, and how can I recreate it using CSS?

Apologies for the lackluster title, but I'm completely stumped on what to name my creation. I'm looking to put together a list of links (or a menu, without any drop-downs) that has a unique appearance: This example isn't the most attractiv ...

Running out of parenthesis options when using PHP to write JavaScript code

Running out of parentheses can be a common issue when working with PHP and JavaScript. In this case, the problem arises from using the echo function to kick off some Javascript but encountering difficulty due to the necessary parentheses around html() and ...