michaelmcgurk
michaelmcgurk

Reputation: 6509

Hide/Show sub menu

I'd like to use jQuery to hide/show a sub menu.

So initially 'Projects' would only be visible. When clicked, it would show the submenu.

I have attached my current HTML code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="menu-primary-menu-container">
    <ul id="menu-primary-menu" class="menu">
        <li id="menu-item-27" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-27"><a href="#">Projects</a>
<ul>
	<li id="menu-item-26" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-26"><a href="/category/projects/residential/">Residential</a></li>
	<li id="menu-item-24" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-24"><a href="/category/projects/private/">Private</a></li>
</ul>
</li>
    </ul>
</div>

Here is my demo: http://jsfiddle.net/76Lr33ap/

Upvotes: 2

Views: 1882

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115212

You can bind click() event handler to the a

$('#menu-primary-menu>li>a').click(function() {
  $(this).next().toggle();
  // if there is any other element after a the  use
  // $(this).parent().find('ul').toggle();
  // also if you need any better effect then use
  // slideToggle() or fadeToggle instead of toggle()
});
#menu-primary-menu>li>ul {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="menu-primary-menu-container">
  <ul id="menu-primary-menu" class="menu">
    <li id="menu-item-27" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-27"><a href="#">Projects</a>
      <ul>
        <li id="menu-item-26" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-26"><a href="/category/projects/residential/">Residential</a>
        </li>
        <li id="menu-item-24" class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-24"><a href="/category/projects/private/">Private</a>
        </li>
      </ul>
    </li>
  </ul>
</div>

Upvotes: 5

Related Questions