I have a simple WordPress theme with a sidebar menu containing main menu items and sub menu items. The menu appears on all pages. This is how the menu renders:
<li id="menu-item-55" class="menu-item "><a href="?page_id=22">Main Menu Item 1</a></li>
<li id="menu-item-120" class="menu-item "><a href="#">Main Menu Item 2</a>
<ul class="sub-menu">
<li id="menu-item-119" class="menu-item"><a href="?page_id=101">Sub Menu Item 1</a></li>
<li id="menu-item-118" class="menu-item"><a href="?page_id=104">Sub Menu Item 2</a></li>
<li id="menu-item-117" class="menu-item"><a href="?page_id=109">Sub Menu Item 3</a></li>
</ul>
</li>
<li id="menu-item-53" class="menu-item "><a href="?page_id=26">Main Menu Item 3/a></li>
I am using a simple bit of jQuery to toggle the submenu items:
$(document).ready(function() {
$("#menu-item-120").click(function() {
$('.sub-menu').slideToggle('medium');
});
});
This is basically fine for my requirements with one small problem – I need to have the sub-menus initially hidden when a page loads. Using jQuery to hide the menu items when the page has loaded causes the menus to briefly display, which is not acceptable.
To add to the problem, ideally, the submenus should always display if one of the subpages is being displayed. I’m happy to hard code in ids etc just to get things working, and would be grateful for any hints.
You should do this using CSS as suggested by Dejo Dekic. Or you can just add hide() here:
The CSS way
Here’s a hack which I can suggest for the second part :
In the header.php (where typically the menu should be defined/loaded),