Search code examples
javascripthtmlmenuresponsive-designfullscreen

How to close responsive fullscreen menu when user clicks on a link?


I have one of those responsive menus on my one-pager site which brings up a transparent fullscreen menu when the hamburger icon is clicked. The fullscreen menu closes when user clicks the close button (X) at the top right, so everything works fine. But since most of my site is one-page, all the links in the menu are also links within the same page. When user clicks one of those links, the page jumps there as intended but the transparent fullscreen menu still stays fullscreen as it is...

The menu should disappear when user clicks on a link exactly as it does when user clicks the close button. This is the problem I'm trying to solve and I'm sure it requires just a few lines of Javascript but I'm not so fluent in JS.

This is the website:

http://www.artegradesign.com

Here's the related code (maybe there's more to it, not sure):

HTML

<div class="menu-btn"></div>
<nav>
    <ul>
        <li><a href="">Home</a></li>
        <li><a href="#about">About</a></li>
        <li><a href="#work">Work</a></li>
        <li><a href="#contact">Contact</a></li>
    </ul>
</nav>

CSS

.menu-btn {
cursor: pointer;
height: 60px;
width: 60px;
display: inline;
z-index: 99;
position: absolute;
top: 2px;
right: 5%;
}
.close-btn {
position: fixed;
z-index: 100;
}
nav {
position: fixed;
top: -1600px;
left: 0;
right: 0;
background-color: rgba(0,26,51,0.95);
transition: all 0.5s;
color: white;
min-height: 100%;
z-index: 99;
}
.open {
top: 0;
}

JS

$(document).ready(function(){
$('.menu-btn').click(function(){
    $('nav').toggleClass('open');
    $(this).toggleClass('close-btn');
    $('.container').toggle();
})
})

Update: I managed to close the fullscreen menu (with the js below) when clicking on a link, but it also makes the menu button disappear entirely. So I still need a hero to bring it back!

$(document).ready(function(){
    $('nav li a').click(function(){
        $('nav').toggle();
    })
})

Thanks!


Solution

  • Seems less ideal how the click event is being handled, but because you are just looking for a toggle when you click it (for both closing and opening), you can just tie a link click in with triggering the menu click like so:

    $('nav li a').on('click', function(){
        $('.menu-btn').trigger('click');
    });
    

    I do suggest using an ID or a specific class for your nav, however. It could easily break if you added a nav element with an unordered link list anywhere else in the site.