Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
dead-simple dropdown menus with jquery
jQuery.fn.dropdown = function() {
var menu = $(this);
var ddm = 0;
menu.find('li ul').hide();
menu.find('li').bind('mouseover', function() {
ddm = $(this).find('ul li').unbind('mouseout');
ddm = $(this).find('ul').stop().show();
ddm.prev().addClass('on');
}).bind('mouseout', function() {
if(ddm) {
ddm.animate({opacity:1.0},500).hide();
menu.children().children('a').removeClass('on');
}
});
$(ddm).find('li ul li a').each(function() {
elem = $(this);
w = elem.parent().parent().parent().width();
if(elem.parent().parent().width() < w) {
elem.css('width', w + 'px');
}
});
}
$(function() {
$('#nav').dropdown();
});
<ul id="nav">
<li><a href="#">Menu Item 1</a>
<ul>
<li><a href="#">Sample Link 1</a></li>
<li><a href="#">Sample Link 2</a></li>
<li><a href="#">Sample Link 3</a></li>
</ul>
</li>
<li><a href="#">Menu Item 2</a>
<ul>
<li><a href="#">Sample Link 1</a></li>
<li><a href="#">Sample Link 2</a></li>
<li><a href="#">Sample Link 3</a></li>
</ul>
</li>
<li><a href="#">Menu Item 3</a>
<ul>
<li><a href="#">Sample Link 1</a></li>
<li><a href="#">Sample Link 2</a></li>
<li><a href="#">Sample Link 3</a></li>
</ul>
</li>
</ul>
#nav {
background:#ddd;
border-bottom:1px solid #aaa;
height:30px;
line-height:30px;
margin:0;
padding:0 10px;
}
#nav li {
float:left;
list-style:none;
width:auto;
}
#nav li a {
background:#ddd;
border-right: 1px solid #aaa;
color: #aaa;
display:block;
height:30px;
line-height:30px;
padding: 0 10px;
text-decoration:none;
width:auto;
white-space:nowrap;
}
#nav li a:hover {
background-color:#ccc;
color:#000;
}
#nav li ul {
border-top:1px solid #aaa;
padding:0;
position:absolute;
margin:0;
}
#nav li ul li {
display:inline;
float:none;
}
#nav li ul li a {
background: #555;
border-top:1px solid #eee;
color:#fff;
padding-left:10px;
width:auto;
}
#nav li ul li a:hover {
background: #aaa;
color:#fff;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment