0

I have a div panel somewhere on my page that should be hidden when the window size gets too small.

Works fine using this css:

#panel {display: block; }

@media (max-width: 1000px) {
   #panel { display: none; }
}

There is another rule that displays a button which should make the #panel visible onclick.

#panel {display: block; }
#button {display: none; }
@media (max-width: 1000px) {
   #panel { display: none; }
   #button {display: block; }
}

The javascript looks like this:

 $("#button").click(function() { $("#panel").toggle(); });

there are some other rules as well that make the panel appear friendlier... no need to explain this. The problem is: when you once clicked the button and changed the display state of the panel to on and off again. That means the display:none property was set by the javascript, the panel will not be displayed again when you resize the window > 1000px. The default style of the panel will not be applied, even if you create some rule like @media(min-width: 1000px).. the js seems to have priority.. so what is the best way to combine media queries and js?

2
  • you may be worrying about something that will likely never happen. People don't go around resizing their browsers unless they are demo'ing a responsive site. Commented May 16, 2014 at 14:47
  • hehe.. nice one.. probably your are right.. but if someone does it the page will break completly. and this should better not happen.. Commented May 16, 2014 at 14:56

1 Answer 1

1

You could add an event listener for the window resize event that forces the panel to be visible when the window is resized to a width > 1000px.

$(window).on('resize', function() {
    if (window.innerWidth > 1000) {
        $("#panel").show();
    }
});

As soon as toggle, show, or hide are called that will trump whatever is in the CSS.

Sign up to request clarification or add additional context in comments.

2 Comments

yes.. thanks. that's what i am doing at the moment, because i dont have a better solution.. but in that case you dont need the @media query at all, because you can also hide the #panel in the else-part : ) i was just wondering how you can be sure about the state of the objects.. something may break totally if you use both types..
toggle, show, and hide modify the element's style tag, so it will always override what is in the CSS. I think it makes sense to use a combination of CSS and javascript in this case.

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.