hidehawk
hidehawk

Reputation: 81

Combine @media with javascript to set display none/block

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?

Upvotes: 0

Views: 973

Answers (1)

abstractcoder
abstractcoder

Reputation: 376

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.

Upvotes: 1

Related Questions