1
votes

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.

2
Can't you just hide your sub-menus using CSS {display:none} and display them using Jquery? Try api.jquery.com/slideDown - Dejo Dekic
I think @DejoDekic's suggestion would fix the first problem. For the second part, what do you mean by "the submenus should always display if one of the subpages is hidden"? - TJ-
That works - thanks very much. I have edited my original problem to correct my stupid sentence - I meant to say "the submenus should always display if one of the subpages is being displayed" - Christian Mayne

2 Answers

3
votes

You should do this using CSS as suggested by Dejo Dekic. Or you can just add hide() here:

$(document).ready(function() {
    $(".sub-menu").hide();
    $("#menu-item-120").click(function() {
        $('.sub-menu').slideToggle('medium');
    });
});

The CSS way

.sub-menu { display: none; }
0
votes

Here's a hack which I can suggest for the second part :

In the header.php (where typically the menu should be defined/loaded),

    0.v) Set a css (as above) to hide all the sub-menus by default.
    i) Check if the page is a sub-page (http://mattvarone.com/wordpress/wordpress-check-page-parent/)
    ii) If Yes, set a class in the submenu for this page to show it.
        For this, you may have to change the naming convention of ids of the sub-menu items.
       They may be named as menu-item-<PageId>. In that case you may just add this to show (only) this submenu already : $('menu-item' + currentPageId).parent().show(); <-- Submenus will be enabled via javascript.