Search code examples
jquerywidthtogglecontainersforum

Toggle width of a container using jQuery


I am working on a theme for MyBB forum software. I want to add a feature where the width is expanded from fixed 1000px of the container to a fluid width 85% and viceversa ith slow animation using jQuery. I want to have a toggle button which says expand - shrink buttons. The container also should support cookies so when user reloads the page , it would be of same width he chose. I tried many solutions from Stackoverflow and over web but in vain. Help is appreciated. Thanks in advance, regards

Here is the code :

Hello i figured it out .... the jquery toggle , but i want to add cookie to it. here is the code

$(document).ready( function(){
$('#toggle-button').click( function() {
var toggleWidth = $("#container").width() == 960 ? "85%" : "960px";
$('#container, .wrap').animate({ width: toggleWidth });
});
});

Thanks :)


Solution

  • Following is the code as per your requirement so try this code:
    HTML

    <div id="container">this is container div</div>
    <div class="wrp">this is wrp div</div>
    <input type="button" value="toggle" id="toggle-button">  
    

    CSS

    #container {
       width:960px;
       background-color: red;
    }
    .wrp {
        width:1000px;
        background-color: green;
    }
    

    JS

    $(document).ready(function () {
        var setWidth = $.cookie("width");
        if (typeof setWidth !== "undefined" && setWidth == "85%") {
            $('#container,.wrp').width(setWidth); // 85% width set using cookie
        } else if (typeof setWidth !== "undefined" && setWidth == "960px") {
            $('#container,.wrp').width(setWidth); // 960px,1000px(for wrp) width set using cookie
        }
        $('#toggle-button').click(function () {
            var toggleWidth = $("#container").width() == 960 ? "85%" : "960px";
    
            $('#container, .wrp').animate({
                width: toggleWidth
            });
            $.cookie('width', toggleWidth);
        });
    });  
    

    JSFIDDLE DEMO

    Note: you have to include jquery.cookie.min.js into your file for cookie to get work