Although this tip will work, I certainly would not recommend using it as base for more code, it is pretty inefficient and quite brittle
There are lots of really great jquery plugins that will automate all this for you.
If you really want to do this yourself, here a quick snippet that I just wrote, to try to help rather than to just be a critic It can be improved.
Here is a real simple clean xhtml layout structure. It has nested ul that reflect the semantic structure of the dropdown menus. This also allows for easy selection of child menus.
The sub menus are hidden with the class display-none which is just a wrapper around a css display:none declaration. The rest of the css is purly for layout and styling.
<style>
.dropdown-menu{width:100%;}
.dropdown-menu li{display:inline-block;
vertical-align:top;background-color:Teal;color:white;padding-bottom:5px;}
.dropdown-menu li ul li {display:list-item;
background-color:Red;color:Navy;padding-bottom:3px;}
.display-none{ display:none;}
</style>
<ul class="dropdown-menu">
<li>Menu 1
<ul class="display-none">
<li><a href="#">sub 1</a></li>
<li><a href="#">sub 2</a></li>
</ul>
</li>
<li>Menu 2
<ul class="display-none">
<li><a href="#">Sub 1</a></li>
<li><a href="#">Sub 2</a></li>
</ul>
</li>
</ul>
The jQuery again is pretty simple. I have wrapped it a closue and made it a jQuery plug-in. You do not have to do this but it provides more options for only a few extra lines of javascript.
<script type="text/javascript">
(function($) {
$.fn.DropDownMenu = function(options) {
return this.each(function() {
var $dropdownmenu = $(this);
$(">li", $dropdownmenu).mouseover(function() {
var $menuItem = $(this);
$("ul", $menuItem).stop().slideDown("slow");
}).mouseout(function() {
var $menuItem = $(this);
$("ul", $menuItem).stop().slideUp("slow");
});
});
};
})(jQuery);
</script>
To initalise the menu, use a document.ready event on you page.
<script type="text/javascript">
$(function() {
$(".dropdown-menu").DropDownMenu();
});
</script>
The nice this is that becuase this is a plugin, if we have multiple dropdown menus we can given them both the css class dropdown-menu and with this one call they will both be initalised