1

I'm trying to make a sidebar menu to achieve a responsive design.

I have a container div #wrapper for the page and a sidebar div for the menu #sidebar-wrapper.

On desktop view when screen width > 768px both wrappers are shown, and when browser's width <= 768px the sidebar disappears.

It worked with me with CSS media queries, but after I added a jquery function to toggle showing/hiding the sidebar by a button, the CSS media queries stopped working after the first click.

Why did that happen, and how to get both of them to work?

JQUERY

var wrapper = $("#wrapper");
var sidebar = $("#sidebar-wrapper");

$("#btn-toggle").click(function(e) {
    e.preventDefault();
    collapse();
});

function collapse(){
    if(sidebar.css("left") == "0px")
    {
        sidebar.css("left","220px");
        wrapper.css("margin-left","220px");
    }
    else
    {
        sidebar.css("left","0px");
        wrapper.css("margin-left","0px");
    }
}

CSS (I'm using LESS here)

#wrapper{ 
   .
   .
   margin-left: 220px;  /* for left sidebar */
   @media only screen and (max-width : 768px){
      margin-left: 0;
   }
}
#sidebar-wrapper {
    .
    .
    left: 220px;
    @media only screen and (max-width : 768px){  
        left: 0;    
    }
}

1 Answer 1

2

When you use jQuery's css() method, it sets the DOM element's style property, which is more specific (has higher priority) than the stylesheet. You might want to create classes with predefined style and toggle those classes on the given elements. For example:

function collapse() {
    sidebar.toggleClass('collapsed');
    wrapper.toggleClass('collapsed');
}

The above will work provided that you have the following in your CSS:

#wrapper.collapsed {
    margin-left: 0;
}
#sidebar-wrapper.collapsed {
    left: 0;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.