jQuery: mobile menu remains after click and screen expansion

Hi all,

Beginner here; I practicing working on on a responsive nav that toggles between the hamburger icon and menu on small devices and displays a regular menu once the screen width exceeds 768px (using jQuery). It works overall; however, after I click the hamburger icon and the mobile menu displays, if I expand the screen, the mobile menu is still displayed. I would like it to disappear.

Full code is https://codepen.io/srhbishop/pen/PveEGz, but here are excerpts:

HTML:

<div id="hamburger">
        <i class="fas fa-bars"></i>
    </div>
</div>
<div id="mobile-menu">
        <div id="mobile-menu-inner">
            <a href="#">Link 1</a>
            <a href="#">Link 2</a>
            <a href="#">Link 3</a>  
        </div>
 </div>
 <div id="desktop-menu">
        <a href="#">Link 1</a>
        <a href="#">Link 2</a>
        <a href="#">Link 3</a>
    </div>

CSS excerpt:

        @media only screen and (min-width: 768px) {
            #desktop-menu {
                display: flex;
                background-color: lightgray;
            }
            
            #hamburger {
                display: none;
            }
            
            #mobile-menu {
                display: none;
            }

JS code:

$(document).ready(function() {
   $("#hamburger").click(function() {
       $("#mobile-menu").slideToggle(1000);
   });
    
    if(screen.width>768) {
        $('#mobile-menu').hide();
    }
});
   $(window).resize(function() {
     if(screen.width>768) {
       $('#mobile-menu').hide();
     }
   }); 

To add to @camperextraordinaire,

you may also use $(window).width() since you’re using jQuery.

The difference is that your screen.width never changes regardless of how much your browser is open. It’s based on your screen’s actual size.

So Randell’s example would ensure all tablets and greater size screens would not see the #mobile-menu.

But if you had your desktop browser shrunk down to below 768px you would still see it.

However, if you use $(window).width(), it would cover both cases. The javascript equivalence I believe is screen.innerWidth;

So it just depends what you want to happen.

2 Likes

Ah., it’s window.innerWidth. My error.

Thank you! Randall’s solution was exactly what worked, and the explanation is super helpful.