Search code examples
javascriptjqueryhtmlcssnav

Close nav overlay when link is clicked (one pager)


On the mobile version of my site, I have a hamburger icon that opens a full-screen overlay when clicked using javascript. The links are anchor links, since it's a one page website. When one of the links is clicked, the overlay remains open when I want the overlay to close.

The problem I believe I am running into is because I have jQuery code set up so there is a smooth scroll effect when one of these links is clicked. This works flawlessly, however the overlay stays open.

So the openNav/closeNav is set up with javascript, and the scroll effect is set up with jQuery. I'm having difficulties figuring out how to go about this.

Here's my HTML:

<div id="mobile-navbar">
    <img class="open-nav" src="img/open-nav.png" onclick="openNav()">
    <a href="#1"><img class="logo-mobile" src="img/logo-mobile.png" alt=""></a>
    <div id="myNav" class="overlay">
        <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
        <div class="overlay-content">
            <a href="#1">ABOUT</a>          
            <a href="#2">RIDING AREAS</a>
            <a href="#3">FACILITY</a>
            <a href="#4">PRICING AND SERVICES</a>
            <a href="#5">CONTACT</a>
        </div>
    </div>
</div>

Here's the Javascript (used to open/close the nav):

function menu(x) {
   x.classList.toggle("change");
   }
   function openNav() {
        document.getElementById("myNav").style.height = "100%";
    }
    function closeNav() {
        document.getElementById("myNav").style.height = "0%";
    }

And here's the jQuery (for the smooth scroll):

$(document).ready(function(){
  $("a").on('click', function(event) {
    if (this.hash !== "") {
      event.preventDefault();
      var hash = this.hash;
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){
        window.location.hash = hash;
      });
    }
  });
});

Solution

  • You could add onclick="closeNav();" to all of your links.