hide menus that aren’t currently selected

I have a menu with headings. When a heading is clicked, the child menu items will open. I would like to show only the menu that has most recently been clicked. If heading_practice is clicked, and other menus are open, they will slideToggle close. How can I do this?

<div id="pageHeadings">
    <div id="heading_practice">                     
        <a href="#">
           <p>Practice Areas</p>
        </a>
        <div class="menu_practice">
           <p>test</p>
           <p>test2</p>
        </div>
    </div>
    <div id="heading_about">                        
        <a href="#">
           <p>About</p>
        </a>
        <div class="menu_about">
           <p>test</p>
           <p>test2</p>
        </div>
    </div>
 </div>

$("#pageHeadings div[class^=menu]").hide();

$("#pageHeadings div[id^=heading]").click(function () { 
    if(!$(this).find('[class^=menu]').is(":visible")) {
        $(this).find('[class^=menu]').slideToggle("fast");      
    }

    //if element is clicked, hide all other menus
});

Fiddle

Answer

You probably want to perform a slideUp on all the other elements. This can be achieved like so:

$("#pageHeadings div[id^=heading]").click(function () {
    var $menu = $(this).find('[class^=menu]');

    if ( ! $menu.is(":visible") ) {
        $menu.slideToggle("fast");      
    }

    $('[class^=menu]').not($menu).slideUp("fast");
});

Leave a Reply

Your email address will not be published. Required fields are marked *