open and close submenus on click Jquery

javascript, jquery, menu

Solution

Try something like this

$(function() {
    $('#MainMenu > li').click(function(e) { // limit click to children of mainmenue
        var $el = $('ul',this); // element to toggle
        $('#MainMenu > li > ul').not($el).slideUp(); // slide up other elements
        $el.stop(true, true).slideToggle(400); // toggle element
        return false;
    });
    $('#MainMenu > li > ul > li').click(function(e) {
        e.stopPropagation();  // stop events from bubbling from sub menu clicks
    });
});​

http://jsfiddle.net/Ssu32/

Problem

I have a main menu that will display the submenus with a click event in jquery (client wanted to be click instead hover) so I got it working however I still can't figure out one thing: I have the menu and submenus working properly so when I click on "news" the submenu slides down nicely and when I click back on "news" it closes back, however if after openening news' submenu and I click on "resources" the respective submenu appears but news' submenu stays open, I want the previous submenu to close when clicking on another menu item or outside the main menu area any ideas? here's what I got: ``` <ul id="MainMenu"> <li><a href="#">Home</a></li> <li><a href="#">About Us</a></li> <li> <a href="#">News</a> <ul class="noJS"> <li><a href="#">sub menu 1</a></li> <li><a href="#">sub menu 2</a></li> <li><a href="#">sub menu 3</a></li> <li><a href="#">sub menu 4</a></li> <li><a href="#">sub menu 5</a></li> <li><a href="#">sub menu 6</a></li> </ul> </li> <li><a href="#">Jobs</a></li> <li><a href="#">Contact Us</a></li> <li><a href="#">Admin</a></li> <li> <a href="#">Resources</a> <ul class="noJS"> <li><a href="#">sub menu 1</a></li> <li><a href="#">sub menu 2</a></li> <li><a href="#">sub menu 3</a></li> <li><a href="#">sub menu 4</a></li> <li><a href="#">sub menu 5</a></li> <li><a href="#">sub menu 6</a></li> </ul> </li> <li class="lastChild"><a href="#">New Button</a></li> </ul> ``` and the jquery: ``` $(function(){ $('#MainMenu').find('> li').click(function(){ $(this).find('ul') .stop(true, true).slideToggle(400); return false; }); }); ```

Original source