jQuery toggle another element on the same level

I have a collapsible Hamburger mobile menu that I am working on for a website. I'm inserting a simple div (with an up and down arrow symbol) to expand the children list. When I click the Arrow, it unfolds or collapses the list as intended for each acroding menu link, but if I want to apply the same click effect for the menu link directly, it unfold all the child lists from all the menu links.

Here is the code:

(function($) {
    function setup_collapsible_submenus() {
        $( "<div class='sub-menu-toggle'></div>" ).insertBefore( "#main-header #mobile_menu.et_mobile_menu .menu-item-has-children > a" );

        $( "#main-header #mobile_menu.et_mobile_menu .menu-item-has-children > a" ).off('click').click(function () {
            $(this).attr('href', '#'); 
            $("#main-header #mobile_menu.et_mobile_menu .sub-menu-toggle").toggleClass("popped");
        });

        $( "#main-header #mobile_menu.et_mobile_menu .sub-menu-toggle" ).click(function () {
            $(this).toggleClass("popped");
});
    }

    $(document).ready(function() {
        setup_collapsible_submenus();
    });
    $(window).load(function() {
        setup_collapsible_submenus();
});

})(jQuery);

How can I fix this line:

$( "#main-header #mobile_menu.et_mobile_menu .menu-item-has-children > a" ).off('click').click(function () {
            $(this).attr('href', '#'); 
            $("#main-header #mobile_menu.et_mobile_menu .sub-menu-toggle").toggleClass("popped");
        });

1 answer

  • answered 2020-01-24 11:36 user1286956

    Ah, the answer was a bit tricky:

    $(this).parent().children().toggleClass("popped");
    

    instead of:

    $("#main-header #mobile_menu.et_mobile_menu .sub-menu-toggle").toggleClass("popped");