Search code examples
jquerycssjquery-animateeasing

jQuery - CSS dropdown multilevel menu animation


I have standard multi-level menu like this one:

<ul id="nav">
    <li><a href="#">Home</a></li>
    <li><a href="#">Dropdown</a>
       <ul class="sub-menu">
           <li><a href="#">Link #1</a></li> 
           <li><a href="#">Link #2</a></li>  
           <li><a href="#">Link #3</a></li>            
       </ul>
    </li>    
</ul>

Source: http://jsfiddle.net/Dg2Cb/

I want to animate sub-menus height like on this page (looks like jswing effect): http://themes.truethemes.net/Karma/

Is there any easy (not messy like in example above) way of achieving this?

Here's the best effect I've managed to create (but it still looks bad as it renders width too): http://jsfiddle.net/Dg2Cb/1/

I can use jQuery easing plugin, but would love to do that without any plugins. I know how to animate height of an element, but the tricky part is I have to change its visibility and animate it at the same time.


Solution

  • Animate both the height, and the opacity together:

    $("#nav > li").on("mouseenter mouseleave", function(e){
      e.type === "mouseenter" 
        ? $(".sub-menu", this).stop().animate({ height:'toggle', opacity:1 }, 250)
        : $(".sub-menu", this).stop().animate({ height:'toggle', opacity:0 }, 250) ;
    });​
    

    Additionally, don't set .sub-menu to visibility:hidden - instead, set to display:none.

    Fiddle: http://jsfiddle.net/Dg2Cb/6/