Toggle button to expand/collapse divs

Issue

I have two divs next to each other and would like to use the toggle function to collapse one div (Sidebar) horizontally while expanding the other (Map) to take full width of the former. I would then need the toggle to bring back both divs to their original widths/positions. I can get it to do the first operation but I have no clue on how to do the reverse. See Fiddle:

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

Solution

Try this

HTML

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

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')
                }
            });
        });

DEMO

Answered By – Sridhar R

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published