Search code examples
jqueryaccordionslidetoggle

jQuery slide toggle, close others wherever accordion type?


I've a simple slide toggle for an accordion type menu.

If an li has the class .menu-item-has-children then clicking will slide open the .sub-menu which resides within that li:

  $(".menu-item-has-children").unbind('click').click(function(){    
        $(".menu-item-has-children > a").toggleClass("sub-open");
        $(this).children(".sub-menu").slideToggle();
  });

How do I make it that if another class with menu-item-has-children is clicked, it closes the one I've previously opened an opens the one I've just clicked.

So essentially an accordion, that closes one that is already collapsed/open before opening the new one. But these might appear elsewhere within the page, not with the same list for example.


Solution

  • You can slideUp() child menus of other menu-item elements.

    $(".menu-item-has-children").unbind('click').click(function(){  
        //Find other menu items 
        var otherMenuItems = $(".menu-item-has-children").not($(this));
    
        //Find children and perform Slideup sub-menus and remove sub-open class
        otherMenuItems.children(".sub-menu").slideUp();
        otherMenuItems.children("a").removeClass("sub-open");
    
        $(this).children("a").toggleClass("sub-open");
        $(this).children(".sub-menu").slideToggle();
    });