Search code examples
htmljqueryresponsive-designmenu

Auto collapse jquery menu depending on screen size


I have created a responsive menu that can opens and collabses when i push the open menu. But the problem is that when i resize the screen it is auto opened when it hits 680 px or lower and if i then collapse the menu when i'm mobile size and try to resize it to desktop again(over 680px) the menu stays hidden.

html code

<a href="#" id="pull"><img src="assets/img/nav-icon.png" alt="Menu"></a>
<div class="bar">
    <div class="lang">
        <a href="#"><div class="langDK"></div></a>
        <a href="#"><div class="langUK"></div></a>
    </div>
    <ul class="navigation">
        <a href="#"><img src="assets/img/logo.png" alt=""></a>
        <li class="item"><a href="#">Home</a></li>
        <li class="item"><a href="#">Products</a></li>
        <li class="item"><a href="#">Work</a></li>
        <li class="item"><a href="#">About</a></li>
        <li class="item"><a href="#">Contact</a></li>
    </ul>
</div>

jquery

$(function(){
    var pull        = $('#pull');
        menu        = $('.bar .item');
        w = $(window).width();

        if(w > 680 ) {
            menu.show()
        }

        if(w < 680){
            menu.hide();
        }

        $(pull).on('click', function(e) {
            e.preventDefault();
            menu.slideToggle();
        });
});

i also have some css and media querys but dont think the problem lies there.


Solution

  • Set up the event listener for the window's resize:

    $(window).on('resize', function(){
        var menu = $('.bar .item');
        var w = $(window).width();
        if(w >= 680 ) {
            menu.show()
        }else{
            menu.hide();
        }
    })
    

    If you'd like to hide the li items by default, add the CSS class as below:

    li.item {display:none;}