Search code examples
jqueryjquery-uimenusubmenu

Onclick show submenu but hide other submenu(s)


I am using jQuery UI menu widget to have header navigation on my pages

here is a mock up http://jsfiddle.net/ctL6T/1/

My issue is i want to close any other shown submenus if another main menu is clicked, you can see in my fiddle if you click one main stub, the submenu stays open if you click another main stub

i thought by using an $.each on the click event, i could by using the same code that toggles iterate through the elements and flip them back and forth, but this opens the opposite menu

        $('.has-sub').on('click', function(){
            $('#mainmenu li').each(function () {
                $(".submenu" ).toggle();
            });
            $(this).toggleClass('ui-state-active').children('span').toggleClass('ui-icon-triangle-1-s ui-icon-triangle-1-n');
            return false;
         });

and this is just a mess

 $('.has-sub').on('click', function(){
$('#mainmenu li').each(function () {
  $(".submenu" ).toggle();
  $(this).toggleClass('ui-state-active').children('span').toggleClass('ui-icon-triangle-1-s ui-icon-triangle-1-n');
});
return false;
 });

as always any help is appreciated

*due to flashing of unstyled content, i decided to have the main menu as static html using some jquery ui theme classes, it should not effect the functionality of what im asking


Solution

  • Try this:

    $(function() {
    
                $( ".submenu" ).menu({
                    position: {at: "left bottom"},
                    icons: { submenu: "ui-icon-triangle-1-s" }
                });
                $('.has-sub').on('click', function(){
                    $(this).next(".submenu").toggle();
                    $(this).toggleClass('ui-state-active').children('span').toggleClass('ui-icon-triangle-1-s ui-icon-triangle-1-n');
                    $('.has-sub').not($(this)).each(function(){
                       $(this).next(".submenu").hide();
                        $(this).removeClass('ui-state-active');
                    });
                    return false;
                    });     
    });
    

    jsFiddle: http://jsfiddle.net/ctL6T/6/