Very Simple jQuery Drop Down Menu Tutorial
As the title of this article states, we are going to build a very simple and clean drop down menu using jQuery, XHTML and CSS.
Here the example of what we are going to be building.
Components:
Let's start with looking at the components of the menu. In this case we have 3 of them - xHTML, CSS and jQuery.
- xHTML Markup.
Basic xHTML markup that will be displayed as regular bullet list if used without CSS. - Set of CSS rules.
This is what makes the menu look pretty. - jQuery.
We are using jQuery to make the menu interactive.
Putting everything together:
Now, when we know what we will be working with, it's time to put everything together. We will start with adding the xHTML markup to our page.
<ul id="jmenu">
<li>
Item 1
<ul class="secondary-jmenu">
<li>Subitem 1</li>
<li>Subitem 2</li>
<li>Subitem 3</li>
</ul>
</li>
<li>
Item 2
</li>
<li>
Item 3
</li>
</ul>
Now let's add a little bit of styling. Adding CSS rules is very import in our case, as bullet list is not exactly a menu that we are looking for, so using CSS we will add a button-like look for our list items.
#jmenu ul {
display: none;
}
#jmenu li {
background:none repeat scroll 0 0 #CCCCCC;
border:1px solid #EFEFEF;
color:#555555;
cursor:pointer;
display:block;
float:left;
font-family:Verdana;
font-size:20px;
font-weight:bold;
padding:10px;
position:relative;
text-shadow:1px 1px 1px #FFFFFF;
}
#jmenu .secondary-jmenu {
left:-41px;
position:absolute;
top:45px;
display: none;
}
.secondary-jmenu li {
font-size: 12px !important;
width: 97px;
}
.selected
{
color: white !important;
background: #666 !important;
}
And finally here comes the spice - jQuery code. We need it to be able to dynamically display certain parts of the menu and hide the other ones based on user behavior. This piece of code will go into you JavaScript file or <script> tag in your header.
$(document).ready(function() {
$('#jmenu').find('li').mouseenter(function() {
$(this).children('ul').show();
$(this).addClass('selected');
$(this).mouseleave(function() {
$(this).children('ul').hide();
$(this).removeClass('selected');
});
});
});
This is pretty much it. Enjoy your brand new menu
Download source code:
You can also download complete source code of this tutorial.
