user3328557
user3328557

Reputation: 100

Show/Hide wordpress submenu

I am having some difficulty swapping the behaviour of my Wordpress menu. I am looking for it show when clicked and not when hovering:

<nav>
    <ul>
        <li>
            <?php wp_nav_menu( array( 'theme_location' => 'header-menu' ) ); ?>
        <li>
            <br />
        <form method="get" id="search_form" action="<?php bloginfo('home'); ?>">
            <input type="text" class="text searchForm" name="s" value="Search" >
        </form>
    </ul>
</nav>

jQuery(document).ready(function ($) {
    $(".sub-menu").hide();
    $(".current_page_item .sub-menu").show();
    $("li.menu-item").click(function () { // mouse CLICK instead of hover
        $(".sub-menu").hide(); // First hide any open menu items
        $(this).find(".sub-menu").show(); // display child
    });
});

When I change it to toggle it kills off the other links in the menu. I am not sure what the issue is here...

Upvotes: 3

Views: 6907

Answers (1)

Jens Kooij
Jens Kooij

Reputation: 389

You can just use the jQuery click function, instead of hover. Also you'll have to make sure the <a> tag doesn't work, by disabling the default behaviour of the hyperlink.

jQuery(document).ready(function ($) {
    $(".sub-menu").hide();
    $(".current_page_item .sub-menu").show();
    $("li.menu-item").click(function () { // mouse CLICK instead of hover
        // Only prevent the click on the topmost buttons
        if ($('.sub-menu', this).length >=1) {
            event.preventDefault();
        }
        $(".sub-menu").hide(); // First hide any open menu items
        $(this).find(".sub-menu").show(); // display child
        event.stopPropagation();
    });
});

Upvotes: 6

Related Questions