JQuery: I need to customize hide () function to toggle

I have a simple menu / submenu with jquery click () and toggle () function. My problem: toggle () works fine, but when for example # submenu1 is open and I press "Menu 2" # submenu1 remains visible of course and both submenus overlap. So I need a straight line () for the submenu, but I don't understand how it works! I have not tried () siblings () without success. Any help is appreciated! Thanks in advance.

JQuery

$('#menu li').click(function() {
$('div', this).stop(true, true).animate({ 'height': 'toggle' }, 300);
 });

      

HTML:

<ul id="menu">
   <li><a href="#">Menu 1</a>
       <div id="submenu1">
           <ul>
              <li>Submenu 1</li>
           </ul>
       </div>
   </li>
   <li><a href="#">Menu 2</a>
       <div id="submenu2">
           <ul>
              <li>Submenu 2</li>
           </ul>
       </div>
   </li>
</ul>

      

CSS

#submenu1, #submenu2 {
z-index: 99;
position: absolute;
background: #6fb700;
display: none;
}

      

+3


source to share


4 answers


Try it: http://jsfiddle.net/D9pq8/



$('#menu li').click(function () {
   $(this).siblings().children('div').hide();
   $('div', this).stop(true, true).animate({ 'height': 'toggle' }, 300);
});

      

+1


source


try it

Edit To shorten the version

$("#menu li").click(function() {
    if($('div' , this).css('display') != 'block')
            $("#menu li div.active").hide().removeClass('active');

      $('div', this).addClass('active').stop(true, true).animate({ 'height': 'toggle' }, 300);  
});

      



Sample script

This is your fiddel example

0


source


Try it with jquery tabs. Main menus in vertical mode and submenus in default EX mode: user interface tabs

0


source


Extending what @silagy posted:

 $('#menu li').click(function() {
     $("#menu li div.active").hide().removeClass('active');
    $('div', this).addClass('active').stop(true, true).animate({ 'height': 'toggle' }, 300);
});

      

This just adds the "active" class, so there is no duplicate animation of the menu item.

0


source







All Articles