Dropdown Menu Using jQuery


Learn how to spice up your navigation menu using jQuery! In this tutorial I will show you how to create a navigation menu with an animated drowndown using javascript. I will also provide a nice fallback option in case javascript is disabled on the browser.

Let’s begin the tutorial by looking at the HTML.

HTML

<div id="nav">
	<ul>
		<li>
			<a href="#">Home</a>
		</li>
		<li>
			<a href="#">About</a>
		</li>
		<li id="menu">
			<a href="#">Portfolio</a>
			<div id="dropDown">
				<a href="#">Pictures</a>
				<a href="#">Music</a>
				<a href="#">Other</a>
			</div>
		</li>
		<li>
			<a href="#">Contact</a>
		</li>
	</ul>
</div>

The HTML is pretty straightforward and I’ve placed the dropdown menu within the navigation’s portfolio section. To determine when the menu is hidden or when it is shown, we’ll have to apply css.

CSS

#nav li{
	float:left;
	list-style:none;
	margin-right:5px;
}
  
#nav a{
	padding:10px;
	text-decoration:none;
	background-color:#00B3FF;
	color:white;
}
 
#menu:hover #dropDown{
	display:block;
}

#dropDown a{
	display:block;
}
  
#dropDown{
	display:none;
	overflow-x: hidden;
	overflow-y: hidden; 
}

I’ve added some styling to make the menu prettier but feel free to customize it. I used the css that jQuery uses to hide an element with the ‘toggle’ option so that the dropdown is not displayed until you hover over the portfolio section. We’ll be using the property display:block to provide us with a nice fallback option in case javascript is disabled. It allows us to display the dropdown menu without any animation.

jQuery

jQuery(document).ready(function(){
	var maxHeight = $('#dropDown').height();
	
	$('#dropDown').css('height', '0');
	$('#dropDown').css('display', 'block');
	
	$('#menu').mouseenter(function() {
		$('#dropDown').stop().animate({height:maxHeight},{duration:400, easing: 'linear'});
	})
	$('#menu').mouseleave(function() {
		$('#dropDown').stop().animate({height:0},{duration:400, easing: 'linear'});
	})
});

I used the animate function to “animate” the dropdown, causing the dropdown tp slide down when someone hovers over the portfolio section. Initially, I was having some issues with the animation’s height when I was testing. When I hovered over the portfolio section in the middle of the dropdown’s animation, it would mess up the calculated height of the dropdown. This height issue caused future hovers to display the dropdown as if half of it was cut off. To correct the issue, I decided to use static values for the height property.

View demo here: Demo