Drop down menu with jQuery

March 23, 2009 | Demo | Download

The beauty of jQuery is that it turns complicated javascript functions into minimal lines of code. You really have to just love any library that cuts your working time to 2% of the time it would take you to complete the same project. The only thing you really need to think about, is what shade of blue or red to use from the menu's.

<ul id='ddmenu'>
	<li>
		<a href='http://www.codenothing.com'>Home</a>
		<ul>
			<li><a href='index.php?blog=2'>Database.php</a></li>
			<li><a href='index.php?blog=5'>PHP RSS Feed</a></li>
			<li><a href='index.php?blog=6'>Snippet: pageLinks</a></li>
		</ul>
	</li>
	<li><a href='index.php?blog=1'>About Me</a></li>
	<li>
		<a href='index.php?list=1'>Blogs</a>
		<ul>
			<li><a href='index.php?blog=4'>Snippet: encode</a></li>
			<li><a href='index.php?blog=7'>Local Server</a></li>
		</ul>
	</li>
</ul>

First you need to set up your list hierarchy. Above we have lists nested within each-other for mouse-over drop-down effect to hold. Now let's take a look at the javascript that creates the drop-down effect.

$(document).ready(function(){
	$('ul#ddmenu > li').mouseover(function(){ $(this).children('a').addClass('ddmenu-hover').siblings('ul').show(); });
	$('ul#ddmenu > li').mouseout(function(){ $(this).children('a').removeClass('ddmenu-hover').siblings('ul').hide(); });
});

I've added an extra affect that will add/remove css to the parent list links to give a better feel of what list you are looking at. Let's add the final touch of CSS to make it crisp and clean and finish this menu up.

#ddmenu {
	list-style: none;
	padding: 0;
	margin: 0;
}

#ddmenu > li {
	float: left;
}

#ddmenu > li > a {
	display: block;
	width: 100px;
	text-align:center;
	padding-top: 5px;
	padding-bottom: 5px;
	text-decoration: none;
	color: #232323;
	font-weight: bold;
	background-color: #f1f1f1;
	border: 1px solid #c5c5c5;
}

#ddmenu > li > .ddmenu-hover {
	background-color: #c5c5c5;
	border-left: 1px solid #545454;
}

#ddmenu > li > ul {
	display: none;
	list-style: none;
	position: absolute;
	z-index: 99;
	margin: -1px 0 0 0;
	padding: 0;
}

#ddmenu > li > ul > li > a {
	display: block;
	width: 100%;
	padding: 5px;
	border-bottom: 1px solid #545454;
	border-right: 1px solid #545454;
	border-left: 1px solid #545454;
	text-decoration: none;
	font-weight: bold;
	font-size: 10pt;
	color: #232323;
	background-color: #c5c5c5;
}

#ddmenu > li > ul > li > a:hover {
	background-color: #f1f1f1;
}

And now we have ourselves a working drop-down menu. I've included the demo below, as well as a zip folder containing a complete mock-up of everything in this blog.


Download

Latest: drop-down-menu.zip
Released: March 23, 2009