Search code examples
javascriptjquerynavigation

Javascript that toggles sub-menu also disabling sub-menu links


I'm using the code below to toggle the the sub-menu. The toggle works great, but it disables both the parent link (a good thing) and also the sub-menu links (definitely NOT a good thing).

What do I need to do with this piece of code to have the sub-menu links remain enabled?

jQuery(document).ready(function () {
   jQuery('#menubar ul.sub-menu').hide();
    if (jQuery('.menu-item-has-children').length > 0) {
        jQuery('.menu-item-has-children').click(
        function (event) {
            jQuery(this).addClass('toggled')
            if (jQuery(this).hasClass('toggled')) {
                jQuery(this).children('ul').toggle();
            }
            return false;
        });
    }
});

and here's the menu structure:

<nav id-"menubar">
    <div class="menu-header">
        <ul id="nav" class="menu">
            <li class="menu-item"><a href="/">Home</a></li>
            <li class="menu-item menu-item-has-children">
                <a href="#">Page 2</a>
                <ul class="sub-menu">
                    <li><a href="#">A</a></li>
                    <li><a href="#">B</a></li>
                    <li><a href="#">c</a></li>
                </ul>
            </li>
        </ul>
    </div>
</nav>

Solution

  • The issue with your code lies in the return false; statement within the click event. This effectively prevents any default actions and event bubbling, which also disables the sub-menu links. To fix this, you can modify the code so that only the parent link (the one with sub-menu) is affected by the toggle behavior, while allowing the sub-menu links to remain clickable.

    So you should go like that:

    jQuery(document).ready(function () {
       jQuery('#menubar ul.sub-menu').hide();
       
        if (jQuery('.menu-item-has-children').length > 0) {
            jQuery('.menu-item-has-children > a').click(function (event) {
                event.preventDefault(); // Prevent default behavior only for parent link
                jQuery(this).siblings('ul').toggle(); // Toggle the sub-menu
            });
        }
    });