How to make a multilevel navigation Menu using CSS & jQuery

Web programming topics
Post Reply
User avatar
Saman
Lieutenant Colonel
Lieutenant Colonel
Posts: 828
Joined: Fri Jul 31, 2009 10:32 pm
Location: Mount Lavinia

How to make a multilevel navigation Menu using CSS & jQuery

Post by Saman » Fri Jul 15, 2011 11:10 pm

The result is something like this:
menu.png
menu.png (5.75 KiB) Viewed 2981 times
The only thing you have to do is to create nested &ltul> lists into a main list with id="nav", in this way:

Code: Select all

<ul id="nav">
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a>
	<ul>
		<li><a href="#">Link 3.1</a></li>
		<li><a href="#">Link 3.2</a></li>
	<ul>
</li>
</ul> 
Use this basic CSS code (you have to modify it to customize the layout of this menu with the style of your site.

Code: Select all

#nav, #nav ul{
margin:0;
padding:0;
list-style-type:none;
list-style-position:outside;
position:relative;
line-height:26px;
}
 #nav a:link, 
 #nav a:active, 
 #nav a:visited{
display:block;
color:#FFF;
 text-decoration:none;
background:#444;
height:26px;
line-height:26px;
padding:0 6px;
 margin-right:1px;
}
#nav a:hover{
background:#0066FF;
color:#FFF;
}
#nav li{
 float:left;
 position:relative;
}
#nav ul {
 position:absolute;
width:12em;
top:26px;
 display:none;
}
#nav li ul a{
 width:12em;
float:left;
}
#nav ul ul{
width:12em;
top:auto;
} 
#nav li ul ul {margin:0 0 0 13em;}
#nav li:hover ul ul, 
#nav li:hover ul ul ul, 
#nav li:hover ul ul ul ul{display:none;}
#nav li:hover ul,
#nav li li:hover ul, 
#nav li li li:hover ul, 
#nav li li li li:hover ul{display:block;}
This is the JavaScript code for jQuery you have to copy in the tag <head> of the pages that use this menu.

Code: Select all

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
function showmenu(){
	$("#nav li").hover(function(){
		$(this).find('ul:first').css({visibility:"visible", display:"none"}).show();
	}, function(){
		$(this).find('ul:first').css({visibility:"hidden"});
	});
}
 
$(document).ready(function(){     
	showmenu();
});
</script>
Post Reply

Return to “Web programming”