Search code examples
javascripthamburger-menu

Close hamburger menu when clicking on link or button


I am trying to make my hamburger menu close when clicking on a link inside or on the button. I am not very good at Javascript, so I kinda just put together some code I found online. However, if i add the second part of the code, it closes when clicking on the link but won't close anymore when clicking on the button. If I only leave the first part it closes when clicking on the button, but not the link.

    // Hamburger Menu

$(document).ready(function () {
  var $mainmenu = $(".main-menu"),
    $hamburger = $(".hamburger");

  $hamburger.click(function () {
    $hamburger.toggleClass("open");
    $mainmenu.toggleClass("open");
    return false;
  });


// Close Menu when click on Link

  $(".hamburger").on("click", function () {
    $(".main-menu").addClass("open");
  });

  $(".main-menu a").on("click", function () {
    $(".main-menu").removeClass("open");
  });
});

I feel like there is a simple solution, which I can't find due to my lack of knowledge. I really hope someone can help me! Thanks in advance.


Solution

  • First of all, you don't need to have a return false in your $hamburger.click function. For the future, you should specify what the button is as you really only provided classes or attach screenshots so that it's better to visualize.

    Assuming that .hamburger is your button, your code could just look like this

    $(document).ready(() => {
      var $mainmenu = $(".main-menu"),
        $hamburger = $(".hamburger");
    
      $hamburger.click(() => {
        $mainmenu.toggleClass("open");
      });
    
    // Close Menu when click on Link
      $(".main-menu a").on("click",() => {
         $mainmenu.removeClass("open");
      });
    });