In this article, I will introduce a simple way to display a dropdown menu using jQuery’s hover(), show(), and hide() methods.
- CSS Code for Displaying a Dropdown Menu with hover(), show(), and hide() Methods in li Tags
- JavaScript Code for Displaying a Dropdown Menu with hover(), show(), and hide() Methods
- HTML Code for Displaying a Dropdown Menu with hover(), show(), and hide() Methods
- Demo Page for Displaying a Dropdown Menu with Simple jQuery
CSS Code for Displaying a Dropdown Menu with hover(), show(), and hide() Methods in li Tags
By default, the #idMenu li ul is hidden. Change as needed.
<style type="text/css">
<!--
ul{
list-style:none;
}
#idMenu li {
position: relative;
float: left;
margin: 0;
padding: 5px;
width: 150px;
height: 20px;
border: solid 1px #cccccc;
line-height:1.4em
}
#idMenu li:hover {
color: #ffffff;
background-color:#CCCCCC;
}
#idMenu li ul {
display: none;
position: absolute;
top: 30px;
left: -1px;
padding: 5px;
width: 150px;
background-color:#999999;
border: solid 1px #cccccc;
}
#idMenu li ul li {
margin: 0;
padding: 0;
width: 150px;
border: none;
}
#idMenu li ul li a {
display: inline-block;
width: 150px;
height: 20px;
text-decoration:none;
color:#FFFFFF;
line-height:1.4em
}
#idMenu li ul li a:hover {
background-color:#999999;
color:#333333;
text-decoration:underline;
}
-->
</style>
JavaScript Code for Displaying a Dropdown Menu with hover(), show(), and hide() Methods
Load the jquery.min.js file (version 1.5 series).
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
When #idMenu li is hovered over, the ul tag is displayed with show(), and hidden with hide() on mouse out.
<script type="text/javascript">
$(function() {
$("#idMenu li").hover(function() {
$(this).children('ul').show();
}, function() {
$(this).children('ul').hide();
});
});
</script>
HTML Code for Displaying a Dropdown Menu with hover(), show(), and hide() Methods
Prepare the dropdown display area (id=”idMenu”). Change as needed.
<div id="idWrap">
<h1>Hover over "Menu 1" or "Menu 2" below to display the dropdown menu.</h1>
<ul id="idMenu">
<li>Menu 1
<ul>
<li><a href="#">Dropdown 11</a></li>
<li><a href="#">Dropdown 12</a></li>
<li><a href="#">Dropdown 13</a></li>
</ul>
</li>
<li>Menu 2
<ul>
<li><a href="#">Dropdown 21</a></li>
<li><a href="#">Dropdown 22</a></li>
<li><a href="#">Dropdown 23</a></li>
</ul>
</li>
</ul>
</div><!--/idWrap-->
Demo Page for Displaying a Dropdown Menu with Simple jQuery
Demo Page for Displaying a Dropdown Menu with Simple jQuery
There are many ways to create dropdown menus, but this method is often used when you want to keep things simple.
Please use this at your own risk if you decide to reuse it. Do not reuse the Google Analytics tag from the demo page tags.