Search code examples
javascriptjqueryhtmlcsshamburger-menu

How do I close a Hamburger Menu once an Item is clicked?


Having trouble closing the Menu after clicking the hamburger button. What's the best way to close the entire menu screen once any of the items are clicked?

My HTML is:

`<body>
  <div class="menu-wrap">
    <input type="checkbox" class="toggler">
    <div class="hamburger">
      <div></div>
    </div>
    <div class="menu">>
      <div>
        <div>
          <ul>
            <li><a href="#Home">Home</a></li>
            <li><a href="#About">About</a></li>
            <li><a href="#">Menu</a></li>
            <li><a href="#">Contact</a></li>
          </ul>
        </div>
      </div>
    </div>
  </div>`

I've tried using jQuery but havent had success. Here's the js code:

`$('.toggler').on('click', function () {
    $('.menu').toggleClass('open');
});
$('.menu li').on("click", function () {
    $('.menu-wrap').toggleClass('open');
});`

Or if there's a simpler way using CSS to close the menu?

Here's the codepen to run: https://jsfiddle.net/7rmcx861/#&togetherjs=g5zDdkhjc5


Solution

  • https://jsfiddle.net/h7et0qnv/

    this menu style work on input chechbox situation. If checked your hamburger menu get visible else get hidden . so just need to change its situation

    wrote one function in your script.

    function toggle(){
        $(".toggler").prop("checked", false);
    }
    

    then put this function to onclick event of menu list

    <li><a onclick="toggle()" href="#Home">Home</a></li>
     <li><a onclick="toggle()" href="#About">About</a></li>
     <li><a onclick="toggle()" href="#">Menu</a></li>
     <li><a onclick="toggle()" href="#">Contact</a></li>