Search code examples
javascriptjquerycsshidesidebar

Hiding the Sidebar - marginRight / display CSS bug with Javascript


I want to remove the sidebar when the window is resized below a certain width. And then show it again when the window is expanded.

Html:

<style type="text/css">
    #sidebar{
       width:290px;
       float:right;
       /*...*/
    }
    #header{
       margin-right:290px;
       /*...*/
    }
    #navigation{
       margin-right:290px;
       /*...*/
    }
    #page{
       margin-right:290px;
       /*...*/
    }
</style>
<div id="wrapper">
    <div id="sidebar">
        ...
    </div>
    <div id="header">
        ...
    </div>
    <div id="navigation">
        ...
    </div>
    <div id="page">
        ...
    </div>
</div>

Javascript:

<script type="text/javascript"><!--
function sbar_check(){

    var page = $("#page");
    var header = $("#header");
    var navigation = $("#navigation");
    var sidebar = document.getElementById("sidebar");

    //get width of page
    var pagew = page.width();

    if(pagew < 451) {

        //hide
        sidebar.style.display = 'none';

        header.css('marginRight',   '0');
        navigation.css('marginRight',   '0');
        /*
        //error
        page.css('marginRight',     '0');
        */

    } else {

        //show
/*
            header.css('marginRight',   '290');
            navigation.css('marginRight',   '290');
            page.css('marginRight',     '290');
*/

            sidebar.style.display = 'block';
    }

}

//initial sidebar check
$().ready(function(){
    sbar_check();
});
//sidebar check on resize
window.onresize = function(event){
    sbar_check();
};
//--></script>

The line that causes the unexpected behavior is marked with //error. If I leave this line uncommented, both the header and the navigation container expand and the sidebar gets removed. But if I uncomment the line, the sidebar is NOT removed.

I have no explanation for this behavior.


Solution

  • A much cleaner way to do this is to use media queries.

    @media (max-width: 451px) { /*when the screen is less than 451px wide*/
        #sidebar {
            display: none; /*hide the sidebar*/
        }
        /*more CSS to change margins, etc...*/
    }