I have a WordPress site with a menu in the sidebar. I am trying make the “sub-menu” part toggle. The toggle works, however it is toggling the sub-menu when the sub-menu items themselves are clicked not just the parent and therefore the links for the sub-menu items aren’t working.
This is the jQuery code:
jQuery(document).ready(function(){
jQuery('#sidebar .menu .sub-menu').hide();
jQuery('li.menu-item-has-children').click(function() {
jQuery(this).find('.sub-menu').toggle();
return false;
});
});
And this is the HTML (I’m trying to toggle the “ul.sub-menu” part):
<aside id="sidebar">
<div id="nav_menu-6" class="widget widget_nav_menu"><h3>Athletics</h3>
<div class="menu-athletics-container">
<ul id="menu-athletics" class="menu">
<li id="menu-item-641" class="menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-32 current_page_item menu-item-641"><a href="http://web2.gradelink.com/747/athletics/">Athletics</a></li>
<li id="menu-item-664" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-664 parent"><a href="#">Sports</a>
<ul class="sub-menu" style="display: none;">
<li id="menu-item-665" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-665"><a href="http://web2.gradelink.com/747/athletics/baseball/">Baseball</a></li>
<li id="menu-item-666" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-666"><a href="http://web2.gradelink.com/747/athletics/basketball/">Basketball</a></li>
<!-- ... -->
</ul>
</li>
<li id="menu-item-675" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-675"><a href="http://web2.gradelink.com/747/athletics/athletic-forms-resources/">Athletic Forms & Resources</a></li>
<!-- ... -->
</ul>
</div>
</div>
</aside>
Turns out that since the li element was waiting for the click, it applied to the entire element:
li Parent Object: Inspect Element selection
I fixed it by applying the click to the link itself, and then using parent and children to backtrack and toggle the sub-menu.
You may use
children
to select any child element with desired class: