jQuery vertical dropdown menu This code works great and does exactly as it should, but there has to be a better way of doing this and I just can't figure out how!

I'm pretty new to jQuery and am trying to use it more myself instead of using plugins and I can get stuff to work fine. It just isn't the tidiest or neatest code, which I'm trying to move away from!

I've included a fiddle here just so you can see the functionality as it currently stands.

HTML

&lt;ul&gt;
    &lt;li&gt;Example 1&lt;/li&gt;
    &lt;li class="open"&gt;Example 2
        &lt;ul&gt;
            &lt;li&gt;Sub Example 2.1&lt;/li&gt;
            &lt;li&gt;Sub Example 2.2&lt;/li&gt;
            &lt;li&gt;Sub Example 2.3&lt;/li&gt;
            &lt;li&gt;Sub Example 2.4&lt;/li&gt;
        &lt;/ul&gt;
    &lt;/li&gt;
    &lt;li class="open2"&gt;Example 3
        &lt;ul&gt;
            &lt;li&gt;Sub Example 3.1&lt;/li&gt;
            &lt;li&gt;Sub Example 3.2&lt;/li&gt;
            &lt;li&gt;Sub Example 3.3&lt;/li&gt;
        &lt;/ul&gt;
    &lt;li&gt;
&lt;/ul&gt;


jQuery

var menu = $('li.open ul');
menu.css('display','none');
     $('li.open')
     .mouseenter(function(){
          menu.slideDown(400);
     })
     .mouseleave(function(){
          menu.slideUp(400);
     });

var menu2 = $('li.open2 ul');
menu2.css('display', 'none');
    $('li.open2')
    .mouseenter(function(){
         menu2.slideDown(400);
     })
     .mouseleave(function(){
         menu2.slideUp(400);
     });
Instead of selecting .open and .open2, you could change your selector to see if there is a child &lt;ul&gt;.

$('li:has(ul)').hover(function() {
  $(this).find('ul').slideDown(400);
}, function() {
  $(this).find('ul').slideUp(400);
})


Edit: you can also hide all the child &lt;ul&gt; nodes at once instead of individually.

$('li ul').hide();


Reference

Here are the three main features of jQuery that I used. Each link uses &lt;api.jquery.com> which is a great place to learn about various jQuery functions.


:has() selector
.hover()
.find()