CharlyAnderson
CharlyAnderson

Reputation: 737

Close toggle when clicking navigation link

Currently, the toggle opens correctly and applies an 'open' css to the navigation when clicked. However, I cannot get the script to remove the class when you click on a menu item.

Usually this wouldn't be an issue but this menu is being used to scroll to anchor tags within one page, so needs to close once clicked.

Here is my basic markup:

$(document).ready(function(){
    $("a.toggle").click(function(){
        $("nav > ul").slideToggle(500);
        $(this).toggleClass("open");
    });
});

HTML

<nav id="main">
    <a href="#" class="toggle"></a>
    <ul>
        <li><a href="#">Example Link 1</a></li>
        <li><a href="#">Example Link 1</a></li>
        <li><a href="#">Example Link 1</a></li>
        <li><a href="#">Example Link 1</a></li>
    </ul>
</nav>

Upvotes: 0

Views: 1361

Answers (2)

Phani Kumar M
Phani Kumar M

Reputation: 4590

You can attach click event to the menu item to toggle display of main menu. Hope this is what you are looking for.

$("#main ul li a").click(function () {
    $("nav > ul").slideToggle(500);
    $("a.toggle").toggleClass("open");
});

$(function () {
  $("a.toggle").click(function () {
	$("nav > ul").slideToggle(500);
	$(this).toggleClass("open");
  });

  $("#main ul li a").click(function () {
	$("nav > ul").slideToggle(500);
	$("a.toggle").toggleClass("open");
  });
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<nav id="main">
<a href="#" class="toggle">Home</a>
<ul>
  <li><a href="#">Example Link 1</a></li>
  <li><a href="#">Example Link 1</a></li>
  <li><a href="#">Example Link 1</a></li>
  <li><a href="#">Example Link 1</a></li>
</ul>
</nav>

Upvotes: 1

Enmanuel Jimenez
Enmanuel Jimenez

Reputation: 1

you have to look if you have to look if you have the latest version of jquery, if it does not use addclass and remoeclass instead of toggleclass

Upvotes: 0

Related Questions