Open and close submenu when jQuery is pressed

I have a main menu that will display submenus with the click event in jquery (the client needed to click instead of hover), so I got it working, but I still can’t understand one thing: I have a menu and the submenu working correctly, therefore, when I press “news”, the submenu slides down well, and when I press “news”, it closes, but if after opening the news submenu and I press “resources”, the corresponding submenu appears, but the news submenu remains open, I want so that the previous submenu closes when you click on another th menu item or outside the main menu area any ideas? here is 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 jquery:

  $(function(){ $('#MainMenu').find('> li').click(function(){ $(this).find('ul') .stop(true, true).slideToggle(400); return false; }); }); 
+6
source share
2 answers

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/

+7
source

Just add this line to your code

 $('#MainMenu > li').not(this).find('ul').slideUp(); 

FULL CODE

 $('#MainMenu').find('> li').click(function() { $('#MainMenu > li').not(this).find('ul').slideUp(); $(this).find('ul').stop(true, true).slideToggle(400); return false; });​ 

Check feed

+2
source

All Articles