Pending
Pending

Reputation: 97

Close jQuery responsive menu onclick of menu item?

I have a simple open/close responsive menu that uses jQuery. The menu works just fine but the website I'm using it on is a simple single page site with different sections. My problem is the menu opens and closes when the user clicks the menu handle and I'd like it to close when the user clicks on a menu item also. I have very little experience in jQuery so I need help solving this problem.

The HTML:

  <nav>
    <ul>
      <a href="#home"><li>home</li></a>
      <a href="#about"><li>about</li></a>
      <a href="#contact"><li>contact</li></a>
    </ul>
    <div class="handle">Menu</div>
  </nav>

The jQuery:

$('.handle').on('click', function(){
  $('nav ul').toggleClass('showing');
});

Thank you.

Upvotes: 2

Views: 201

Answers (2)

Sampgun
Sampgun

Reputation: 2977

I think you need this:

$('.handle').on('click', function(){
  $('nav ul').toggleClass('showing');
});
$('nav ul a').on("click", function(){
    $('nav ul').removeClass('showing');
});

I also noticed your HTML structure is wrong... The <li> should be child of <ul>

 <nav>
     <ul>
         <li><a href="#home">home</a></li>
         <li><a href="#about">about</a></li>
         <li><a href="#contact">contact</a></li>
     </ul>
     <div class="handle">Menu</div>
 </nav>

Working fiddle ==> https://jsfiddle.net/osd4nn1n/

Upvotes: 2

illmortem
illmortem

Reputation: 103

You can change the toggleClass to just toggle to hide the elements. To get the behavior you'd like, change your jQuery selector to:

$('.handle, nav ul a').on('click', function(){
  $('nav ul').toggle();
});

Upvotes: 1

Related Questions