user3813234
user3813234

Reputation: 1682

Toggled element still displayed after window resize despite media queries

I want my code to do the following: If the screen width is smaller than 651, set a list that is a submenu to display:none; and make the menu toggable.

Here's the code:

HTML:

 <ul id="main_menu">
<li class="mainpoint">
<div class="mainpoint_content" id="some">some</div>
<ul class="submenu_1">
<li class="submenu_point"><a href="">some</a></li>
</ul>
</li>

CSS:

    .submenu_1 {
        display:block;
        padding:3%;
    }

 @media (max-width:650px) {

        .submenu_1 {
            padding:2%;
            display:none;
        }

JS:

$( document ).ready(function() {
        $("#some").click(function(){

            if ($(window).width() < 651) {
                $(this).next().toggle();
            }

        });

        $(window).resize(function() {
                if ($(this).width() > 651) {
                    $(".submenu_1").show();
                }               
        });

});

Works fine except for one point:

When the screen width is less than 650 and I toggle the menu so that the submenu is displayed and then I resize the screen to more than 651, this toggled submenu is still display (which is fine). However, when I then resize to less than 650 again, the menu is still displayed, altough according to my media query, it should not be displayed. Does the toggle take precedence over the media query here?

Upvotes: 1

Views: 370

Answers (2)

Benjamin
Benjamin

Reputation: 1070

@Barmar is correct above about the inline styles added by hide(), but his solution breaks your javascript. You should add an else block to your JS to show the submenu above 651 px, eg:

else { $(".submenu_1").hide(); }

http://jsfiddle.net/3zgs04x8/

Incidentally, you have a 1px gap between the two queries-- more than 651, less than 651-- so if the screen is 651 px, it messes up. Maybe that's not a big deal, but still, you should account for it (as I have in my example).

Upvotes: 1

Barmar
Barmar

Reputation: 781141

jQuery sets inline style on the object, that takes precedence over the stylesheet. You can put !important in the stylesheet to make it take precedence.

@media (max-width:650px) {

    .submenu_1 {
        padding:2%;
        display:none !important;
    }

Upvotes: 0

Related Questions