Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close hamburger menu after click event

I have a hamburger menu which is almost complete with just 1 bug/issue that I can't figure out. My nav links to different areas on the home page. So on the home page the user can click a nav link which would instantly take them down to the desired location on the page.

My issue comes as there is no loading so once the user clicks on the nav link they are brought to the location but the dropdown menu will not close. I tried adding .hide to the JS which hides the dropdown on the click of a link but that created my new issue.

After the user clicks one of the nav links it does hide the menu but upon clicking the menu icon again the menu will not open at all. In dev tools I see that upon clicking one of the nav links it is given the style of display:none so I feel that the issue might lie there. Thanks for the help and please let me know if any other information is needed!

HTML:

     <nav class="navbar navbar-light navbar-fixed-top">
     <div class="wrapping container-fluid">
        <div class="hamburger">
          <div class="line"></div>
          <div class="line"></div>
          <div class="line"></div>
        </div>
      <ul class="nav navbar-nav float-sm-right mr-0 menu">
        <li class="nav-item">
          <span class="sr-only"></span>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#schedule">Schedule<span class="sr-only">(current)</span></a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#workshops">Workshops</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#locations">Location</a>
        </li>
        <li class="nav-item">
          <a class="nav-link last-link" href="#register">Register</a>
        </li>
      </ul>
      <a class="navbar-brand" href="#home"><img class="logo" src="img/Logo.png" alt=""></a>
    </div>
  </nav>

CSS for this menu:

.menu{
  height: 0;
  overflow: hidden;
  transition: height 0.3s;
}

.open{
  height: 295px;
}

.hamburger {
  cursor: pointer;
  padding: 15px 10px 15px 0;
  display: block;
  float: right;
  margin-top: 15px;
}

JS:

$('.hamburger').on('click', function () {

$('.menu').toggleClass('open');

});

$( '.menu a' ).on("click", function(){
$('.menu').hide();
});
like image 321
Jack O Avatar asked Dec 18 '22 10:12

Jack O


1 Answers

If you're going to use .toggleClass('open') to open the menu, use it for closing the menu as well.

Generally, though, you'll want to use .addClass() and .removeClass() instead:

$('.hamburger').on('click', function () {
  $('.menu').addClass('open');
});

$( '.menu a' ).on("click", function(){
  $('.menu').removeClass('open');
});
like image 72
Ouroborus Avatar answered Jan 02 '23 14:01

Ouroborus